← Building blocks

Decouple producer from consumer

Decoupling & async workfundamental

The request path waits on slow work (email, resize, analytics) or on a service that may be down.

Say it like this

The request only needs the write to be durable, not the email to be sent, so I enqueue a job and return 202; workers drain the queue at their own pace and a slow provider never blocks the API.

Basic solution

Put a queue between them. The producer enqueues and returns; workers consume at their own pace.

SQSRabbitMQKafkaGoogle Pub/Sub

Queue between the API and the workers

The API returns as soon as the broker has the message. Workers pull, do the slow part, and ack; an unacked message reappears for another worker.

How it works

  1. The API does only the part the user needs an answer to: it validates the request and writes the row (the notification record, the order). Then it publishes a small message to the broker: the row id and the minimum context a worker needs, such as the channel and template id. It does not include the full payload; the worker reads that from the row.
  2. The broker writes the message to its own durable storage and replies to the API with an acknowledgement. Only now does the API return 202 Accepted to the client, with a status URL. 202 means "I have it and will do it", not "done".
  3. A worker takes a message from the queue. Taking it does not delete it: the broker hides the message from other workers for a visibility timeout (say 60 seconds) so only one worker holds it. The worker then does the slow work, such as calling the email provider.
  4. On success the worker acknowledges the message, which tells the broker to delete it for good. If the worker crashes or the visibility timeout runs out first, the broker makes the message visible again and another worker picks it up and tries again.
  5. The client learns the outcome by polling the status URL (which reads the job row the worker updated), by receiving a push over a WebSocket, or by a notification. The job row is the source of truth either way.

What the queue buys you

  • Producer and consumer scale and deploy independently: you can add workers without touching the API, and a bad worker deploy never breaks request handling.
  • A burst of 100K requests becomes a backlog that drains over minutes instead of a wall of timeouts, because the API only has to write a message, not do the work.
  • A consumer outage is a delay, not an error: messages wait in the broker until workers return, as long as the broker keeps them (its retention) for longer than the outage.

Worked example

Notification system intake

  • 250M notifications/day ≈ 2,900/s average; a campaign spikes to 33K/s for ten minutes. The API must survive the spike without the providers being involved at all.
  • Intake API work per request: validate, SET NX dedup key, insert row, publish. About 5 ms, so a 20-instance fleet absorbs 33K/s without touching any provider. The providers only ever see the workers.
  • SMS provider cap: 1,000 messages/s. A 20M-recipient blast is 20,000 s ≈ 5.5 hours of sending. The queue holds the backlog for those hours while the API keeps answering in 5 ms, which is the whole point.
  • Queue depth at peak ≈ (33K − 1K) × 600 s ≈ 19M messages × 300 B ≈ 6 GB. Trivial for Kafka or SQS, which store to disk; a single RabbitMQ node keeps messages in memory first and would need disk paging at that size.
  • Worker sizing: a worker spends ~50 ms per provider call, so 20 concurrent calls per worker ≈ 400/s; three workers saturate the provider limit. More workers would only queue up behind the provider's rate limit.

Variants and when each wins

Broker queue (SQS, RabbitMQ)

  • Each message is delivered to one of the competing workers and deleted once that worker acknowledges it; visibility timeouts and a dead-letter queue are built in. It wins for plain job dispatch, where one kind of worker does the work and nobody needs the history.

Log (Kafka, Kinesis)

  • Messages are kept for a retention period rather than deleted, and each consumer remembers its own position (offset), so several independent consumers can read the same stream and anyone can replay it. It wins when more than one system needs the events or when you need replay; it costs more to run.

Database as queue

  • A jobs table that workers claim with SELECT ... FOR UPDATE SKIP LOCKED, which locks a row for one worker and lets others skip past it. It wins when the job must be created in the same transaction as your data and the rate is modest, up to about a thousand jobs a second; beyond that, polling load and table bloat hurt.

In-memory queue inside the process

  • A channel or list inside the application, with no broker. It is fast and free but everything in it is lost when the process restarts, so it wins only for best-effort work such as metrics.

Default to a managed broker queue for jobs; move to a log when several consumers or replay are needed.

Failure modes

Duplicate processing

  • A user receives the same email twice. It happens because the worker finished the send but crashed before acknowledging, so the broker assumed the work was not done and redelivered the message to another worker. Make the handler idempotent: record a dedup key per message id before the side effect and skip the send when the key already exists.

Backlog grows without end

  • The age of the oldest message climbs for hours and notifications arrive stale. It happens because consumers are processing more slowly than producers are publishing, often after a provider slowdown, and nobody noticed. Alert on oldest-message age rather than depth, autoscale workers on depth, and give low-priority messages an expiry so they are dropped once they are no longer useful.

Poison message

  • One message is retried forever and a worker is permanently busy with it. It happens because the payload is something the handler cannot parse or process, so every attempt fails the same way. Set a maximum receive count (say 5) after which the broker moves the message to a dead-letter queue, where someone can look at it.

Visibility timeout shorter than the work

  • Two workers process the same message at the same time. It happens because the work took longer than the invisibility window, so the broker made the message visible again while the first worker was still on it. Set the timeout above the p99 duration of the work, or have the worker extend it periodically while it is still busy (a heartbeat).

Head-of-line blocking

  • Urgent messages wait behind a bulk batch. It happens because one queue holds all priorities and a queue is first-in-first-out, so an OTP enqueued after two million campaign messages waits for all of them. Use separate queues per priority and per channel, each with its own workers.

Interviewer follow-ups

Answer out loud before you open each one.

How does the client find out the work is done?

Return 202 with a job id and a status endpoint the client can poll with backoff. For interactive flows push the result over WebSocket or a notification instead. Either way the job record is the source of truth, written by the worker when it finishes.

What happens if the broker itself is down?

Publishing fails, so decide per feature: fail the request, fall back to a local durable buffer and replay later, or do the work inline for a small subset. Run the broker replicated across zones so this is rare, and alert on publish error rate.

Push or pull consumers?

Pull lets the worker control its own rate and is the natural fit for backpressure. Push is lower latency and simpler for small fan-out. Most brokers expose long-polling pull, which gives both low latency and flow control.

How do you keep ordering with multiple workers?

You generally cannot across a shared queue, so only order where the product needs it: FIFO queues with a message group id, or a log partitioned by the entity key with one consumer per partition. Everything else stays unordered and parallel.

Connections

In study paths
Making retries safe · Decoupling with events
Pairs with
Make retries safe · Park poison messages · Move slow work off the request · Keep urgent work ahead of bulk work · Slow the producer when the consumer is behind
Pulls against
Order events within a stream
Used in
Notification System · URL Shortener (TinyURL / bit.ly) · Video Streaming Platform (YouTube / Netflix)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingAPI, WorkersCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon SQSQueuePub/Sub, Cloud TasksService Bus queues, Queue StorageRabbitMQ, ActiveMQ
Amazon DynamoDBJob statusFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra