Learn

PATTERN · ORIGINAL

Queues, retries and dead letters

At-least-once delivery, visibility timeouts and acks, exponential backoff with jitter, poison messages and dead-letter queues, ordering vs parallelism, idempotent consumers, and back-pressure.

Queues show up in almost every design as the box between “something happened” and “work gets done about it”. Drawing the box is easy. The follow-ups are about what happens inside it when a consumer crashes halfway, when a message can never succeed, when work arrives faster than it can be done, or when order matters. This article is about those moments.

It covers per-message work queues: each message is handled by one consumer and then acknowledged. Replayable partitioned logs with consumer offsets are a related but different tool, covered in partitioning and ordering. The message queue and distributed log questions exist to test that difference.

At-least-once is the normal promise

A consumer receives a message, does the work, then tells the queue it is done (acks). Something can fail between any two of those steps. If the consumer crashes after doing the work but before the ack, the queue cannot tell the difference between “done but unacked” and “never started”. The safe choice is to deliver it again. That is at-least-once delivery, and it is what most queues give you by default.

The alternative, acking before doing the work, is at-most-once: a crash loses the message. That is acceptable for some telemetry and nothing else. So assume at-least-once and plan for duplicates from the start.

Visibility timeouts and acks

Queues avoid two consumers working on the same message at once by hiding a message when it is handed out. Two common models:

  • Lease with a visibility timeout: the message becomes invisible for, say, 60 seconds. If the consumer deletes it in time, it is gone. If not, it reappears and someone else gets it.
  • Connection-bound acks: the message stays assigned to a consumer until it acks, nacks, or its connection drops, at which point it is requeued.

Sizing the visibility timeout is a real decision. Too short, and slow but healthy work reappears and runs twice in parallel. Too long, and a crashed consumer's messages sit hidden for minutes before anyone retries. A good default is several times the p99 processing time, plus a heartbeat that extends the lease for jobs that are legitimately long. For a web crawler fetching pages with a 10-second timeout, a 60-second visibility timeout is reasonable; for a video transcode that takes 20 minutes, extend the lease every minute instead of setting a 1-hour timeout.

Limit how many unacked messages each consumer holds (often called prefetch). A consumer that grabs 1,000 messages and then crashes delays all 1,000 by a full timeout.

FIG. 6ORIGINAL SKETCH
enqueue1lease2send3record + ack4transient fail5duemax attempts6inspect, redriveProducerWork queuevisibility 60 sWorkersdedupe by msg idResults storeEmail providerRetry delay2^n s + jitterDead lettersafter 6 triesOps dashboard
A work queue with retries: producers enqueue, workers lease and ack, failures go to a delay queue with growing backoff, and after a maximum number of attempts a message moves to the dead-letter queue for inspection and redrive.

Retries with exponential backoff and jitter

Most failures a consumer sees are transient: a timeout, a 503 from a dependency, a lock conflict. Retrying is right. Retrying immediately is usually wrong, because whatever caused the failure (an overloaded dependency) is made worse by an instant wave of retries.

Exponential backoff waits longer after each failure: 1 s, 2 s, 4 s, 8 s, up to a cap. Jitter randomises each wait, for example a random value between zero and the exponential delay. Without jitter, a thousand messages that failed together retry together, at exactly 1 s, 2 s and 4 s, and the dependency sees synchronised spikes. With jitter, the retries spread out into a smooth trickle. The AWS post in further reading simulates this.

Practical rules:

  • Cap the delay and the attempts. Six attempts with a cap of a few minutes covers most transient outages. Write the numbers next to the retry arrow.
  • Classify errors. Retry timeouts, throttling and 5xx responses. Do not retry validation errors, a 404 for a deleted user, or an invalid address; they will fail identically forever. Send them straight to the dead-letter queue or drop them with a log.
  • Retry at one layer. If the HTTP client retries 3 times, the worker retries 3 times, and the queue redelivers 3 times, one failing call becomes 27 attempts. Pick the layer that owns retries (usually the queue, for durable work) and keep the others shallow.
  • Use a delay queue, not a sleeping worker. A worker that sleeps for 60 seconds holds a slot and a lease doing nothing. Put the message on a delayed or scheduled queue and free the worker.

Poison messages and dead-letter queues

A poison message is one that fails every time: malformed data, a bug triggered by one specific input, a reference to something deleted. Without a limit, it is redelivered forever, burning worker time and, worse, blocking anything queued behind it if order is enforced.

