Dead-letter queues and retries
How to retry failures that might pass, give up on those that will not, and park poison messages where someone will see and fix them.
The problem
An order consumer processes about 200 messages a second. One evening a partner integration sends an order whose quantity field is the string “two”. The consumer throws while parsing it and does not acknowledge, so the broker redelivers it. It throws again. Nothing about the message will ever change, so this repeats several times a second with no end.
What happens next depends on the broker. On a queue the message loops for ever, taking a worker each time and burying the error log, while other messages flow around it. On a Kafka partition it is worse. The consumer cannot commit past the bad record, so every order behind it on that partition waits. Lag climbs, an alert fires at 2 a.m., and one malformed message has stopped a twelfth of the business.
The first two fixes teams reach for are both wrong, in ways worth understanding. Catch every exception, log it and move on: the pipeline flows again, and a 30-second database outage now silently discards every message that arrives during it. Retry for ever: nothing is lost, and one poison message blocks everything. A working answer needs both halves. Retry what might succeed later, give up on what will not, and put what you gave up on somewhere safe and visible. That place is a dead-letter queue (DLQ).
Step 1 of 9
An order consumer reads from a queue and updates inventory. Almost every message succeeds on the first try. The queue is configured to allow three receives before it gives up on a message.
Read the steps as text
- An order consumer reads from a queue and updates inventory. Almost every message succeeds on the first try. The queue is configured to allow three receives before it gives up on a message.
- Then a message arrives that the consumer cannot handle. Order 18 has a quantity of minus one, and the code throws an exception. The consumer does not acknowledge, so the message stays on the queue.
- The queue redelivers it after a delay. Nothing about the message has changed, so it fails in the same way. Retrying helps when the cause is a timeout or a restart. It does nothing for bad data or a bug.
- Without a limit this would repeat for ever. Each attempt occupies a worker and fills the error log, and on an ordered stream it holds up every message queued behind it. A message like this is called a poison message.
- The message has now used its three receives. The queue does not deliver it a fourth time and moves it to the dead-letter queue. The main queue is clear, and the consumer goes back to processing good messages.
- A dead-letter queue that nobody watches is only a slower way of losing data. An alarm fires as soon as its depth is above zero, and the on-call engineer is told which queue it is.
- The engineer reads the message and the error recorded with it, and finds the missing validation. They deploy a fix so that the consumer handles a negative quantity properly.
- With the fix live, they redrive, which moves the dead-lettered messages back to the source queue. Order 18 is delivered again, and this time it is processed. The consumer must be idempotent, because a redrive is one more delivery.
- Retry transient failures with backoff, cap the attempts, and park whatever still fails where a person will see it. Notice the cost: order 19 was processed before order 18. A dead-letter queue gives up strict ordering in exchange for progress.
Two kinds of failure
Everything depends on telling these apart.
| Transient | Permanent | |
|---|---|---|
| Examples | Timeout, connection reset, 503, lock conflict | Malformed payload, schema mismatch, failed validation |
| Will a retry help? | Probably, after a wait | No |
| Right response | Retry with backoff | Dead-letter at once |
When the code can tell which it is, it should act on that: a parsing error or a 400 from a downstream API goes straight to the DLQ without using up retries. When it cannot tell, a bounded number of retries is how you find out. A failure that survives five attempts over ten minutes is treated as permanent.
A third case looks like poison and is not: a dependency is down and every message fails. Dead-lettering them all only moves the whole stream into the DLQ. The right response is to stop consuming, with a circuit breaker or by pausing the consumer, until the dependency recovers.
Retry policies
A retry policy answers three questions.
How many attempts? Enough to ride out a typical transient fault, usually three to five. More attempts add delay and load without much more success.
How long between them? An immediate retry hits a struggling dependency at its worst moment. Use exponential backoff, for example 1 s, 5 s, 30 s and 2 min, with random jitter so that messages which failed together do not retry together. Retries and timeouts covers backoff and jitter in detail.
Where does the message wait?
- In the consumer, sleeping between attempts. This is simple and preserves order, but it blocks the worker or the partition for the whole wait. In Kafka, a consumer that waits longer than
max.poll.interval.msis removed from its group, so in-process retries must stay short. - In the broker, by not acknowledging. SQS redelivers after the visibility timeout, and the consumer can extend that timeout for one message to get backoff. The worker is free in the meantime.
- In a separate retry queue or topic, with a delay. The original is acknowledged, so the main stream moves on.
How brokers support it
Amazon SQS counts receives per message. A redrive policy on the source queue names a dead-letter queue and a maxReceiveCount. Once a message has been received more than that many times without being deleted, SQS moves it. SQS can also redrive messages from the DLQ back to the source queue when you are ready.
RabbitMQ uses dead-letter exchanges. A message is dead-lettered when a consumer rejects it without requeueing, when its TTL expires, or when its queue overflows. Quorum queues can also enforce a delivery limit. A common trick builds delayed retries from these parts: publish to a “wait” queue that has a TTL and no consumers, and let expiry dead-letter the message back to the work queue.
Kafka brokers have no dead-letter feature, because the broker does not track individual records. The consumer application implements it: on giving up, it produces the record to a dead-letter topic and then commits the offset. Kafka Connect (for sink connectors) and frameworks such as Spring Kafka provide this ready-made.
Retry topics in Kafka
Blocking a partition while one record backs off for two minutes is rarely acceptable, so Kafka consumers use retry topics, a pattern Uber’s engineers described publicly in 2018. On failure the consumer publishes the record to orders-retry-1 and commits. A consumer of that topic waits until the record is, say, 30 seconds old before trying again. A second failure moves it to orders-retry-2 with a longer delay, and a final failure moves it to orders-dlq. The main topic never stalls.
Carry metadata in the record headers: the original topic, partition and offset, the attempt count, the time of the first failure and the error. Whoever opens the DLQ later will need all of it.
What to do with a DLQ
A DLQ is a holding area, not a destination.
- Alert on it. A message in the DLQ of a critical flow is a customer whose order, payment or email did not happen. Alarm on depth above zero, or on rate for noisier flows, and on the age of the oldest message.
- Make it inspectable. Keep the payload and the failure metadata, with retention long enough to cover a long weekend plus a fix. On SQS standard queues a message’s age keeps counting from when it was first sent, so give the DLQ a longer retention period than its source.
- Classify, then act. For a consumer bug: fix, deploy, then redrive the messages to the source. For bad data from a producer: fix it upstream, then repair or discard. For messages that are now obsolete, such as an order since cancelled: discard deliberately and record that you did.
- Redrive safely. A redrive is one more delivery, possibly days late, so the consumer must be idempotent and tolerate stale events. Redrive at a controlled rate so the backlog does not swamp live traffic.
Ordering implications
Moving a failed message aside lets later messages overtake it. Often that is fine: emails and thumbnails do not care. Where order matters per key it is not. If “account created” is dead-lettered and “account updated” for the same account is processed, the update fails or is applied to nothing.
There are three options, in increasing strictness:
- Accept reordering and make the consumer tolerant, for example with a version number so it ignores anything older than what it holds.
- Park the key. Once a message for a key is in retry or the DLQ, send every later message for that key after it and release them in order. Other keys keep flowing, at the cost of tracking which keys are parked.
- Stop the partition and page someone. This is right when the stream is a strict sequence, such as change data capture from a database, where skipping one record corrupts what follows.
SQS FIFO queues behave like the second option by design. A message that keeps failing blocks its own message group, while other groups carry on, until it succeeds or is dead-lettered.
When to use one and when not to
Use a DLQ on any consumer whose messages matter and can fail for reasons a retry will not fix, which is most consumers.
Do not add one where a message is worthless once late, such as a live-location update: drop it and count the drop. Do not dead-letter out of a strictly ordered stream. And do not let a DLQ stand in for validation at the producer. Rejecting a bad order at the API is cheaper than finding it three services later.
In the interview
Whenever you draw a consumer, say what happens to a message that keeps failing. A complete answer takes four sentences: “Transient errors retry with exponential backoff and jitter, up to five attempts. Errors I can identify as permanent skip the retries. After that the message goes to a dead-letter queue with the error attached, and we alarm on its depth. Once the cause is fixed we redrive, which is safe because the consumer is idempotent.” If the stream is keyed, add the ordering point: say whether a dead-lettered message may be overtaken, and what you do if it may not.
Key takeaways
- A poison message fails every time it is delivered. Without a limit it wastes capacity on a queue and blocks a whole partition on a log.
- Separate transient failures, which deserve retries with backoff, from permanent ones, which should be dead-lettered straight away.
- A retry policy says how many attempts, how long between them, and where the message waits: in the consumer, in the broker, or in a retry topic.
- SQS and RabbitMQ dead-letter in the broker. Kafka has no broker feature, so the consumer publishes to retry and dead-letter topics itself.
- A dead-letter queue needs an alarm, failure metadata, an owner and a redrive path. Unwatched, it is delayed data loss.
- Moving a message aside lets later ones overtake it, so decide per stream whether to accept reordering, park the key or stop.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What is a poison message?
A message that fails every time it is processed, because of bad data or a bug it triggers. Retrying never helps, so it must be set aside after a bounded number of attempts.
Which failures should skip retries and be dead-lettered at once?
Ones the consumer can identify as permanent: a payload that cannot be parsed, a schema mismatch, a validation failure, a 4xx response that will not change.
How does SQS decide to dead-letter a message?
The source queue has a redrive policy with a maxReceiveCount. When a message has been received more times than that without being deleted, SQS moves it to the configured dead-letter queue.
How do you get a dead-letter queue in Kafka?
The consumer does it: after giving up, it produces the record to a dead-letter topic with failure metadata in headers, then commits the offset. Retry topics with delays sit in between.
What must exist around a dead-letter queue?
An alarm on depth and age, the error and origin stored with each message, enough retention to fix the cause, an owner, and a controlled redrive into an idempotent consumer.
What does dead-lettering do to ordering?
Later messages overtake the one set aside. Either make the consumer tolerate that, park later messages for the same key, or stop the stream when it is a strict sequence.