Message Queues & Streaming
Decouple producers from consumers so work can be absorbed, retried, and processed at its own pace.
Message queues in 30 seconds
- What: a durable buffer between parts of a system that run at different speeds — producer writes, consumer reads when ready.
- Why: absorbs spikes, survives a downstream being briefly offline, and retries failures instead of dropping work.
- Queue vs log: a queue deletes a message once acked (one consumer); a log (Kafka) keeps an ordered, replayable record for many readers.
- Delivery: at-most-once (can lose), at-least-once (the pragmatic default, duplicates happen), exactly-once (expensive, often an illusion).
- The real answer: at-least-once + an idempotent consumer keyed on message ID gives exactly-once effects without exactly-once delivery.
- Operate it: ordering only within a partition/key, a dead-letter queue for poison messages, and backpressure so the backlog can't grow forever.
The coffee shop order counter
Watch a busy coffee shop and you'll see a queue in the wild. You order and pay at the till, the cashier shouts or writes your order onto a ticket rail, and you step aside — you don't stand at the espresso machine waiting. The barista pulls tickets off the rail and makes drinks at their own steady pace. When a rush hits, the ticket rail gets long but nobody is turned away; the line just drains a bit slower. If the barista fumbles a drink, they remake it from the ticket — the order isn't lost. A message queue is that ticket rail for software: the part taking orders (the producer) is decoupled from the part doing the slow work (the consumer), and the rail in between absorbs bursts and survives stumbles.
The problem it solves
When a request triggers slow work — sending email, encoding video, updating a dozen downstream systems — doing it synchronously makes the user wait and ties their request's fate to every dependency. A queue lets the producer hand off a message and move on; a consumer picks it up later. The system absorbs spikes, survives a downstream being briefly offline, and retries failures instead of dropping them.
The gap a direct, synchronous call can't fill
The obvious alternative is to just call the downstream service directly and wait for it, no queue needed. For fast, reliable calls that's often the right answer. But lean on it for slow or shaky work and three cracks appear — and each crack is a reason the queue exists.
- The user waits for the slowest thing. If uploading a video means waiting for it to finish encoding, the user stares at a spinner for minutes. Their request's speed is chained to your slowest dependency.
- One failure fails everything. If the request fans out to five downstream services and the fourth is briefly down, the whole request fails — even though four-fifths of the work succeeded.
- A spike has nowhere to go. If 10,000 uploads land in a second and the encoder can handle 100 a second, a synchronous design just melts. There's no buffer to hold the overflow politely.
A queue closes all three gaps with one move: it inserts a durable buffer between 'request received' and 'work done.' The user's request finishes the instant the message is safely stored, a brief downstream outage just means the work waits a little, and a spike becomes a backlog that drains over time instead of a pile of errors.
The core idea, plainly
A queue is a durable buffer between two parts of your system that run at different speeds. The producer writes; the consumer reads when ready. This turns a tight, synchronous coupling (both must be up at once) into a loose, asynchronous one (they just need the queue). The cost is that you now reason about ordering, duplicates, and eventual completion instead of immediate results.
def handle_upload(request):
video = save_raw(request.file)
# Don't encode inline -- just enqueue the work and return fast.
queue.publish({
"id": uuid4(), # stable message ID for dedup downstream
"type": "encode_video",
"video_id": video.id,
})
return respond(202, "processing") # user isn't blocked on the slow work
# The producer's request succeeds even if the encoder is busy or briefly down.Scaling the work: competing consumers
Here's a payoff that falls out of the queue almost for free. If one barista can't keep up with the ticket rail, you add a second barista pulling from the same rail. In queue terms, that's the competing consumers pattern: many consumer instances read from one queue, each grabbing a different message, so throughput scales simply by adding more consumers.
This is why queues pair so naturally with elastic scaling. When the backlog grows, you spin up more consumers to drain it faster; when it shrinks, you scale them back down to save money. The queue is the shared work pile that makes 'just add more workers' actually work — no consumer needs to know how many siblings it has.
Queue vs log
A classic queue (like SQS or RabbitMQ) deletes a message once it's acknowledged — each message goes to one consumer and then it's gone. A log (like Kafka) keeps an ordered, replayable record; many independent consumers read at their own offset, and you can rewind. Queues suit task distribution; logs suit event streaming, replay, and multiple downstream readers of the same events.
The clearest way to feel the difference: a queue is like a to-do list where you tear off and throw away each task as you finish it — once it's done, it's gone, and only one person works each task. A log is like a diary that's never erased; many people can read it, each keeping their own bookmark (an offset) of how far they've got, and anyone can flip back to re-read an old entry. That replayability is the log's superpower — a brand-new consumer can process the entire history of events from the beginning.
| Queue (SQS, RabbitMQ) | Log (Kafka, Kinesis) | |
|---|---|---|
| Lifetime of a message | Deleted once acknowledged. | Retained for a window (days) or forever; replayable. |
| Who reads it | One consumer group drains it; message then gone. | Many independent consumers, each at their own offset. |
| Ordering | Usually best-effort or per-group. | Strict order within a partition. |
| Best for | Distributing tasks to workers. | Event streaming, replay, many downstream readers. |
| Rewind / reprocess | No — it's gone after ack. | Yes — reset the offset and re-read. |
Delivery semantics
Now the subtle part that every interviewer loves. Because networks drop packets and consumers crash mid-work, a queue has to make a choice about how hard it tries to deliver each message — and that choice is a genuine trade between losing messages and duplicating them.
| Guarantee | Meaning | Pros | Cons | Use when |
|---|---|---|---|---|
| At-most-once | Delivered 0 or 1 times. | Simple; no duplicates. | Can silently lose messages. | Loss is acceptable (metrics, telemetry sampling). |
| At-least-once | Delivered 1 or more times. | Never loses a message. | Duplicates happen; consumer must be idempotent. | Most real systems — the pragmatic default. |
| Exactly-once | Delivered precisely once (effectively). | No loss, no duplicates. | Expensive; needs dedup + transactional sinks. | Money movement, where a double-apply is harmful. |
Why can't you just have exactly-once and be done? Because the acknowledgement itself can get lost. Picture a consumer that finishes the work and then tries to tell the queue 'done' — but its network blips and the 'done' never arrives. The queue, having heard nothing, reasonably assumes the work failed and redelivers the message. The consumer did the work and is about to do it again. There's no way to make both 'never lose' and 'never duplicate' true across an unreliable network, so you pick: risk loss (at-most-once) or risk duplicates (at-least-once).
def handle(message):
if seen.exists(message.id):
return # already processed -> no-op (the dedup magic)
process(message) # do the real work exactly once in effect
seen.add(message.id) # remember this ID so a redelivery is ignored
message.ack()Ordering, dead letters, and backpressure
Global ordering across a scaled consumer pool is expensive; most systems guarantee ordering only within a partition / key (all events for one user stay in order). Messages that keep failing go to a dead-letter queue so one poison message doesn't block the line. When producers outpace consumers, the queue grows — you need backpressure (slow the producer) or autoscaling, or the backlog becomes unbounded.
A poison message is one that will fail no matter how many times you retry it — malformed data, a reference to something deleted, a bug it triggers. Without a plan, it retries forever and can wedge the whole line behind it. The fix is a dead-letter queue (DLQ): after a message has failed a set number of times, you move it aside into the DLQ so the healthy work keeps flowing, and a human (or an alert) can inspect the stuck ones later.
while True:
# Message is hidden from other consumers for `visibility_timeout`,
# not deleted -- so a crash mid-process lets it reappear and retry.
msg = queue.receive(visibility_timeout=30)
if not msg:
continue
try:
handle(msg) # must finish within the timeout window
msg.ack() # ack => queue finally deletes it
except Exception:
if msg.receive_count > 5:
dlq.publish(msg) # poison message -> dead-letter queue
# no ack: message becomes visible again and is redeliveredThe visibility timeout in that loop is a quiet hero. When a consumer receives a message, the queue doesn't delete it — it just hides it from other consumers for a while. If the consumer finishes and acks, the message is deleted for good. If the consumer crashes before acking, the timeout lapses, the message reappears, and another consumer retries it. That's exactly how at-least-once delivery survives a worker dying mid-task without losing the work.
A message queue is the move from 'do it now, together' to 'hand it off, handle it later' — the foundational building block of asynchronous, event-driven systems that stay standing under bursty, unreliable load.
Why it matters
- It decouples producers from consumers in both time and speed, so a slow or down dependency doesn't sink the request path.
- It turns spikes into a manageable backlog instead of a cascade of failures and timeouts.
- It makes retries and dead-lettering first-class, so transient failures get reprocessed rather than lost.
If ignored
- Users wait synchronously on slow downstream work, and one flaky dependency fails their whole request.
- A traffic spike with no buffer overwhelms the backend instead of queueing politely.
- Promising exactly-once without idempotency, then double-applying every redelivered message.
Where it fits
- Sits between services on the write/work path, buffering handoffs from fast producers to slower consumers.
- Underpins pub/sub and CDC, which ride on top of durable queues and logs.
- Pairs with idempotent consumers and rate limiting to stay correct and within budget under load.
Related topics
- Idempotency: the thing that makes at-least-once delivery safe to rely on
- Pub/Sub & CDC: event-broadcast patterns built on top of queues and logs
- Rate limiting: queue overflow lets a burst wait instead of being hard-rejected
- Replication: how a log like Kafka keeps messages durable across nodes
Interview lens
Questions it unlocks
- Design the notification/email pipeline for a large app.
- How do you handle a spike that your downstream can't absorb in real time?
- Design a system to process uploaded videos.
60-second answer
I'd put a queue between the request path and the slow work so the user gets a fast response and the work happens asynchronously. I'd scale throughput with competing consumers reading one queue. I'd assume at-least-once delivery and make consumers idempotent with a message ID, rather than chasing true exactly-once. I'd add a dead-letter queue for poison messages and call out backpressure or autoscaling so the backlog can't grow without bound. If multiple systems need the same events or replay, I'd choose a log over a plain queue.
Common traps
- Promising exactly-once delivery without idempotency or a transactional sink.
- Assuming global ordering when only per-key ordering is realistic at scale.
- Ignoring what happens when consumers fall behind producers.