Message Queues
Why async decoupling changes a system's failure behavior, the log vs broker distinction, delivery semantics, ordering, and dead letter handling.
#What a queue actually buys you
A queue sits between a producer and a consumer, holding work until it can be processed. It looks like a small addition and it changes four properties of your system at once:
- Decoupling. The producer doesn't know or care who consumes, how many consumers there are, or whether they're up. You can add consumers without touching the producer.
- Buffering. Traffic spikes are absorbed by the queue instead of by your database. A 10× burst becomes a temporarily deeper queue rather than an outage.
- Load leveling. A slow consumer no longer causes user-facing latency — the queue depth grows, the user already got their response.
- Retry and durability. A failed message stays available to retry, instead of vanishing into a dropped HTTP call.
The cost, which you must name to score well: you have traded latency and simplicity for resilience. The work now happens "eventually," you need to handle duplicates, ordering gets complicated, debugging spans systems, and you've added a component that itself can fail.
#Two families
The most useful distinction, and one that is frequently blurred.
#Traditional brokers (queue semantics)
RabbitMQ, ActiveMQ, SQS
The broker tracks per-message state. A consumer takes a message, acknowledges it, and the broker deletes it. Messages are distributed among consumers — each message goes to exactly one.
- Rich routing (by topic, by header, or fanout — copying each message to several queues), per-message TTL, priority queues, and delayed delivery.
- Individual message acknowledgment means one poison message — a message that makes the consumer fail every time it's processed, say because its data is malformed — doesn't block others. The broker can set it aside and keep handing out the rest.
- Consumers are simple: they don't have to remember how far they've read, because the broker tracks that.
- Throughput is lower (per-message bookkeeping), and once consumed, a message is gone — you can't replay.
#Log-based systems (stream semantics)
Kafka, Pulsar, Kinesis, Redpanda
An append-only, partitioned, durable log. Consumers track their own offset; messages are retained by time or size policy regardless of consumption.
Partition 0: [m0][m1][m2][m3][m4][m5][m6][m7]...
▲ ▲
consumer-B consumer-A
offset=3 offset=7
Independent consumer groups read the same data at
their own pace. Nothing is deleted on read.- Replay. Reset the offset and reprocess history — invaluable for bugs, backfills, and new consumers that need the past.
- Multiple independent consumers of the same stream, each with its own position.
- Very high throughput — appending to the end of a file is the fastest thing a disk does; reads are sent from disk to the network without being copied through the application ("zero-copy"); and messages move in batches. Hundreds of MB/s per broker.
- Ordering within a partition is guaranteed.
- Costs:
- No per-message ack. The consumer only records "I've processed everything up to offset 7", so it can't skip a message that keeps failing and come back to it later — a stuck message blocks its whole partition.
- Coarser retries: to retry one message you either stop the partition or copy the message to a separate retry topic yourself.
- More operational complexity.
- Consumer parallelism is capped by partition count.
Choosing: need replay, event sourcing (storing every change as an event and rebuilding state from that history), multiple consumers, or very high throughput → log. Need complex routing, per-message priority/TTL, or simple task distribution → broker. "Kafka for the event backbone, SQS/RabbitMQ for task queues" is a common and defensible combination.
#Delivery semantics
A guaranteed follow-up question. Be precise.
These three phrases describe when the consumer tells the queue "I've got this" — the acknowledgement, or ack. Everything follows from whether that happens before or after the work.
At-most-once — ack first, then work. If the consumer dies mid-work the message is already marked done and is gone forever. Never duplicated, sometimes lost. Acceptable only for throwaway telemetry.
At-least-once — work first, then ack. If the consumer dies mid-work, no ack arrives and the queue hands the message to someone else. Nothing is lost, but duplicates are guaranteed to happen eventually. This is the practical default for nearly everything.
Exactly-once — the one to be careful about.
#Ordering
Global ordering across a distributed queue requires a single partition, which caps throughput at one machine. That's rarely acceptable, so real systems use partial ordering:
partition = hash(ordering_key) mod num_partitions
All events for user 42 → same partition → ordered
All events for conversation X → same partition → ordered
Across different users → no ordering guarantee (fine)Choose the ordering key as the entity whose events must be sequential. This is exactly the partition key decision, with the same hot-spot risks.
Ordering is also broken by retries and concurrency, which candidates often miss:
- If a consumer processes messages concurrently, order is lost regardless of partitioning.
- If a failed message is retried later while subsequent ones succeeded, order is lost.
- Producer-side retries can reorder unless the producer enforces sequencing (Kafka's idempotent producer does this with sequence numbers).
The robust design response: prefer commutative or version-checked operations over relying on order. A commutative operation gives the same result in any order. A version-checked one carries a version number and is ignored if it's older than what's already stored.
- "Set status to X if version > current" survives reordering: a late, older update is simply rejected.
- "Increment" doesn't care about order: +1 then +1 is the same either way.
- "Apply this delta" does care — a patch written against one version of the data can corrupt it if applied on top of a different one.
#Consumer groups and scaling
Parallelism comes from partitions:
6 partitions, 3 consumers → 2 partitions each ✓ balanced
6 partitions, 6 consumers → 1 each ✓ max parallel
6 partitions, 8 consumers → 2 consumers IDLE ✗ wastedPartition count is your parallelism ceiling, and it's awkward to increase later because it changes the key→partition mapping. User 42's older events sit in partition 3, but after the change their new events hash to partition 5. A consumer can then read the new events before it has finished the old ones, so that user's ordering breaks. Over-provision partitions up front — the same "pre-split generously" logic as virtual shards.
Rebalancing happens when consumers join or leave: partitions are reassigned. Naive rebalancing stops all consumption briefly ("stop the world"); modern protocols do it incrementally. Frequent rebalances are a classic production problem worth mentioning. The usual cause: a consumer must check back with the broker every so often (a poll timeout) to prove it's alive. If it spends too long on a slow batch, it misses that deadline and is declared dead. Its partitions are reassigned, it reappears, they're reassigned again — and little work gets done.
#Backpressure and queue depth
Queue depth is your most important metric. Interpret it correctly:
- Stable depth → producers and consumers are balanced. Healthy.
- Growing depth → consumers are behind. Either a spike (self-correcting) or under-provisioned consumers (not).
- Depth at zero always → possibly over-provisioned, but fine.
Alert on consumer lag in time ("we're 4 minutes behind"), not just message count — it's the number that maps to user impact.
An unbounded queue is a trap: it converts a throughput problem into a memory/disk problem plus unbounded latency. Messages processed hours late are often worse than useless — a notification about an event that already passed. Options: bounded queues that reject producers (real backpressure), TTLs that drop stale messages, or priority lanes so important work isn't stuck behind bulk work.
#Dead letter queues
Some messages will never succeed: malformed data, references to things that have been deleted, plain bugs. A dead letter queue is where you put them after N failed attempts — a side-queue for messages that need a human, so the main flow can carry on. Without one, such a message is retried forever, burning capacity and, in a log-based system, blocking everything queued behind it.
consume → process → fail → retry (backoff) → fail → ...
│
after N attempts
▼
┌──────────────────┐
│ Dead Letter Q │ → alert, inspect,
└──────────────────┘ fix, replayPractices worth naming: keep the original message plus the error and stack trace; alert on DLQ arrivals (a non-empty DLQ is a bug, not a normal state); make replay a first-class operation; and distinguish retriable errors (timeout, 503) from permanent ones (validation failure) so you don't waste retries on messages that can never succeed.
#The outbox pattern
The most important queue-related correctness problem, and excellent material for a deep dive.
You need to update the database and publish an event. Two systems, no shared transaction:
BROKEN:
BEGIN; INSERT order; COMMIT;
publish("order_created") ← crash here: order exists,
nobody downstream knows
BROKEN (other order):
publish("order_created")
BEGIN; INSERT order; COMMIT; ← fails: event for an
order that doesn't existThe fix: write the event into an outbox table in the same database transaction as the business change. A separate process reads the outbox and publishes, marking rows sent.
BEGIN;
INSERT INTO orders ...;
INSERT INTO outbox (event, payload) VALUES (...);
COMMIT; ← atomic: both or neither
[relay] poll outbox / read WAL → publish → mark sent(The relay either polls the outbox table for unsent rows, or reads the database's write-ahead log — its internal record of every committed change — to spot new outbox rows as they commit.)
Now the event is published at-least-once and never diverges from the data. Combined with an idempotent consumer, you get exactly-once effect. See CDC & Outbox.
#Queue vs direct call
Don't use a queue for everything. A direct synchronous call is right when the caller genuinely needs the result to respond, when latency budget is tight, or when the operation is trivially fast and reliable. Adding a queue there costs latency and complexity for nothing.
| Use a queue | Use a direct call |
|---|---|
| Caller doesn't need the result | Caller needs the result now |
| Work is slow or bursty | Work is fast and predictable |
| Failure should be retried later | Failure should surface immediately |
| Multiple independent consumers | Exactly one known consumer |
| Load smoothing is valuable | Latency budget is tight |
#Check yourself
Name the four things a queue buys you, and the cost.Show answer
Traditional broker versus log: what's the core difference?Show answer
At-most-once versus at-least-once: where is the acknowledgement?Show answer
Why is exactly-once delivery impossible, and what do systems provide instead?Show answer
How do you get ordering without capping throughput at one partition?Show answer
What breaks ordering even with correct partitioning?Show answer
Six partitions and eight consumers in one group: what happens?Show answer
What is the outbox pattern for?Show answer
#What to carry forward
- A queue trades immediacy and simplicity for decoupling, buffering and retries.
- Brokers delete on acknowledgement and route richly; logs retain, replay and scale to many readers.
- Use at-least-once delivery with idempotent consumers; "exactly-once" means exactly-once effect.
- Order per key through partitioning — and watch for concurrency and retries breaking it.
- Alarm on consumer lag in time, bound your queues, dead-letter poison messages, and use an outbox for DB-plus-event writes.