Skip to content

RabbitMQ dead-letter exchange setup: route rejected, expired, and over-length messages

Set up a RabbitMQ dead-letter exchange so rejected, expired, or over-length messages land in a dead-letter queue instead of vanishing, plus a TTL-based retry-with-delay loop.

A RabbitMQ dead-letter exchange (DLX) is a normal exchange you nominate on a queue so that any message RabbitMQ dead-letters from that queue gets re-published to the DLX instead of disappearing. You wire it with two queue arguments — x-dead-letter-exchange and, optionally, x-dead-letter-routing-key — either at declare time or through a policy. Once the DLX has a queue bound to it, rejected, expired, and over-length messages land somewhere you can inspect them, and you can add a second queue with a message TTL to build a retry-with-delay loop that feeds messages back to the original work queue after a wait.

What you’ll accomplish

  • Declare a dead-letter exchange and a dead-letter queue (DLQ) that captures messages the main queue drops.
  • Configure the main queue with x-dead-letter-exchange / x-dead-letter-routing-key so all three dead-letter triggers route there.
  • Read the x-death header to see why a message was dead-lettered and how many times.
  • Build a TTL-based wait queue that re-delivers messages to the work queue after a fixed delay, giving you retries without a busy loop.
  • Apply the same wiring to existing queues with a policy, since queue arguments are immutable after declare.

