Sub topic 7
Retries and Dead-Letter Queues
This chapter assumes you know how acknowledgements work, what at-least-once delivery means, and why consumers should be idempotent. Those topics come from the earlier chapters. Here the question is what to do when a message fails. You can retry it, delay it, or set it aside for a person to inspect.
Why failures need a policy
A consumer can fail on a message for two different reasons.
- Transient failures go away if you wait. Examples are a database that is restarting, a network timeout, or a rate limit from a downstream API. Retrying later usually works.
- Permanent failures never go away. Examples are a malformed JSON body, a reference to a record that does not exist, or a bug in your handler. Retrying the same message gives the same error every time.
A consumer that treats both kinds the same way causes trouble. If it requeues every failure immediately, a permanent failure becomes a poison message. This is a message that fails every time it is delivered. The broker hands it back at once, the consumer fails again, and the loop uses CPU and floods the logs. In a queue with ordering, the poison message can also block everything behind it.
A good policy answers three questions:
- Which failures should be retried, and which should not?
- How long should the system wait between attempts?
- Where does a message go after the attempts run out?
Immediate requeue and why it fails
In the previous chapter's consumer, basic_nack with requeue=True puts the message back at the head of the queue. The next delivery follows almost immediately. This is fine for a single glitch. It is a poor choice when the cause lasts longer than a few milliseconds, because the consumer burns through all its attempts before the dependency recovers. It also keeps hammering a service that is already struggling.
Two things are missing from immediate requeue: a delay between attempts, and a limit on the number of attempts.
Retry with delay and backoff
Backoff means waiting longer after each failed attempt. A common schedule is exponential: 1 second, 2 seconds, 4 seconds, 8 seconds, and so on, up to a cap. Add jitter, a small random amount, so that many failing messages do not all retry at the same instant.
There are two places to implement the delay.
| Approach | How it works | Trade-off |
|---|---|---|
| In-process sleep | The consumer catches the error, sleeps, and tries again before acknowledging. | Simple, but the message stays unacknowledged and holds a prefetch slot. A long sleep stalls the consumer. Restarts lose the attempt count. |
| Broker-side delay | The consumer rejects the message into a retry queue that holds it for a set time, then returns it to the main queue. | More setup, but the consumer stays free and the delay survives restarts. |
Use in-process retries only for very short, bounded cases, such as two quick attempts against a flaky connection. For anything longer, delay at the broker.
Delay queues in RabbitMQ
RabbitMQ has no built-in per-message delay in its core. The usual technique uses a queue with a time-to-live (TTL), which is a maximum time a message may sit in that queue. When the TTL expires, the message is dead-lettered to another exchange. If that exchange routes back to the work queue, the message returns after the delay.
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
# Main work queue. Rejected messages go to the dead-letter exchange.
ch.exchange_declare(exchange="work", exchange_type="direct", durable=True)
ch.exchange_declare(exchange="retry", exchange_type="direct", durable=True)
ch.exchange_declare(exchange="dead", exchange_type="direct", durable=True)
ch.queue_declare(
queue="tasks",
durable=True,
arguments={
"x-dead-letter-exchange": "retry",
"x-dead-letter-routing-key": "tasks.retry",
},
)
ch.queue_bind(queue="tasks", exchange="work", routing_key="tasks")
# Retry queue. Messages wait 10 seconds, then expire back to the work exchange.
ch.queue_declare(
queue="tasks.retry",
durable=True,
arguments={
"x-message-ttl": 10000,
"x-dead-letter-exchange": "work",
"x-dead-letter-routing-key": "tasks",
},
)
ch.queue_bind(queue="tasks.retry", exchange="retry", routing_key="tasks.retry")
# Final parking queue for messages that have used up their attempts.
ch.queue_declare(queue="tasks.dead", durable=True)
ch.queue_bind(queue="tasks.dead", exchange="dead", routing_key="tasks.dead")
conn.close()With this topology, basic_nack(requeue=False) on a message in tasks sends it to tasks.retry. It waits 10 seconds and then returns to tasks. The delay is fixed per retry queue. To get growing delays, create several retry queues (for example 10 s, 60 s, 10 min) and choose among them.
Counting attempts
A retry limit needs an attempt count. Brokers handle this differently.
- RabbitMQ adds an
x-deathheader each time a message is dead-lettered. It records the queue, the reason, and a runningcount. You can read it in the consumer. - Amazon SQS exposes
ApproximateReceiveCountand lets a redrive policy setmaxReceiveCount. After that many receives, SQS moves the message to the dead-letter queue by itself. - Some systems have no counter. In that case, put an
attemptfield in a header or in the body, and republish the message with the field incremented.
Here is a consumer that reads the count, retries transient errors, and sends permanent errors or exhausted messages to the dead-letter exchange.
import json
import pika
MAX_ATTEMPTS = 4
class PermanentError(Exception):
"""The message can never succeed, so retrying is pointless."""
def process(body):
data = json.loads(body) # raises ValueError on malformed input
if "image_id" not in data:
raise PermanentError("missing image_id")
print("handling", data["image_id"])
def death_count(properties):
deaths = (properties.headers or {}).get("x-death", [])
return sum(d.get("count", 0) for d in deaths)
def handle(ch, method, properties, body):
tag = method.delivery_tag
try:
process(body)
ch.basic_ack(delivery_tag=tag)
except (PermanentError, ValueError):
# Permanent: publish straight to the dead-letter queue, then ack the original.
ch.basic_publish(exchange="dead", routing_key="tasks.dead", body=body)
ch.basic_ack(delivery_tag=tag)
except Exception:
if death_count(properties) + 1 >= MAX_ATTEMPTS:
ch.basic_publish(exchange="dead", routing_key="tasks.dead", body=body)
ch.basic_ack(delivery_tag=tag)
else:
# Transient: dead-letter into the retry queue via the queue's policy.
ch.basic_nack(delivery_tag=tag, requeue=False)
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.basic_qos(prefetch_count=10)
ch.basic_consume(queue="tasks", on_message_callback=handle, auto_ack=False)
ch.start_consuming()Note the order in the two dead-letter paths: publish first, acknowledge second. If the consumer crashes between them, the message is delivered again and may land in the dead-letter queue twice. That is a duplicate, which is acceptable under at-least-once delivery. The reverse order could lose the message.
Note also that the dead-letter publish above uses a non-persistent message. For anything you cannot afford to lose, set delivery_mode to persistent, as you did in the durability examples.
The dead-letter queue
A dead-letter queue (DLQ) is a queue that collects messages the system gave up on. A message ends up there for one of these reasons:
- The consumer rejected it with
requeue=Falseand no retry path exists. - It exceeded the maximum number of attempts.
- Its TTL expired.
- The queue hit its length limit and dropped it.
A DLQ is not a trash can. It exists so that no message disappears silently. Treat it as an inbox that someone owns.
Working with the DLQ
- Alert on it. A DLQ with a nonzero depth should notify a person. The monitoring chapter covers how.
- Keep the context. Store the original headers, the failure reason, the exception text, and the timestamp, so a person can diagnose the cause without guessing.
- Fix the cause first. Replaying messages into an unchanged consumer repeats the failure.
- Redrive deliberately. After the fix, move messages back to the work queue in small batches. Tools exist for this, such as RabbitMQ's shovel plugin and the SQS redrive feature.
- Set a retention period. Unbounded DLQs fill disks. Decide how long a dead message stays before it is archived or deleted.
Because a redriven message is delivered again, the consumer must be idempotent. A message that partly succeeded before failing will repeat its side effects if the handler is not safe to run twice.
Edge cases and common errors
- Retry storms. If a downstream service is down, every message fails and retries together. Backoff with jitter spreads the load. A circuit breaker, which stops calling a failing dependency for a while, avoids wasted attempts.
- Retrying permanent errors. Classify errors. Validation and parsing errors go to the DLQ at once. Timeouts and connection errors are retried.
- Losing ordering. A message sent to a retry queue comes back after later messages have been processed. If order matters, retrying out of line breaks it. Either block the partition until the message succeeds, or design handlers to tolerate reordering.
- Large retry delays and TTL. In RabbitMQ, a per-queue TTL is simple and reliable. Per-message TTL only expires messages at the head of a queue, so a short-TTL message behind a long-TTL one waits longer than expected.
- Dead-lettering and acknowledgement mismatch. A message that is dead-lettered only on
nackorrejectwithrequeue=False. If your consumer catches an error and still callsbasic_ack, the failure is hidden and nothing is retried. - Unbounded retry. A limit of "forever" turns every bug into a permanent load. Always set a maximum.
Summary of the policy
| Situation | Action |
|---|---|
| Success | Acknowledge. |
| Transient error, attempts remaining | Reject without requeue so the message waits in a retry queue. |
| Transient error, attempts exhausted | Publish to the DLQ, then acknowledge. |
| Permanent error | Publish to the DLQ, then acknowledge. |
| After a fix | Redrive from the DLQ in small batches to an idempotent consumer. |
Exercise
A consumer calls basic_nack(requeue=True) for every exception. A message with invalid JSON arrives. What happens, and what two changes fix it?
Show answer
The message is requeued immediately, fails again, and repeats in a tight loop. It is a poison message that wastes CPU, fills logs, and can block messages behind it. Fix it by (1) classifying the error as permanent and sending the message to a dead-letter queue instead of requeueing, and (2) for transient errors, adding a delay and a maximum attempt count, for example through a TTL retry queue and the x-death count.
Exercise
In the dead-letter path, why should the consumer publish to the DLQ before acknowledging the original message, and what is the cost of that order?
Show answer
If the consumer crashes after publishing but before acknowledging, the broker redelivers the original, so no message is lost. The cost is a possible duplicate in the DLQ. Acknowledging first would risk losing the message if the crash happened before the publish. Duplicates are acceptable under at-least-once delivery.
Exercise
Your DLQ contains 500 messages after a bug in the consumer. The bug is now fixed. Describe a safe way to process them.
Show answer
First confirm the fixed consumer is deployed. Then redrive a small batch back to the work queue and check that the messages succeed. Continue in larger batches while watching error rates and the DLQ depth. The consumer must be idempotent, because some of these messages may have partly succeeded before they failed.