Dead Letter Queue Runbook
Operational runbook for triaging, fixing, and replaying dead letter queue messages in Kafka and RabbitMQ, with inspection commands, root cause analysis, and alert rules.
Overview
This runbook covers the operational procedures for handling messages that land in a dead letter queue (DLQ) in Kafka and RabbitMQ. A DLQ captures messages the consumer failed to process: deserialization errors, business rule failures, or a downstream service that went away. Left alone, a DLQ fills up silently until it becomes an incident; treated as a queue of actionable failures, it becomes a recovery tool.
The procedures below assume you already have a DLQ configured. If you’re setting one up from scratch, see the Dead Letter Queues recipe for per-broker configuration, or the Dead Letter Channel pattern for the architectural trade-offs behind the approach.
Every DLQ workflow follows the same shape:
The rest of the runbook walks each stage: setup for reference, inspection, root cause analysis, replay, and the monitoring that tells you a DLQ is filling up before it pages anyone.
1. DLQ Setup
1.1 RabbitMQ DLQ Configuration
RabbitMQ dead-letters a message when a consumer rejects it with requeue=False, when the message TTL expires, or when the queue overflows. The routing glue is a dead-letter exchange (DLX) declared on the source queue:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq-prod'))
channel = connection.channel()
# Declare the dead letter exchange
channel.exchange_declare(
exchange='prod.orders.dlx.direct',
exchange_type='direct',
durable=True,
)
# Declare the dead letter queue with 7-day retention
channel.queue_declare(
queue='prod.orders.dlq.failed-messages',
durable=True,
arguments={
'x-message-ttl': 604800000, # 7 days in ms
},
)
# Bind the DLQ to the DLX
channel.queue_bind(
exchange='prod.orders.dlx.direct',
queue='prod.orders.dlq.failed-messages',
routing_key='order-processing-failed',
)
# Configure the main queue to dead-letter into the DLX
channel.queue_declare(
queue='prod.orders.payment-service.process-payment',
durable=True,
arguments={
'x-dead-letter-exchange': 'prod.orders.dlx.direct',
'x-dead-letter-routing-key': 'order-processing-failed',
},
)
1.2 Kafka DLQ Topic Setup
Kafka has no broker-side dead-lettering; the consumer application writes failed records to a dedicated topic. Give the DLQ topic the same durability guarantees as the source topic:
# Create the DLQ topic
kafka-topics.sh --bootstrap-server kafka:9092 \
--create \
--topic prod.orders.order-created.dlq \
--partitions 6 \
--replication-factor 3 \
--config retention.ms=604800000 \
--config cleanup.policy=delete
Keep partition count aligned with the source topic. Replay tooling that preserves keys benefits from matching partition layouts, and a DLQ with fewer partitions becomes a bottleneck when you replay a large backlog.
1.3 Kafka Consumer DLQ Producer
The consumer retries in place a few times, then writes the record to the DLQ with enough metadata headers to reconstruct what failed and where:
import logging
from datetime import datetime, timezone
from confluent_kafka import Consumer, Producer, KafkaError
logger = logging.getLogger(__name__)
consumer = Consumer({
'bootstrap.servers': 'kafka:9092',
'group.id': 'payment-service',
'auto.offset.reset': 'earliest',
'enable.auto.commit': False,
})
dlq_producer = Producer({'bootstrap.servers': 'kafka:9092'})
consumer.subscribe(['prod.orders.order-created.v1'])
MAX_RETRIES = 3
def process_with_dlq():
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
if msg.error().code() == KafkaError._PARTITION_EOF:
continue
logger.error("Consumer error: %s", msg.error())
continue
try:
process_message(msg.value())
consumer.commit(msg)
except Exception as e:
headers = dict(msg.headers() or [])
retry_count = int(
headers.get('retry-count', b'0').decode()
) + 1
if retry_count <= MAX_RETRIES:
# Retry: requeue on the source topic with an incremented count
dlq_producer.produce(
topic='prod.orders.order-created.v1',
key=msg.key(),
value=msg.value(),
headers=[('retry-count', str(retry_count).encode())],
)
else:
# Max retries exhausted: write to the DLQ with failure metadata
dlq_producer.produce(
topic='prod.orders.order-created.dlq',
key=msg.key(),
value=msg.value(),
headers=[
('retry-count', str(retry_count).encode()),
('error', str(e).encode()),
('original-topic', msg.topic().encode()),
('original-partition', str(msg.partition()).encode()),
('original-offset', str(msg.offset()).encode()),
('failed-at', datetime.now(timezone.utc)
.isoformat().encode()),
],
)
# Commit either way — requeuing instead of re-raising avoids
# reprocessing the same poison record forever
consumer.commit(msg)
Two details matter here. First, the commit happens after the record is safely produced to its next destination, not after processing, and that’s what prevents the infinite loop the pattern article warns about. Second, everything the on-call engineer will need later (error, original offset, timestamp) travels as headers, so no one has to grep consumer logs at 3 AM to find out why a record is in the DLQ.
1.4 SQS Redrive Policy
SQS dead-letters broker-side through a redrive policy: after maxReceiveCount receives, the message moves to the DLQ automatically, with no consumer code required. Attach the policy to the source queue:
aws sqs set-queue-attributes \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789012/prod-orders-payments \
--attributes '{
"RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:123456789012:prod-orders-dlq\",\"maxReceiveCount\":3}",
"VisibilityTimeout": "30"
}'
Mind the interaction between maxReceiveCount and VisibilityTimeout: the count tracks receives, not failed processing attempts, so a long visibility timeout paired with a low count can dead-letter messages that were merely slow. If the DLQ should only accept traffic from specific source queues, set redriveAllowPolicy on it.
Replay on SQS is a first-class API since 2023 rather than a hand-rolled consumer:
# Redrive DLQ messages back to the source queue
aws sqs start-message-move-task \
--source-arn arn:aws:sqs:us-east-1:123456789012:prod-orders-dlq \
--max-number-of-messages-per-second 25
# Check task status
aws sqs list-message-move-tasks \
--source-arn arn:aws:sqs:us-east-1:123456789012:prod-orders-dlq
For monitoring, the CloudWatch metric ApproximateNumberOfMessagesVisible on the DLQ replaces the RabbitMQ depth queries from section 5; alarm on any value above zero for more than a few minutes.
2. DLQ Inspection
2.1 RabbitMQ DLQ Inspection
Start with depth and growth rate, then sample a few messages:
# Check DLQ message count
rabbitmqctl list_queues name messages messages_ready messages_unacknowledged \
| grep dlq
# Inspect DLQ messages via the management API
curl -u admin:"$RABBITMQ_PASS" \
http://rabbitmq-prod:15672/api/queues/%2F/prod.orders.dlq.failed-messages/get \
-H "content-type: application/json" \
--data '{"count": 5, "ackmode": "ack_requeue_true", "encoding": "auto"}'
The ack_requeue_true mode peeks at messages and puts them back, so it’s safe to run on production. Never use ack_requeue_false during inspection or you consume the messages you’re trying to save.
2.2 Kafka DLQ Inspection
# Consume from the DLQ for inspection (no offset commits)
kafka-console-consumer.sh --bootstrap-server kafka:9092 \
--topic prod.orders.order-created.dlq \
--from-beginning \
--max-messages 10 \
--property print.headers=true \
--property print.partition=true \
--property print.offset=true
# Count messages in the DLQ
kafka-run-class.sh kafka.tools.GetOffsetShell \
--broker-list kafka:9092 \
--topic prod.orders.order-created.dlq \
--time -1
2.3 DLQ Message Analysis Script
When the DLQ holds more than a handful of messages, inspect them in aggregate before touching anything. This script buckets failures by error type so you can decide whether you’re looking at one bug or five:
from collections import Counter
from confluent_kafka import Consumer
consumer = Consumer({
'bootstrap.servers': 'kafka:9092',
'group.id': 'dlq-inspector',
'auto.offset.reset': 'earliest',
'enable.auto.commit': False,
})
consumer.subscribe(['prod.orders.order-created.dlq'])
error_categories = Counter()
total_messages = 0
empty_polls = 0
while empty_polls < 3: # stop after 3 consecutive empty polls
msg = consumer.poll(1.0)
if msg is None:
empty_polls += 1
continue
if msg.error():
continue
empty_polls = 0
headers = dict(msg.headers() or [])
error = headers.get('error', b'unknown').decode()
if 'ConnectionError' in error:
category = 'downstream_unavailable'
elif 'JSONDecodeError' in error:
category = 'deserialization_error'
elif 'ValidationError' in error:
category = 'schema_validation_error'
elif 'TimeoutError' in error:
category = 'timeout'
else:
category = 'business_logic_error'
error_categories[category] += 1
total_messages += 1
print(f"Total DLQ messages: {total_messages}")
for category, count in error_categories.most_common():
print(f" {category}: {count} ({count * 100 / total_messages:.1f}%)")
A healthy signal is one dominant category — a single deploy or a single outage explains most DLQ backlogs. A flat spread across categories usually means the DLQ has been accumulating failures for a while and needs per-category triage.
3. Root Cause Analysis
3.1 Common DLQ Causes
| Cause | Frequency | Fix |
|---|---|---|
| Downstream service down | High | Fix downstream, replay DLQ |
| Schema mismatch | Medium | Fix consumer deserialization, replay |
| Invalid message format | Medium | Fix producer, discard or transform |
| Business rule violation | Low | Fix data, replay or discard |
| Timeout | Medium | Raise timeout, optimize handler, replay |
| Deserialization error | Medium | Fix schema, deploy, replay |
| Null pointer / bug | Low | Fix code, deploy, replay |
Two categories deserve care before replaying. A business rule violation is often correct behavior: the message should never have been sent, and replaying it just feeds it back to the DLQ. A schema mismatch can hide partial corruption: verify a sample of messages deserializes cleanly after the fix before replaying the whole backlog.
3.2 Deciding to Replay or Discard
Work through this sequence per error category:
- Is the fix deployed? Replaying before the fix ships just recreates the DLQ. Confirm the new consumer version is live on all replicas.
- Is the message still relevant? A payment event for a cancelled order, or a notification whose window closed, should be discarded.
- Is the payload recoverable? If the bytes are corrupt beyond repair, discard. If a transform can fix them (re-encode, add a missing field), apply it during replay — not by hand-editing the DLQ.
- Is the consumer idempotent? If not, replay can double-charge, double-notify, or double-write. See the message idempotency recipe before replaying into a non-idempotent consumer.
3.3 RCA Template
Incident: <DLQ alert name>
Date: <YYYY-MM-DD HH:MM>
DLQ: <queue or topic name>
Message count: <N>
Error category: <category from analysis>
Root cause:
<Describe what caused the messages to fail>
Affected messages:
- Count: <N>
- Time range: <start> to <end>
- Original topic/queue: <name>
Resolution:
- [ ] Fix applied: <description>
- [ ] Fix deployed: <version>
- [ ] DLQ replayed: <yes/no>
- [ ] DLQ cleared: <yes/no>
- [ ] Monitoring confirmed: <yes/no>
Prevention:
- <What to do to prevent recurrence>
Fill the template even for small incidents. The paper trail is what turns “we replayed some messages” into an auditable recovery, and six months of RCA records is the best data source for deciding which alerts deserve paging.
4. Replay Strategies
Replay is destructive-adjacent work: you’re injecting messages into live traffic. Replay in small batches, watch error rates and consumer lag as you go, and pause if the source failure comes back. For very large backlogs, replay off-peak, since a flood of stale messages competes with live traffic for downstream capacity.
Replay throughput differs per broker and is worth a moment’s thought before you start. On SQS, start-message-move-task handles rate limiting for you (up to 50 messages/second, tunable with --max-number-of-messages-per-second). On RabbitMQ, basic_get is pull-based, so the batch size and the delay between iterations are your only throttle; keep them small on busy queues. On Kafka, replay speed is bounded by producer throughput, and each replayed record lands at the end of the partition: consumers see a burst of old messages after the newest live ones, which can confuse lag-based autoscalers into scaling up for a backlog that drains itself in minutes.
One more ordering note for all three brokers: messages replay from the DLQ in arrival order, not original order. If two messages for the same entity failed at different times, the later failure replays first only if it dead-lettered first, which it usually did, but not always. When strict per-entity ordering matters (account balances, state machines), filter and replay by key instead of draining the whole queue.
4.1 RabbitMQ Replay
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq-prod'))
channel = connection.channel()
def replay_dlq(source_queue, target_exchange, routing_key, batch_size=100):
for _ in range(batch_size):
method, properties, body = channel.basic_get(
queue=source_queue,
auto_ack=False,
)
if method is None:
print("DLQ empty — replay complete")
break
# Strip dead-letter headers so the broker doesn't re-dead-letter
if properties.headers:
for h in ('x-death', 'x-first-death-exchange',
'x-first-death-queue', 'x-first-death-reason'):
properties.headers.pop(h, None)
channel.basic_publish(
exchange=target_exchange,
routing_key=routing_key,
body=body,
properties=properties,
)
channel.basic_ack(delivery_tag=method.delivery_tag)
print(f"Replayed message {method.delivery_tag}")
replay_dlq(
source_queue='prod.orders.dlq.failed-messages',
target_exchange='prod.orders.order-created.direct',
routing_key='order.payment.required',
)
The x-death header is the important detail: RabbitMQ records every dead-lettering there, and if the replayed message fails again it lands back in the DLQ with a death count — useful for spotting messages that keep failing, but also capable of confusing tooling that treats any x-death presence as poison.
4.2 Kafka Replay
from confluent_kafka import Consumer, Producer
consumer = Consumer({
'bootstrap.servers': 'kafka:9092',
'group.id': 'dlq-replayer',
'auto.offset.reset': 'earliest',
'enable.auto.commit': False,
})
producer = Producer({'bootstrap.servers': 'kafka:9092'})
consumer.subscribe(['prod.orders.order-created.dlq'])
DLQ_METADATA = ('retry-count', 'error', 'original-topic',
'original-partition', 'original-offset', 'failed-at')
def replay_dlq(target_topic, max_messages=None):
count = 0
empty_polls = 0
while empty_polls < 3:
msg = consumer.poll(1.0)
if msg is None:
empty_polls += 1
continue
if msg.error():
continue
empty_polls = 0
# Strip DLQ metadata headers; keep the original business headers
clean_headers = [
(k, v) for k, v in (msg.headers() or [])
if k not in DLQ_METADATA
]
producer.produce(
topic=target_topic,
key=msg.key(),
value=msg.value(),
headers=clean_headers,
)
consumer.commit(msg)
count += 1
if max_messages and count >= max_messages:
break
producer.flush()
print(f"Replayed {count} messages to {target_topic}")
replay_dlq(target_topic='prod.orders.order-created.v1', max_messages=500)
Kafka replay preserves key and value exactly, so the consumer sees the same record, including the same partition assignment by key, it failed on before. Order across partitions isn’t preserved; if ordering matters for the affected keys, replay one key range at a time.
4.3 Post-Replay Verification
Don’t declare success at “replay script finished.” Verify each of these before closing the incident:
- DLQ depth drops to zero (or to the count you deliberately left behind for unrecoverable messages).
- No new entries appear in the DLQ within one full processing window; a refilling DLQ means the fix didn’t work.
- Downstream state is consistent: spot-check a sample of replayed messages end-to-end (payment captured, email sent, row updated).
- Consumer lag returns to normal on the source topic.
5. Monitoring and Alerts
DLQ ownership has to be explicit or the queue rots. Assign each DLQ to the team that owns the consuming service, route the alerts to that team’s channel, and give the on-call a documented escalation path: warning-level DLQ alerts get triaged within one business day, growth-rate alerts page immediately. If a DLQ alert pages and nobody knows who owns the queue, that’s a process bug worth its own postmortem.
5.1 Alert Rules
# Prometheus alert rules for DLQs
groups:
- name: dlq-alerts
rules:
- alert: RabbitMQDLQMessages
expr: rabbitmq_queue_messages_ready{queue=~".*dlq.*"} > 0
for: 5m
labels:
severity: warning
annotations:
summary: "DLQ has messages: {{ $labels.queue }}"
description: "DLQ {{ $labels.queue }} has {{ $value }} messages"
- alert: KafkaDLQMessages
expr: kafka_topic_partition_current_offset{topic=~".*dlq"} > 0
for: 5m
labels:
severity: warning
annotations:
summary: "Kafka DLQ has messages: {{ $labels.topic }}"
- alert: DLQRateIncreasing
expr: deriv(rabbitmq_queue_messages_ready{queue=~".*dlq.*"}[10m]) > 1
for: 10m
labels:
severity: critical
annotations:
summary: "DLQ message rate is increasing: {{ $labels.queue }}"
The first two alerts warn when anything lands; the derivative-based third alert catches the dangerous case, a DLQ actively filling, which means an ongoing failure, not leftover debris.
5.2 Dashboard Queries
# DLQ depth per queue
rabbitmq_queue_messages_ready{queue=~".*dlq.*"}
# Rate of change in DLQ depth (growth means an active failure)
deriv(rabbitmq_queue_messages_ready{queue=~".*dlq.*"}[10m])
# DLQ messages per minute
rate(rabbitmq_queue_messages_ready{queue=~".*dlq.*"}[5m]) * 60
For message age, use the broker’s oldest-message metric where available (rabbitmq_queue_head_message_timestamp from the Prometheus plugin) rather than deriving it from queue depth: depth tells you volume, not staleness.
See Also
- Dead Letter Queues — DLQ configuration recipe across RabbitMQ, Kafka, and SQS
- Dead Letter Channel Pattern — the architectural pattern behind DLQs
- Message Queues — RabbitMQ, Kafka, and SQS detailed analysis
- Configure Dead-Letter Queues in RabbitMQ for Failed Messages
- Message Processing Idempotency — required reading before replaying into non-idempotent consumers
Frequently Asked Questions
How long should I retain messages in the DLQ?
Seven days is a reasonable default for production: long enough to investigate, fix, and replay across a normal on-call rotation. Extend to 30 days for topics under compliance requirements. Set x-message-ttl on RabbitMQ DLQs and retention.ms on Kafka DLQ topics, and alert on messages older than 24 hours; stale messages are the hardest to replay because the context around them has moved on.
When should I discard DLQ messages instead of replaying?
Discard when the payload is unrecoverable (corrupt bytes, fields that can't be reconstructed) or when the business event is no longer relevant: a payment event for a cancelled order, a notification past its delivery window. Document every discard in the RCA. Never discard just because the message is inconvenient; check whether a producer fix could regenerate the correct payload first.
How do I prevent infinite retry loops?
Cap retries in message headers (three is typical) and route to the DLQ once the cap is hit instead of requeueing. In RabbitMQ that means basic_reject(requeue=False); in Kafka, check the retry-count header and produce to the DLQ topic when it exceeds the cap. Also commit the offset after copying the record; re-raising the exception after the DLQ write processes the same poison record forever.
Should I use a separate DLQ per consumer or per topic?
Per consumer service in RabbitMQ, per source topic in Kafka. RabbitMQ consumers often share queues, so a service-scoped DLQ keeps each team's failures visible and prevents one noisy service from hiding another team's messages. Kafka consumers are typically per-topic, so a DLQ topic per source topic (prod.orders.order-created.dlq) is the cleaner split.
How do I automate DLQ replay?
Build a replay job that reads the DLQ, verifies the fix is live (health check or version check), and reproduces messages to the source, with a dry-run mode that reports what it would replay without writing anything. Rate-limit the replay so a stale backlog doesn't overwhelm downstream services, log each replayed message's original metadata for audit, and run it as a triggered job (Kubernetes Job, Lambda) after a fix deploys rather than on a schedule; scheduled replay hides failures you should be seeing.
Related Resources
Kafka Topic Naming Convention Template
Template for standardizing Kafka topic names across teams: naming pattern, environment prefixes, event suffixes, partition and retention rules.
DocRabbitMQ Queue Design Template
Template for documenting RabbitMQ queue, exchange, and binding design: exchange types, queue properties, binding rules, dead letter handling, TTL policies, and capacity planning with code examples.
DocMessage Schema Evolution Policy (Avro, Protobuf, JSON)
A reusable policy for evolving message schemas safely in event-driven systems: compatibility rules, schema registry requirements, versioning, breaking change procedure, migration checklist, and CI enforcement with Avro, Protobuf, and JSON Schema examples.
RecipeDead Letter Queues: Setup for SQS, RabbitMQ & Kafka
Configure dead letter queues on SQS, RabbitMQ, and Kafka: redrive policies, dead-letter exchanges, retry limits, poison-message detection, and safe replay.
PatternDead Letter Channel Pattern
Route unprocessable messages to a separate dead letter queue for inspection and replay. Prevent poison messages from blocking the main queue indefinitely.