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. Here you will see what a consumer should do when handling an event fails.
Why failures need a policy
A consumer can fail for two different reasons.
- A transient failure goes away if you wait. Examples are a database timeout, a rate limit, or a downstream service restarting.
- A permanent failure will never succeed, however often you retry. Examples are a malformed payload, a missing required field, or a bug in the handler.
Retrying a permanent failure forever wastes capacity. Worse, on a queue that delivers in order, one bad event can block every event behind it. This is called a poison message. A good policy retries transient failures a limited number of times and then moves the event aside.
Retries with backoff
Retrying immediately usually fails again, because the cause has not cleared. If many consumers retry at once, they can also overload a service that is trying to recover. Backoff means waiting longer after each failed attempt. Exponential backoff doubles the wait each time. Jitter adds a random amount to the wait, so that consumers do not retry in lockstep.
import random
import time
class PermanentError(Exception):
"""The event can never be processed successfully."""
def process_with_retry(event, handler, max_attempts=4, base_delay=0.5):
for attempt in range(1, max_attempts + 1):
try:
handler(event)
return True
except PermanentError:
return False # retrying would not help
except Exception:
if attempt == max_attempts:
return False
delay = base_delay * 2 ** (attempt - 1)
time.sleep(random.uniform(0, delay)) # full jitter
return FalseThe function returns False when it gives up. The caller decides what happens next.
Dead-letter queues
A dead-letter queue (DLQ) is a separate queue that holds events the consumer could not process. After the retry limit, the consumer moves the event there and acknowledges the original. The main flow continues, and nothing is silently lost.
from collections import deque
main_queue = deque([{"id": "e-1", "amount": 10}, {"id": "e-2"}])
dead_letters = []
def handler(event):
if "amount" not in event:
raise PermanentError("missing amount")
print("processed", event["id"])
while main_queue:
event = main_queue.popleft()
if not process_with_retry(event, handler, base_delay=0.01):
dead_letters.append({"event": event, "reason": "retries exhausted"})
print("dead letters:", dead_letters)Store the original event, the error, the attempt count and a timestamp. Without that context, nobody can tell why the event failed.
Operating a DLQ
A DLQ is not a trash bin. Treat it as an inbox that someone must read.
- Alert when the DLQ depth is above zero.
- Inspect the stored error and decide whether it was a bug, bad data or an outage.
- Fix the cause first. Replaying before the fix only fails again.
- Replay events to the main queue. Idempotent handlers make this safe.
Common errors
| Error | Result |
|---|---|
| Retrying with no limit | Poison messages block the queue |
| Retrying with no delay | Overloads a recovering service |
| No jitter | Many consumers retry at the same moment |
| Nobody watches the DLQ | Failed events are lost in practice |
| Treating every error as transient | Bugs consume retry capacity |
Exercise
A consumer receives an event with a missing required field. It currently retries five times with exponential backoff, then moves the event to the DLQ. What should change, and why?
Show answer
Classify the missing field as a permanent failure and send the event to the DLQ immediately. Waiting cannot fix malformed data, so the five retries only delay the event and use up capacity. Keep backoff for transient errors such as timeouts.