Sub topic 7
Retries and dead-letter queues
This chapter assumes you know how acknowledgements work, that delivery is usually at-least-once, and that consumers should be idempotent. It covers what to do when a message fails.
Why failures need a plan
A consumer can fail on a message for two kinds of reasons.
- Transient failures go away on their own. Examples are a database timeout or a briefly unavailable API. Retrying later usually works.
- Permanent failures never succeed. Examples are malformed JSON or a reference to a record that does not exist. Retrying only wastes work.
The worst response is to requeue a failing message immediately. The broker hands it straight back, it fails again, and one bad message, called a poison message, can use a consumer's whole capacity in a tight loop.
Retry with a delay and a limit
A sound retry policy has three parts: a delay between attempts, a growing delay (backoff), and a maximum attempt count. After the last attempt, the message moves to a dead-letter queue.
A dead-letter queue (DLQ) is an ordinary queue that holds messages the system gave up on. It keeps them for inspection instead of losing them or blocking the main queue.
Configuring a DLQ in RabbitMQ
In RabbitMQ, a queue can name a dead-letter exchange. Messages that are rejected with requeue=False are republished there. The consumer from the acknowledgements chapter already does this with basic_nack. The queue needs the matching setup.
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.exchange_declare(exchange="tasks.dlx", exchange_type="direct", durable=True)
ch.queue_declare(queue="tasks.dead", durable=True)
ch.queue_bind(queue="tasks.dead", exchange="tasks.dlx", routing_key="tasks")
ch.queue_declare(
queue="tasks.v2",
durable=True,
arguments={
"x-dead-letter-exchange": "tasks.dlx",
"x-dead-letter-routing-key": "tasks",
},
)
conn.close()The queue is named tasks.v2 because RabbitMQ rejects a redeclaration of an existing queue with different arguments. To add a DLQ to a live queue, use a new queue or a broker policy.
Delayed retries
Rejecting to a DLQ sends a message away for good. To retry later, create a retry queue with a message TTL (time to live) that dead-letters back to the work queue. A message waits in the retry queue until its TTL expires, then returns to the work queue.
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(
queue="tasks.retry",
durable=True,
arguments={
"x-message-ttl": 30000,
"x-dead-letter-exchange": "",
"x-dead-letter-routing-key": "tasks.v2",
},
)
conn.close()Here the consumer publishes failed messages to tasks.retry and acknowledges the original. After 30 seconds, the message returns to tasks.v2. The consumer must track the attempt number, for example in a message header, and send the message to the DLQ once it reaches the limit.
Common errors
- Retrying permanent failures. Classify errors. Send validation errors straight to the DLQ.
- Infinite requeue.
requeue=Truewith no counter creates a hot loop. - Retrying non-idempotent work. A retry is a redelivery. Without idempotency, a retry can charge a customer twice.
- Ignoring the DLQ. An unwatched DLQ is silent data loss. Alert when its depth is above zero.
- Losing context. Keep the original body, the error text, and the attempt count so someone can diagnose and replay.
Exercise
A consumer fails on a message because the payload is not valid JSON. Should it retry with backoff or dead-letter the message immediately? Explain why.
Show answer
Dead-letter it immediately. Invalid JSON is a permanent failure, so no number of retries will fix it. Retrying only delays other work and wastes capacity. Keep the message in the DLQ with the error so someone can inspect it.
Exercise
Why does the delayed-retry example publish the message to the retry queue and acknowledge the original, instead of calling basic_nack with requeue=True?
Show answer
With requeue=True the broker redelivers immediately, so there is no delay and a failing message loops rapidly. Publishing to a queue with a TTL adds a wait before the message returns to the work queue. Acknowledging the original removes it from the work queue, so only the retry copy remains.