Sub topic 11
Retries, Backoff and Dead-Letter Queues
This chapter assumes you know what a broker is, how at-least-once delivery works, and why consumers should be idempotent. It covers what a consumer should do when handling an event fails: how to retry, how to space the retries out, and where to put events that never succeed.
Why failures need a policy
A consumer fails on an event for one of two broad reasons.
- Transient failures go away if you wait. Examples are a database timeout, a rate limit from a downstream API, a deploy that restarts a dependency, or a lock conflict.
- Permanent failures repeat every time. Examples are a malformed payload, a missing required field, a schema version the consumer does not understand, or a bug in the handler for one particular input.
Retrying a transient failure is the right response. Retrying a permanent failure only wastes capacity. A good policy tells the two apart, retries the first kind a limited number of times, and moves the second kind out of the way.
Retries also depend on earlier chapters. Because a retry is a redelivery, the handler may run more than once for the same event. If the handler is not idempotent, retries cause duplicate side effects.
The poison message problem
A poison message is an event that makes the consumer fail every time it is processed. Suppose a consumer reads a queue in order and the broker redelivers a failed message immediately. One poison message then blocks everything behind it, and the consumer spends all its time failing on the same event.
On a partitioned log, the problem is sharper. Events within a partition are processed in order, so a consumer that refuses to move past a failing event stalls every later event for that key range. Ordering and retries pull in opposite directions, and you must choose which one wins for each failure.
Retry strategies
Immediate retry
The consumer tries again right away, usually inside the same process. This works for brief glitches such as a dropped connection. Use it for one or two attempts at most. If the dependency is overloaded, immediate retries add load to a system that is already struggling.
Fixed delay
The consumer waits the same interval between attempts, for example five seconds. This is simple, but every failing consumer retries at the same rhythm.
Exponential backoff
The wait grows after each failure, commonly doubling: 1 s, 2 s, 4 s, 8 s. This gives a struggling dependency room to recover. You normally set a maximum delay so the wait does not grow without bound.
Jitter
If a thousand consumers fail at the same moment, plain exponential backoff makes all thousand retry at the same moments too. Each wave can knock the dependency over again. Jitter adds randomness to each delay so retries spread out. A common variant, called full jitter, picks a random delay between zero and the exponential ceiling.
The following Python function computes a delay with exponential backoff, a cap, and full jitter.
import random
def backoff_delay(attempt, base=1.0, cap=60.0):
"""Return seconds to wait before retry number `attempt` (starting at 1)."""
ceiling = min(cap, base * (2 ** (attempt - 1)))
return random.uniform(0, ceiling)
for attempt in range(1, 8):
print(attempt, round(backoff_delay(attempt), 2))The ceiling for attempts 1 to 7 is 1, 2, 4, 8, 16, 32 and 60 seconds. The printed values vary from run to run because of the random draw.
Classifying errors
Before retrying, the handler should decide whether the error can succeed later. A simple approach is to define two kinds of exceptions and let the consumer loop react to each.
import random
import time
class TransientError(Exception):
"""Worth retrying: timeouts, rate limits, temporary outages."""
class PermanentError(Exception):
"""Will never succeed: bad payload, unknown schema version."""
def backoff_delay(attempt, base=0.1, cap=2.0):
return random.uniform(0, min(cap, base * (2 ** (attempt - 1))))
def process_with_retries(event, handler, dead_letters, max_attempts=4):
for attempt in range(1, max_attempts + 1):
try:
handler(event)
return "ok"
except PermanentError as exc:
dead_letters.append({"event": event, "reason": str(exc), "attempts": attempt})
return "dead-lettered"
except TransientError as exc:
if attempt == max_attempts:
dead_letters.append({"event": event, "reason": str(exc), "attempts": attempt})
return "dead-lettered"
time.sleep(backoff_delay(attempt))
calls = {"n": 0}
def flaky_handler(event):
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("database timeout")
def bad_handler(event):
raise PermanentError("missing field: orderId")
dlq = []
print(process_with_retries({"id": "e-1"}, flaky_handler, dlq))
print(process_with_retries({"id": "e-2"}, bad_handler, dlq))
print(dlq)The first event fails twice with a transient error and then succeeds. The second event fails with a permanent error, so it goes to the dead-letter list on the first attempt without any retries.
Classification is often imperfect. An HTTP 500 from a downstream service might be a temporary outage or a bug triggered by your input. A common compromise is to treat unknown errors as transient but limit the number of attempts, so a misclassified permanent error still ends up in the dead-letter queue.
Dead-letter queues
A dead-letter queue (DLQ) is a separate queue or topic that receives events the consumer could not process. Moving the event there lets the main flow continue. The event is not lost, and a person or a tool can inspect it later.
Most brokers support this directly. You typically configure a maximum delivery count on the main queue and name the DLQ. After that many failed deliveries, the broker moves the message itself. In other setups, such as a log-based broker, the consumer publishes the failed event to a dead-letter topic and then commits its offset.
What to store with a dead-lettered event
An event on its own is hard to debug. Keep the original payload unchanged, and add metadata as headers or in a wrapper:
- The original topic or queue, and partition and offset if there are any.
- The consumer name and version.
- The error message and stack trace.
- The attempt count and the time of the first and last failure.
- A trace or correlation ID, so you can find related logs.
Staged retry topics
Blocking the main consumer while it sleeps between retries stalls everything behind that event. A common alternative is a chain of retry queues with increasing delays.
placeholderInstead of the placeholder above, use the diagram below.
The consumer moves a failing event to the next retry queue and goes on to the following event. Ordering is no longer guaranteed, because a retried event arrives after events that were originally behind it. Use this design only when the events do not depend on strict order, or when your handler can tolerate out-of-order arrival.
Handling what lands in the DLQ
A DLQ is not a trash can. Without an owner, it becomes a place where data quietly rots.
- Alert on depth. Any message in a DLQ is worth a notification, or at least a dashboard metric. A growing count means something is broken.
- Diagnose. Read the stored error and payload. Decide whether the cause was a bug, bad data, or an outage that has ended.
- Fix the cause first. Fixing the handler, or a schema mismatch, comes before replaying. Otherwise the events fail again.
- Redrive. Send the events back to the main queue or to a dedicated reprocessing consumer. Many brokers provide a redrive feature.
- Discard deliberately. If an event is truly invalid, record why you dropped it.
Redriving relies on idempotency. Some of the dead-lettered events may have partly succeeded before failing, and the handler will see them again.
Limits and common mistakes
- Retrying forever. An unlimited retry loop turns one bad event into permanent load. Always cap attempts or total retry time.
- Retrying without backoff. Tight loops make an outage worse and can trigger rate limits.
- Retries at every layer. If the HTTP client retries three times, the handler retries three times, and the broker redelivers three times, one failure produces 27 calls. Choose one layer to own retries, and keep the others at a minimum.
- Retry budgets exceeded by the visibility timeout. On queues with a visibility timeout, if the handler plus its backoff sleeps takes longer than the timeout, the broker redelivers the message to another consumer while the first is still working. Set the timeout above the longest expected processing time, or extend it while working.
- A DLQ nobody watches. The system appears healthy while events pile up.
- Dead-lettering because of a dependency outage. If a downstream service is down for an hour, every event may exhaust its retries and land in the DLQ. Consider a circuit breaker, which pauses consumption while the dependency is unhealthy, so events wait in the main queue instead.
- Sensitive data in the DLQ. Dead-lettered payloads are copies of your data. Apply the same access control and retention rules as the main topic.
Choosing a policy
| Situation | Suggested approach |
|---|---|
| Brief network blips | One or two immediate retries |
| Overloaded or rate-limited dependency | Exponential backoff with jitter and a cap |
| Strict per-key ordering required | Retry in place, accept the stall, alert quickly |
| Order not important, high throughput | Staged retry queues, then a DLQ |
| Malformed or unknown-version event | No retry, dead-letter immediately |
| Extended dependency outage | Circuit breaker, so events stay in the main queue |
Exercise
A consumer processes payment events from a partitioned topic where order within an account matters. One event has a malformed amount field and fails on every attempt. The consumer retries it forever with a fixed one-second delay. What goes wrong, and what would you change?
Show answer
The malformed event is a permanent failure, so retrying never helps. Because order within the partition matters, the consumer cannot move past the event, and every later event for that account's partition waits behind it. Change three things: classify the error as permanent and skip retries for it, publish the event with its error details to a dead-letter topic and commit the offset so processing continues, and alert on the DLQ. For genuinely transient errors, use capped exponential backoff with jitter and a maximum attempt count. Because later events for that account proceed without the dead-lettered one, decide whether that is safe, or pause that account until someone fixes the event.
Exercise
Why must a consumer be idempotent before you add retries and DLQ redrive?
Show answer
Retries and redrive both deliver an event again. A handler that failed after partly applying its change will apply that change a second time unless it can recognize the event as already handled, for example by checking a stored event ID. Without idempotency, retries cause duplicate charges, duplicate emails or double updates.