Asynchronism (Message Queues, Task Queues, Back Pressure)¶
Why async?¶
Asynchronous workflows reduce request times for expensive operations that would otherwise run in-line. They also let you do time-consuming work in advance (e.g., periodic aggregation).
Message Queues¶
Message queues receive, hold, and deliver messages. Workflow:
- Application publishes a job to the queue and notifies the user of job status.
- A worker picks up the job, processes it, and signals completion.
The user isn't blocked; the job runs in the background. The client may do a small amount of work to make it look complete (e.g., a tweet appears on your timeline immediately, but takes time to reach all followers).
Queue tech options:
- Redis — simple message broker, but messages can be lost.
- RabbitMQ — popular, but requires the AMQP protocol and managing your own nodes.
- Amazon SQS — hosted, but can have high latency and at-least-once delivery (possible duplicate messages).
Task Queues¶
Task queues receive tasks + data, run them, and deliver results. Support scheduling and background computationally-intensive jobs.
- Celery — supports scheduling; primarily Python.
Message queue = move messages between services. Task queue = execute work and return results. A task queue often uses a message broker underneath.
Back Pressure¶
If queues grow too large, they can exceed memory → cache misses, disk reads, and slower performance.
Back pressure limits queue size to keep high throughput and good response times for jobs already queued:
- When the queue fills, clients get "server busy" or HTTP 503, to retry later.
- Clients retry with exponential backoff.
Disadvantages of asynchronism¶
- Inexpensive calculations and real-time workflows may be better synchronous — queues add delay and complexity.
Key takeaways¶
- Async trades immediate consistency for responsiveness and scalability.
- Always pair unbounded queues with back pressure to avoid cascading failures.
- Choose a queue for delivery semantics: Redis (fast, lossy), RabbitMQ (robust, self-managed), SQS (managed, at-least-once).
Design a Web Crawler¶
A web crawler starts from a set of seed URLs and repeatedly fetches pages, extracts links, and stores content for later search or analysis. The core design challenge is balancing aggressive parallel fetching against politeness to the sites being crawled, while avoiding duplicate work and keeping the crawl scalable.
URL frontier — a persistent, prioritized queue of URLs waiting to be fetched. It is not a simple FIFO: it groups URLs by domain (so workers don't hit one site too hard) and supports priorities (so important pages are fetched first). It also acts as back pressure — when URLs are discovered faster than they're drained, admission control prevents memory exhaustion.
Fetch workers — pull URLs from the frontier, resolve DNS, and issue HTTP
requests. They (1) fetch and cache robots.txt to respect disallowed paths,
(2) enforce a minimum delay between requests per domain (with per-domain queues
so one slow site can't starve the others), and (3) use timeouts, retries with
exponential backoff, and per-domain rate limits to look like a well-behaved
client rather than an attack.
Parser — extracts and normalizes outbound links (removing fragments, resolving relative URLs, canonicalizing hosts and paths). It deduplicates aggressively: a Bloom filter gives a memory-efficient "seen before?" test (occasional false positives are acceptable; the frontier and storage keep the authoritative seen set). Content fingerprints/shingling avoid re-indexing identical content under different URLs.
Storage — decoupled: raw HTML goes into a distributed object store, while typed metadata (URL, status, title, canonical link, fetch time) goes into a queryable database for indexing and future recrawls.
Scaling — built from stateless workers, with the frontier backed by a distributed queue (e.g. Kafka) so many fetchers/parsers consume work independently. The seen-set and robots cache are shared services; the crawl is partitioned by domain or URL hash. Coordination is required so workers can't bypass the global per-domain politeness limit.
Trade-offs — freshness vs. load, and completeness vs. cost. A fast crawler can
overwhelm sites; an overly polite one may never keep up. Prioritize robustness,
deduplication, robots.txt respect, and domain-level fairness, scaling out with
queues, caches, and distributed workers rather than one fast machine.
flowchart LR
F[(URL Frontier)] --> W[Fetcher]
W -->|robots.txt + politeness| T[Target site]
W --> P[Parser]
P -->|new links| F
P -->|dedup| B[Bloom Filter]
P --> S[(Object store + metadata DB)]
Common Interview Questions¶
Design a web crawler
Why it's asked here: crawlers are built on queues and async workers.
Key points to discuss:
- URL frontier (a queue) with priorities; dedup via a Bloom filter.
- Workers fetch asynchronously; respect robots.txt and per-domain rate limits.
- A message queue (Kafka) for the URL stream; a task queue for parsing jobs.
- Back pressure when the frontier grows faster than workers drain it.
flowchart LR
F[(URL frontier)] --> W[Fetch workers]
W --> P[Parser]
P -->|new URLs| F
P -->|dedup| B[Bloom filter]
P --> S[(Index store)]
Design a notification system
Why it's asked here: notifications are a classic async fan-out.
Key points to discuss:
- Producers enqueue notifications; workers deliver via push/email/SMS.
- A message queue decouples senders from delivery (reliability, retries).
- Back pressure and rate limiting to avoid overwhelming downstream providers.
- At-least-once vs exactly-once delivery semantics.
flowchart LR
P[Producer] --> Q[(Message queue)]
Q --> W1[Push worker]
Q --> W2[Email worker]
Q --> W3[SMS worker]
W1 & W2 & W3 --> U[User]
Design Mint.com (financial aggregation)
Why it's asked here: Mint aggregates account data asynchronously.
Key points to discuss:
- Periodically pull account data via scheduled background jobs.
- Task queues (Celery) for scraping/aggregating transactions.
- Categorize asynchronously and cache results.
- Notify the user when async jobs complete.
flowchart LR
S[Scheduler] --> Q[(Task queue)]
Q --> W[Scrape / aggregate worker]
W --> A[(Accounts DB)]
A --> C[Async categorizer]
C --> N[Notify user]
Further reading¶
Design a Web Crawler's Fetching Layer¶
A fetching layer is the part of the crawler that takes normalized URLs from the frontier and retrieves the actual bytes from the web. Its functional requirements are to resolve a URL to an IP address, open an HTTP or HTTPS connection, download the response within a timeout, enforce politeness per host, respect robots.txt, handle redirects and error codes, apply retries with exponential backoff, and emit the fetched document or failure result to the parsing pipeline. The non-functional requirements are high throughput, bounded queue size, predictable per-domain latency, fairness across domains, and resilience to slow or failing sites. For planning, assume the crawler must fetch about 10 billion pages over a 30-day crawl, which is roughly 3,900 pages per second sustained. If peak load is two to three times average, the fetching layer should handle about 10,000 fetches per second. With an average response body of 20 KB, raw content volume is about 200 TB per crawl, not counting compressed transfer or metadata; the frontier and robots cache are much smaller but must support millions of pending URLs and hosts.
The high-level architecture separates scheduling, connection handling, and response capture. A scheduler reads from the distributed URL frontier and assigns each URL to a per-domain queue. Per-domain queues enforce politeness by ensuring each host is contacted no faster than its configured crawl delay, and they allow many slow domains to progress without one hot domain starving others. A pool of stateless fetch workers consumes these queues. Each worker first checks a shared robots cache and only proceeds if the path is allowed. It then resolves DNS through a caching resolver, uses a connection pool keyed by destination host, and sends the request through an optional forward proxy if the operator needs egress control or IP isolation. The worker enforces timeouts on connection, headers, and body, applies retries for transient failures such as connection reset or 5xx, and returns a fetch result containing the final URL, status, headers, body, and timing data. A response receiver marshals that result to a parsing worker and records fetch metrics for host health and crawl progress.
The data model is centered on queued URLs and per-host control state. The URL frontier stores each URL with its priority, schedule time, host, retry count, and discovery time. Per-domain state holds the domain name, crawl delay from robots.txt, last fetch timestamp, current token-bucket state, host health status, and a robots fingerprint. The seen set and frontier share canonical URL hashes to prevent duplicate fetching. Fetch results are stored separately from raw HTML: metadata such as URL, status, redirect chain, fetch timestamp, and content hash goes into an append-heavy data store, while the raw response body goes into object storage for later parsing and indexing.
The core mechanism is a per-host token bucket or leaky bucket combined with domain-isolated queues. A domain's queue can only release a request when that domain has an available token, and tokens refill according to the crawl delay and host health. This prevents multiple fetch workers from collectively hammering one site. Robots policies are cached and refreshed with If-Modified-Since so workers do not fetch robots.txt for every URL. Retries use exponential backoff with jitter, and permanently failing hosts are slowed down or quarantined. This design trades some throughput for politeness, but it keeps the crawler scalable because each domain is independent and can be processed by different workers.
Scaling and availability are achieved by keeping the fetch workers stateless. All scheduling and per-domain state lives in the distributed frontier, Kafka, and shared caches rather than on local disks, so workers can be added or removed easily. The system partitions work by host or URL hash so every queue and its associated domain state is handled by consistent ownership. If a worker dies, its assigned queues are reassigned and unfinished fetches are retried. The DNS resolver and robots cache are replicated and sized to handle the fetch rate, and the forwarded proxy tier is itself stateless or active-active. The main trade-offs are throughput versus politeness, freshness versus overhead, and ease of egress versus IP management. Using a forward proxy centralizes connection reuse and hides the crawler's origin IPs, but adds an extra hop and can become a bottleneck if not scaled. Fetching directly is simpler and faster but makes per-host rate limiting harder to coordinate across many workers.
flowchart LR
F[Distributed URL Frontier] --> S[Per-domain Scheduler]
S --> Q1[Queue domain A]
S --> Q2[Queue domain B]
Q1 --> W1[Fetch Worker 1]
Q2 --> W2[Fetch Worker 2]
W1 --> R[(Robots Cache)]
W2 --> R
W1 --> D[(DNS Cache)]
W2 --> D
W1 --> P[Forward Proxy]
W2 --> P
P --> T1[Target Host A]
P --> T2[Target Host B]
W1 --> O[(Object Storage for Raw HTML)]
W2 --> M[(Fetch Metadata DB)]
W1 --> PF[Parsing Pipeline]
W2 --> PF
Design a Web Crawler Full Walkthrough¶
A web crawler starts from seed URLs and repeatedly fetches pages, extracts links, and stores raw content and metadata for later indexing. For planning, assume the crawler must fetch about 10 billion pages over a 30-day crawl. That is roughly 3,900 pages/sec sustained and about 10,000 fetches/sec at peak. With an average 20 KB HTML page, raw content volume is about 200 TB; metadata and URL indexes add tens of TB more. Functional requirements include seed ingestion, HTTP/HTTPS fetching, respecting robots.txt, per-domain rate limiting, link extraction and normalization, duplicate URL and duplicate content suppression, retry handling, and durable storage of pages and metadata. Non-functional requirements include high throughput, bounded memory and queue sizes, fairness across domains, robustness to slow and failing sites, horizontal scalability, and availability during worker failures.
The high-level architecture uses a persistent URL frontier backed by a distributed queue or log. Fetch workers pull URLs from per-domain queues, check a shared robots cache, resolve DNS, and download pages through a managed HTTP layer. Parser workers extract and normalize outbound links, remove fragments, resolve relative URLs, and canonicalize schemes, hosts, and paths. A Bloom filter provides a memory-efficient preliminary seen-URL test, while the frontier and a URL metadata store keep the authoritative seen set, so duplicates are not fetched repeatedly. Raw HTML is stored in object storage, and typed metadata such as URL, status, content hash, canonical link, and fetch time is written to a queryable database.
The data model separates three storage concerns. The frontier stores pending URLs with host, priority, schedule time, retry count, and discovery context; per-domain state stores crawl delay, last fetch time, robots fingerprint, and host health. The seen-set store maps canonical URL hashes to fetch status and may contain Bloom filters to reject obvious duplicates. Raw content goes into object storage because it is large, immutable, and read less often during crawling. Metadata goes into a distributed key-value or document store because it needs fast URL lookups, deduplication checks, and recrawl scheduling.
The core mechanism is domain-aware scheduling with aggressive deduplication. The frontier partitions URLs by host and priority, and it releases requests only when per-host tokens or schedules allow, so many workers can crawl in parallel without hammering one site. Workers respect robots.txt and use timeouts, exponential backoff with jitter, and retries only for transient failures. Parsers normalize discovered links, apply the seen-set test, and enqueue only new URLs. This loop balances freshness and completeness against load while preventing same-page and near-duplicate content from being stored repeatedly.
For scaling and availability, the crawler uses stateless workers and shared distributed state. The frontier is partitioned by host or URL hash so work spreads evenly across machines; Kafka or a similar log allows replay and redelivery after failures. The robots cache, DNS cache, and seen-set are replicated because they are hot and required on every fetch. If a worker dies, its per-domain queue is reassigned and unfinished fetches are retried. Adding more fetch and parser workers increases throughput as long as the frontier has enough partitions and back pressure prevents unbounded queue growth.
The main trade-offs are throughput versus politeness, completeness versus cost, and freshness versus overhead. A faster crawl risks overwhelming target sites unless per-domain limits are enforced. Deduplication saves storage and bandwidth but can miss pages if the seen-set is too small or false-positive-prone. Recrawling important pages more often improves freshness but increases load on both the crawler and target sites. The design therefore uses queues, caches, and distributed workers rather than a single fast machine.
flowchart LR
S[Seed URLs] --> F[URL Frontier]
F --> W[Fetch Workers]
W --> R[Robots Cache]
W --> P[Parser]
P --> B[Bloom Filter / Seen Set]
P --> F
P --> O[(Object Storage: Raw HTML)]
P --> M[(Metadata DB)]
B --> F
Design a Notification System — Full Walkthrough¶
To design a notification system, start by defining workload and scale. Suppose the product has 50 million monthly active users, 10 million daily active users, and sends about 200 million notifications per day across email, mobile push, SMS, and in-app channels. That is roughly 2,300 notifications per second on average and 10,000 notifications per second at peak. Functional requirements include accepting notification requests from internal services, applying user preferences and quiet hours, fanning out to each valid channel, assigning priority such as transactional versus marketing, and tracking delivery status. Non-functional requirements include low latency for critical notifications, high availability, no silent loss after a request is accepted, horizontal scalability, and tolerance of provider outages. The system should avoid duplicate delivery where possible while still being able to retry failed attempts safely.
The high-level architecture separates synchronous intake from asynchronous delivery. Producer services send notification requests through an API gateway or SDK to a notification intake service. The intake service validates the request, resolves recipient and channel eligibility from a preference service, creates a durable notification record, and publishes an event to a durable message queue for each valid channel. Channel-specific workers consume those events and communicate with external providers: APNs or FCM for mobile push, SES or SendGrid for email, Twilio or another provider for SMS, and a WebSocket gateway for in-app notifications. Delivery status and provider callbacks are written back asynchronously to the notification store and can also feed analytics. This decoupling means a slow email provider does not block push delivery, and traffic bursts are absorbed by the queue instead of overloading provider APIs.
The data model has several parts. Core transactional tables include notification, notification_channel, user_notification_preference, device, and delivery_attempt. A notification row stores notification_id, user_id, type, template_id, payload, priority, status, and created_at. Channel rows store the destination address or device token, provider, status, and an idempotency key used to prevent duplicate deliveries. A sharded relational database is appropriate for this state machine because records require indexed lookups, uniqueness, and retry state. Redis is used for hot per-user rate-limit counters, deduplication keys, and cached preference lookups because these need sub-millisecond access and can tolerate loss or recreation. Large email bodies or push templates are not stored in every row; template metadata and large payloads can live in object storage or a template service, while the notification record stores a template ID and parameters.
The core mechanism is durable enqueue with fan-out, retries, and idempotency. The intake service writes the notification and an outbox record in the same database transaction, so accepting a notification does not depend on the queue being available. An outbox publisher then publishes each outbox record to the queue, and workers consume the events with at-least-once semantics. Each delivery attempt uses an idempotency key and checks the current channel state before calling the provider, so retries do not create duplicate messages in the normal case. Failed provider calls are retried with exponential backoff and a maximum attempt count; exhausted attempts are moved to a dead-letter queue for inspection. Before delivery, workers re-check user preferences, quiet hours, provider rate limits, and per-user throttling. Marketing notifications can be batched or delayed, while transactional notifications skip batching to preserve low latency. Redis TTL-based keys can deduplicate repeated requests that arrive close together, and the notification state machine records whether a message is pending, sent, failed, or retrying.
Scaling and availability come from stateless services, partitioned queues, and isolated provider workers. The intake and worker tiers are stateless behind load balancers, so they can scale horizontally by adding instances. The message queue is replicated and partitioned by notification ID or user ID, which spreads traffic and helps preserve affinity when ordering matters. Databases are sharded by user ID with read replicas for preference and device reads. Redis is sharded and replicated for hot counters. Provider failure is isolated to its own worker pool, so an outage in one provider does not block other channels. Back pressure is enforced by bounded queues and worker capacity, and per-provider rate limiting prevents workers from oversaturating external APIs. If a worker crashes after a provider sends the message but before the status is recorded, the same message may be redelivered when the queue redrives it; the idempotency key and status checks minimize this risk, and the dead-letter queue makes these cases observable.
The main trade-offs are delivery guarantees versus implementation complexity, latency versus throughput, and cost versus durability. Exactly-once delivery across external push, email, and SMS providers is practically impossible, so the design uses at-least-once delivery plus idempotency keys and a state machine. This preserves correctness enough for most products but requires extra database checks and provider-specific idempotency support. Batching marketing notifications improves throughput and reduces cost but adds latency, so the system separates transactional and marketing priority classes. Fanning out to multiple channel queues makes each channel easy to scale independently, but it means one logical notification can be partially delivered if one channel fails; per-channel status records make this visible and retryable. Finally, the outbox pattern prevents notification loss at the cost of additional writes, which is acceptable because users usually consider a missing transactional notification worse than a small increase in database load.
flowchart LR
P[Producer Services] --> I[Notification Intake Service]
I --> V[(Sharded SQL Notification + Outbox)]
V --> OP[Outbox Publisher]
OP --> Q[Message Queue / Event Log]
I --> PR[Preference Service]
I --> RD[(Redis rate limit / dedup)]
Q --> PW[Push Worker]
Q --> EW[Email Worker]
Q --> SW[SMS Worker]
Q --> IW[In-app Worker]
PW --> APNS[APNs / FCM]
EW --> SMTP[Email Provider / SES]
SW --> SMSProvider[SMS Provider]
IW --> WS[WebSocket Gateway]
PW & EW & SW & IW --> V
PW & EW & SW & IW --> DLQ[Dead Letter Queue]
APNS & SMTP & SMSProvider & WS --> U[User]
Design Mint.com (Financial Aggregation) — Full Walkthrough¶
To size the system, assume about 10 million registered users, 1 million daily active users, and 100 million linked financial accounts. Each account is refreshed roughly once per day, so the background scheduler must drive about 1,200 refreshes per second on average and several thousand per second at peak. A successful refresh may pull an average of 10 new transactions per account, producing roughly 1 billion new transactions per day. At about 500 bytes per normalized transaction, this is around 500 GB per day and about 180 TB per year before indexes and replication. Reads are dashboard aggregation requests and tend to spike in the morning and evening, but the dominant background workload is pulling and normalizing account data. The system must be highly available and secure, while freshness can be eventual: users can tolerate balances and transactions appearing within minutes or hours rather than waiting synchronously on every financial provider.
Clients use a web or mobile app that communicates through an API gateway. The gateway authenticates the user and routes dashboard requests to a dashboard service, while link-account and settings operations go to a user and account service. The user and account service stores linked financial institutions, account metadata, user preferences, and references to provider credentials or access tokens. A scheduler periodically scans accounts that are due for refresh and places refresh jobs into a durable queue. Connector workers consume those jobs and use institution-specific adapters to fetch balances and transactions from third-party aggregators such as Plaid or Yodlee, from direct bank APIs, or in some legacy cases from screen-scraping connectors. The workers normalize the returned records and persist them in the transaction and balance stores. A separate categorizer consumes raw transactions asynchronously, applies user rules and machine-learning predictions, updates category fields and budget progress, and invalidates dashboard caches. A notification service sends alerts after refreshes finish or fail. This request flow separates synchronous user-facing reads from heavy asynchronous provider pulls.
The data model is split between relational storage, caches, queues, and a secrets store. Users, institutions, accounts, budgets, categories, and alerts are strongly structured and can live in a relational database because they require uniqueness, indexes, and transactional updates. Linked accounts store user_id, institution_id, account_id, nickname, status, provider reference, and a pointer to encrypted credentials; they do not store raw bank passwords. Transactions are append-heavy but still fit a sharded relational store when sharded by user_id or account_id because they need range queries by date, filtering by category, and joins to accounts. Each transaction row contains user_id, account_id, provider_transaction_id, amount, currency, merchant description, posted_at, category_id, fingerprint, and timestamps. Redis caches dashboard summaries, hot account metadata, refresh status, and category rules because these are read-heavy and can be rebuilt from source-of-truth tables. The durable queue holds refresh jobs and retries, while a separate token vault or KMS-backed secret store encrypts provider credentials and access tokens with least-privilege access.
The core mechanism is an idempotent, asynchronous refresh pipeline. The scheduler claims accounts due for refresh using a distributed lock or database lease so the same account is not enqueued twice. It publishes a refresh job with an idempotency key and enqueue time. A connector worker picks up the job, resolves the institution adapter, retrieves an access token or decrypted credential, and pulls the latest balances and recent transactions. It normalizes dates, currencies, merchant names, account types, and transaction statuses into a common internal model. To avoid duplicate imports, the worker computes a transaction fingerprint from the provider transaction ID, amount, date, and normalized description, or from a hash of provider-supplied fields. Writes are performed idempotently, so retries do not create duplicate transactions. After a successful pull, the worker updates last_refreshed_at and account status, publishes a transaction batch event, and schedules a retry with exponential backoff on failure. The categorizer then assigns a category using user-defined rules first because they are precise, then falls back to a machine-learning classifier trained on merchant descriptions and user corrections. When categories change, budget counters and cached dashboards are invalidated or updated.
Scaling and availability come from stateless services, sharding, replication, and provider isolation. The API gateway, account service, dashboard service, scheduler, connector workers, and categorizer are all stateless and scale horizontally behind load balancers. The refresh queue is partitioned by account or institution and replicated so losing a worker does not lose accepted jobs. Transactions, accounts, and user tables are sharded by user_id or account_id, and read replicas serve dashboard queries. Redis is sharded and replicated for cache and small hot state. The scheduler uses a leader election or lock service so multiple instances do not trigger duplicate refresh jobs. Connector workers are the main bottleneck because financial providers impose rate limits, timeouts, and occasional outages; each institution adapter uses a per-provider token bucket, circuit breaker, and backoff. Dead-letter queues hold persistently failing jobs for inspection and manual replay. Backpressure limits queue depth and prevents a provider slowdown from exhausting memory across workers.
The important trade-offs are freshness versus provider load, third-party aggregation versus direct integration, and at-least-once delivery versus duplicate prevention. Frequent synchronous refresh gives fresher data but increases provider calls, rate-limit risk, and infrastructure cost; scheduled and event-driven asynchronous refresh is more scalable but eventually consistent. Using a third-party aggregator accelerates development and normalizes many institutions, but adds dependency, cost, and an extra network hop. Direct bank APIs are cleaner and cheaper in the long run but require many institution-specific adapters. At-least-once job delivery combined with idempotent transaction writes prevents duplicates, but requires careful fingerprinting and upsert logic. Storing normalized transactions in a sharded relational database provides easy reporting and dashboard queries, but a NoSQL wide-column store could handle the append scale more fluidly at the cost of joins and transactional guarantees. Finally, caching dashboard summaries improves read latency but can display stale balances until the refresh and invalidation path completes.
flowchart LR
U[User / Client] --> G[API Gateway]
G --> D[Dashboard Service]
G --> A[User / Account Service]
A --> V[Token Vault / KMS]
A --> S[(Sharded SQL Accounts and Transactions)]
SC[Scheduler] --> Q[(Durable Refresh Queue)]
Q --> W[Connector Workers]
W --> P[Plaid / Yodlee / Direct Bank APIs]
P --> W
W --> S
S --> C[Async Categorizer and Budget Worker]
C --> S
C --> N[Notification Service]
N --> U
D --> R[(Redis Dashboard Cache)]
R --> S