Prerequisites

  • RabbitMQ 3.12+ or 4.x running, with the management plugin enabled (rabbitmq-plugins enable rabbitmq_management).
  • rabbitmqadmin (downloadable from the management UI at http://<host>:15672/cli/rabbitmqadmin) or the Management UI itself, plus rabbitmqctl on the broker host for policies and queue listings.
  • A client that can publish and consume. The examples use rabbitmqadmin for declaration and one Python pika snippet for the nack, but any AMQP 0-9-1 client works.
  • Decide up front whether the main queue is a classic queue or a quorum queue. DLX routing works on both, but the retry-counting behaviour differs: classic queues rely on the x-death count and x-message-ttl, while quorum queues also expose a native x-delivery-limit that dead-letters a message once it has been redelivered too many times. This guide uses classic queues for the TTL retry loop because per-message and per-queue TTL are the most portable mechanism; the notes call out where quorum queues behave differently.

How it works

When RabbitMQ dead-letters a message, it re-publishes that message to the exchange named in the source queue’s x-dead-letter-exchange argument, using either the original routing key or the x-dead-letter-routing-key override. Three events trigger dead-lettering:

  1. A consumer sends basic.reject or basic.nack with requeue=false.
  2. The message’s TTL expires — set per-queue with x-message-ttl or per-message with the expiration property.
  3. The queue hits a length limit set with x-max-length (message count) or x-max-length-bytes, and the oldest messages are pushed out.

On each dead-letter hop, RabbitMQ appends an entry to the message’s x-death header: an array recording the count, reason (rejected, expired, maxlen, or delivery_limit), source queue, exchange, routing-keys, and a timestamp. That header is how you tell a genuine rejection from a TTL expiry, and how a retry loop knows how many times a message has already been through.

RabbitMQ dead-letter and retry flow: producer to main queue, dead-letter exchange, TTL wait queue looping back, and a terminal DLQ

The retry-with-delay pattern chains two dead-letter hops. The work queue dead-letters a failed message to a DLX, which routes it to a wait queue. The wait queue has no consumer; it only has an x-message-ttl and its own x-dead-letter-exchange pointing back at the work exchange. When the TTL expires, RabbitMQ dead-letters the message again — this time back into the work queue — so the consumer sees it again after the delay. A separate binding sends genuinely dead messages to a terminal DLQ for human inspection.

Step-by-step

1. Declare the dead-letter exchange and terminal DLQ. Use a durable direct exchange and bind a durable queue to it on a dead routing key:

rabbitmqadmin declare exchange name=dlx type=direct durable=true
rabbitmqadmin declare queue name=dlq.orders durable=true
rabbitmqadmin declare binding source=dlx destination=dlq.orders routing_key=dead

Each command prints exchange declared, queue declared, and binding declared. If nothing is bound to the DLX, dead-lettered messages are dropped silently — the DLX is a real exchange and obeys normal routing rules.

2. Declare the main work queue with dead-letter arguments. Point it at the DLX and set the dead-letter routing key so failures go to the terminal DLQ (you will change this to the retry path in step 6):

rabbitmqadmin declare queue name=work.orders durable=true \
  arguments='{"x-dead-letter-exchange":"dlx","x-dead-letter-routing-key":"dead"}'

Output is queue declared. Confirm the arguments took with rabbitmqadmin list queues name arguments, which should show the two x-dead-letter-* keys on work.orders.

3. Publish a test message and reject it. Publish through the default exchange straight to the queue:

rabbitmqadmin publish routing_key=work.orders payload='{"order":1}'

This prints Message published. Now consume it and nack with requeue=false using pika:

import pika

conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()

method, props, body = ch.basic_get(queue="work.orders", auto_ack=False)
if method:
    print("got:", body)
    # requeue=False is what sends the message to the dead-letter exchange
    ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
conn.close()

The script prints got: b'{"order":1}'. The requeue=False is the whole point — requeue=True would put the message back on work.orders and never dead-letter it.

4. Confirm the message landed in the DLQ. Read it back without acking:

rabbitmqadmin get queue=dlq.orders ackmode=reject_requeue_true count=1

You should see one row whose payload is {"order":1}. In the Management UI the same message appears under Queues, dlq.orders, “Get messages”.

5. Inspect the x-death header. In the rabbitmqadmin get output, expand the message properties / headers, or use the Management UI’s Get messages view with “Payload” and headers shown. You will see an x-death array with reason: rejected, queue: work.orders, count: 1, and the routing keys. That header confirms the trigger and the hop count — a retry loop reads count to decide when to give up.

6. Build the delayed-retry wait queue. Declare a wait.orders queue with a TTL and its own DLX back to the work exchange. Here the work exchange is the default exchange (""), whose routing key is the destination queue name, so the wait queue’s dead-letter routing key is work.orders:

rabbitmqadmin declare queue name=wait.orders durable=true \
  arguments='{"x-message-ttl":30000,"x-dead-letter-exchange":"","x-dead-letter-routing-key":"work.orders"}'
rabbitmqadmin declare binding source=dlx destination=wait.orders routing_key=retry

Both print their declared line. Messages that reach wait.orders sit for 30 seconds, then RabbitMQ dead-letters them back to work.orders. To send failures into the retry loop instead of the terminal DLQ, redeclare the work queue’s x-dead-letter-routing-key as retry (see the next note about immutability), and keep the dead binding for messages you route to the DLQ deliberately once x-death count is too high.

7. Prefer a policy for existing queues. Queue arguments are fixed at declare time — you cannot change x-dead-letter-exchange on a live queue by re-declaring it with different arguments; RabbitMQ returns a PRECONDITION_FAILED channel error. For queues that already hold data, set the dead-letter behaviour with a policy instead:

rabbitmqctl set_policy dlx-orders "^work\.orders$" \
  '{"dead-letter-exchange":"dlx","dead-letter-routing-key":"retry"}' \
  --apply-to queues

This prints Setting policy "dlx-orders" .... Confirm with rabbitmqctl list_policies. A policy can be changed or cleared at any time and applies to every queue whose name matches the pattern, which is why it is the right tool for anything already in production.

Validate it works

Dead-letter path. Publish to work.orders, nack with requeue=false (steps 3 and 4), and confirm the message appears in your dead-letter destination with an x-death entry whose count is 1 and reason is rejected.

TTL retry path. With the retry wiring from step 6, dead-letter a message so it routes to wait.orders. Watch it disappear from wait.orders and reappear in work.orders after roughly 30 seconds:

rabbitmqctl list_queues name messages

Run this before and during the wait: the message count sits on wait.orders for the TTL window, then moves back to work.orders. Each pass through the loop adds another x-death entry, so a consumer can read x-death[0].count and stop retrying past a threshold.

Length-limit path. Declare a scratch queue with x-max-length of 2 and the same DLX, publish three messages, and confirm the oldest is dead-lettered with reason: maxlen.

Troubleshooting

DLX declared but messages vanish. The most common cause is that nothing is bound to the DLX on the dead-letter routing key, or the routing key does not match any binding. RabbitMQ dead-letters the message to the DLX, the DLX finds no matching queue, and the message is discarded — exactly like any unroutable publish to a direct exchange. Check rabbitmqctl list_bindings | grep dlx and confirm the routing key on the binding matches x-dead-letter-routing-key. If you set no routing-key override, the message keeps its original routing key, which often matches nothing on the DLX.

Can’t change arguments on an existing queue. Re-declaring work.orders with new x-dead-letter-* arguments fails with PRECONDITION_FAILED - inequivalent arg. You must either delete and redeclare the queue (losing its messages) or, better, leave the queue alone and set the behaviour with rabbitmqctl set_policy as in step 7. Policies override the corresponding queue-argument defaults without touching the queue definition.

Infinite requeue loop. If a consumer nacks with requeue=true (or rejects with requeue), the message goes straight back to the same queue and is redelivered immediately — it never reaches the DLX, and a deterministic failure spins forever. Dead-lettering only happens on requeue=false. For retries with a delay, you want requeue=false plus the TTL wait queue, never requeue=true.

x-death count not incrementing as expected. RabbitMQ groups x-death entries by the pair of source queue and reason. Two expiries from the same wait queue increment one entry’s count; a rejection and an expiry produce separate entries. If your retry cap reads the wrong entry, you may loop longer than intended. Read the entry whose queue matches your work queue and whose reason is expired for a TTL-retry counter, and remember the array order is most-recent-first.

Quorum vs classic differences. On quorum queues, prefer the native x-delivery-limit argument (or the delivery-limit policy key) to cap redeliveries; once exceeded, the message is dead-lettered with reason: delivery_limit. Classic-queue length limits and per-message TTL behave as described here, but quorum queues historically had partial support for per-message TTL and length limits across versions — on quorum queues, drive retries with x-delivery-limit and keep the TTL wait queue as a classic queue.

When this is the wrong approach

  • You need durable exactly-once delivery. DLX plus TTL retry is at-least-once with visible duplicates on every replay. If duplicates are unacceptable, you need a broker or pattern with real delivery guarantees plus idempotent consumers keyed on a message ID, not a retry loop.
  • You are really building a log or stream. If consumers need to replay history, fan out to many independent readers, or keep an ordered, retained record, a log-structured system fits better than queue-and-retry. See install Kafka on Ubuntu for that path.
  • The failures are true poison messages needing review. Messages that will never succeed — malformed payloads, references to deleted data — should go to a terminal DLQ for a human to triage, not loop through a wait queue burning delivery attempts. Route on the x-death count: retry a few times, then send to quarantine. The broader design is covered in the dead-letter queues pattern, and the official reference is the RabbitMQ DLX documentation.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.