A dead-letter queue (DLQ) is where messages go after a maximum number of attempts. It turns an infinite loop into a visible, finite list. Make the DLQ useful:

  • Store the original message, the attempt count, and the last error with each entry.
  • Alert on DLQ depth or growth rate. A DLQ nobody watches is just a slower way to lose data.
  • Support redrive: after the bug is fixed, move messages back into the main queue. Because consumers are idempotent, redriving something that partly succeeded is safe.
  • Set a retention period that is longer than your team's realistic response time, such as 14 days, not 1 hour.

For an on-call escalation system, a page landing in the DLQ is itself an incident. That is a good follow-up answer: the DLQ path for critical messages should alert a human through a separate channel.

Ordering vs parallelism

A queue with 50 workers processes messages in parallel, which means it does not preserve order. Usually that is fine: sending password reset emails in a slightly different order hurts nobody. When order matters, it almost always matters per key, not globally: updates to one account, events in one conversation, state changes of one job.

OptionWins whenCosts
Unordered, many workersMessages are independent: emails, thumbnails, crawl fetchesOut-of-order processing; consumers must tolerate it
Ordered per key (group or partition by key)Order matters within an entity but entities are independentParallelism limited by number of keys or partitions; a hot key or a stuck message blocks its group
Single ordered queue, one consumerStrict global order with low volumeNo parallelism; one slow message stalls everything
Unordered + version check in consumerYou want full parallelism but must not apply stale updatesEach message carries a version; consumer drops older ones, so intermediate states may be skipped

The last row is often the best trade. Instead of forcing order in the queue, give each message the entity's version and let the consumer apply it only if it is newer than what is stored. You keep parallel workers and still end in the right state. Per-key ordering also interacts badly with poison messages: a stuck message blocks its whole key until it is dead-lettered, so keep max attempts low on ordered queues.

Idempotent consumers

Duplicates come from redelivery after a crash, from a lease expiring on a slow worker, from redrive, and from producers that retry a publish. The consumer must make the second delivery harmless. In short: record the message id in the same transaction as the consumer's write and skip ids already seen, or make the write itself idempotent (an upsert, a “set to” rather than “add”, a version check). For side effects in external systems, pass an idempotency key through. Consistency and idempotency covers this in depth; the short version is that at-least-once delivery plus an idempotent consumer gives each effect exactly once.

Back-pressure

A queue absorbs bursts, which is its main job. But a queue that grows without bound is not absorbing a burst; it is hiding an outage. If producers add 2,000 messages per second and consumers finish 1,500, the backlog grows by 1.8 million messages an hour, and every new message waits longer than the last. At some point the data is too stale to be useful.

Decide in advance what happens when consumers fall behind:

  • Autoscale consumers on queue age, not just depth. “Oldest message is 30 seconds old” is a clearer signal than “10,000 messages”, because it is what users feel.
  • Protect the downstream. Scaling workers is pointless if they all hammer the same database or a rate-limited provider. Cap concurrency to what the dependency can take; the queue holds the rest.
  • Push back on producers. Bound the queue, and when it is full, reject or slow new work at the edge (a 429 with retry-after) rather than accepting work you cannot do.
  • Shed or expire stale work. A price alert that arrives an hour late is worse than useless. Give messages a deadline and drop or downgrade them once it passes.
  • Separate priorities. Put password resets and marketing emails in different queues with different workers, so a bulk campaign cannot delay a login.

Queues sit under many other patterns. Fan-out workers in fan-out and real-time delivery consume from one, a job scheduler is a queue with a clock in front of it, and the numbers for sizing consumers come from estimates that drive decisions.

TAKE THIS TO YOUR NEXT SKETCH

  • Assume at-least-once delivery: a crash between doing the work and acking means the message comes back.
  • Size visibility timeouts to several times p99 processing time and extend leases for long jobs; limit prefetch.
  • Retry transient errors with capped exponential backoff and jitter, at one layer only, using a delay queue.
  • Send permanent failures and messages past max attempts to a DLQ that stores the error, alerts, and supports redrive.
  • Order per key only where it matters, or use version checks in the consumer to keep full parallelism.
  • Make every consumer idempotent by recording message ids with the write or making the write itself repeatable.
  • Plan back-pressure: scale on queue age, cap concurrency for downstreams, bound the queue, and expire stale work.

PRACTICE WITH THIS

Now sketch one.

OFF-SITE READING · NOT WRITTEN BY US

Further reading

Next: Reservations and contention: selling what you have, exactly once