Dead Letter Queue
Move messages that repeatedly fail processing to a separate queue, so they stop blocking healthy traffic and can be inspected and replayed.
On this page
Problem
Some messages can never be processed as sent: malformed JSON, a schema version the consumer does not understand, a reference to a record that was deleted, or a payload that triggers a bug. With at-least-once delivery, the broker redelivers such a poison message after every failure, forever.
Each redelivery burns consumer capacity and fills logs with the same stack trace. On queues that preserve order, the poison message blocks every message behind it. Dropping failed messages instead loses data silently, which is often worse than the backlog.
Context
Use this pattern when:
- Consumers process messages with at-least-once delivery and retry on failure.
- Some failures are permanent (bad data, bugs) rather than transient (a dependency briefly down).
- Messages carry business value, so they must not be discarded without a trace.
- Operators need a way to inspect failures and reprocess them after a fix.
Solution
Configure a maximum number of delivery attempts on the main queue. When a message exceeds it, or when the consumer explicitly rejects it as unprocessable, the broker (or the consumer) moves it to a dedicated dead letter queue together with metadata: original queue, failure reason, attempt count and timestamps.
The main queue keeps flowing, and the DLQ becomes a work list for people. Alert on DLQ depth and age, investigate the cause, fix the consumer or the data, and then redrive the messages back to the main queue. Messages that are truly invalid are archived or discarded deliberately.
Separate transient from permanent failures. Transient errors deserve retries with backoff before giving up; a validation error deserves an immediate dead-letter, since retrying it only wastes attempts.
How it works, step by step
- 1Consumer receives a message and attempts to process it.
- 2Permanent failure (invalid payload): dead-letter immediately with a reason.
- 3Transient failure: abandon or nack so the broker redelivers, ideally with a delay.
- 4When the delivery count exceeds the limit, the broker moves the message to the DLQ.
- 5Alert on DLQ depth, investigate, fix, and redrive messages to the main queue.
Implementation
Most brokers support dead-lettering natively: Amazon SQS through a redrive policy, Azure Service Bus through a built-in dead letter sub-queue, RabbitMQ through a dead-letter exchange. The examples show explicit dead-lettering for permanent failures plus the broker's automatic limit.
using System.Text.Json;
using Azure.Messaging.ServiceBus;
public sealed record PaymentRequested(Guid PaymentId, decimal Amount, string Currency);
public sealed class PaymentHandler(IPaymentGateway gateway)
{
// Registered as processor.ProcessMessageAsync with AutoCompleteMessages = false.
public async Task HandleAsync(ProcessMessageEventArgs args)
{
PaymentRequested? request;
try
{
request = args.Message.Body.ToObjectFromJson<PaymentRequested>();
}
catch (JsonException ex)
{
// Permanent: retrying a malformed message can never succeed.
await args.DeadLetterMessageAsync(args.Message,
deadLetterReason: "InvalidPayload",
deadLetterErrorDescription: ex.Message);
return;
}
if (request is null || request.Amount <= 0)
{
await args.DeadLetterMessageAsync(args.Message,
deadLetterReason: "ValidationFailed",
deadLetterErrorDescription: "Amount must be positive");
return;
}
try
{
await gateway.ChargeAsync(request, args.CancellationToken);
await args.CompleteMessageAsync(args.Message);
}
catch (HttpRequestException)
{
// Transient: abandon so Service Bus redelivers. After the queue's
// MaxDeliveryCount (default 10) it dead-letters automatically.
await args.AbandonMessageAsync(args.Message);
}
}
}
public interface IPaymentGateway
{
Task ChargeAsync(PaymentRequested request, CancellationToken ct);
}Dead-lettered messages are read from the <queue>/$deadletterqueue sub-queue, for example with client.CreateReceiver("payments", new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }).
import {
DeleteMessageCommand,
ReceiveMessageCommand,
SetQueueAttributesCommand,
SQSClient,
} from '@aws-sdk/client-sqs';
const sqs = new SQSClient({});
/** After 5 failed receives, SQS moves the message to the DLQ itself. */
export async function configureRedrive(queueUrl: string, dlqArn: string) {
await sqs.send(new SetQueueAttributesCommand({
QueueUrl: queueUrl,
Attributes: {
RedrivePolicy: JSON.stringify({ deadLetterTargetArn: dlqArn, maxReceiveCount: '5' }),
},
}));
}
export async function consume(queueUrl: string, handle: (body: unknown) => Promise<void>) {
for (;;) {
const { Messages = [] } = await sqs.send(new ReceiveMessageCommand({
QueueUrl: queueUrl,
MaxNumberOfMessages: 10,
WaitTimeSeconds: 20, // long polling
VisibilityTimeout: 60, // time to process before redelivery
}));
for (const message of Messages) {
try {
await handle(JSON.parse(message.Body ?? 'null'));
await sqs.send(new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: message.ReceiptHandle }));
} catch (error) {
// Do not delete: the message becomes visible again after the timeout,
// and its receive count grows until the redrive policy dead-letters it.
console.error('processing failed', { id: message.MessageId, error });
}
}
}
}SQS can move messages back from the DLQ to the source queue with a redrive task (StartMessageMoveTask) once the cause is fixed.
In production
- Alert on DLQ depth greater than zero for critical flows; a DLQ that nobody watches is a slower way of dropping messages.
- Store the reason, the stack trace or error code and the original queue with each dead-lettered message.
- Set a retention period on the DLQ long enough to cover investigation (days, not hours).
- Build or adopt tooling for redrive, and make sure consumers are idempotent before replaying.
- Choose the attempt limit so transient outages do not dead-letter healthy messages; combine with delayed retries.
Trade-offs
Benefits
- Poison messages stop consuming capacity and blocking the main queue.
- Failed messages are preserved with context instead of being lost.
- Gives operators a clear signal (DLQ depth) and a recovery path (redrive).
Costs
- Needs monitoring, ownership and tooling; otherwise messages pile up unnoticed.
- Redriving reorders messages relative to ones processed in the meantime.
- A too-low attempt limit dead-letters healthy messages during short outages, creating manual work.
- Messages in the DLQ represent delayed business outcomes that may need compensation.
Alternatives
- Retry queues with delays
- Route failures through one or more delay queues (for example 1 min, 10 min, 1 h) before the final DLQ, giving transient issues time to clear.
- Skip and log
- Acknowledge and discard failing messages with a log entry; acceptable only for low-value data such as metrics samples.
- Store failures in a database table
- A consumer writes failures to a table with full context for a support tool; useful when the broker has no DLQ support.
Anti-patterns
- Unmonitored DLQ
- Without alerts and an owner, the DLQ silently accumulates lost orders or payments for weeks.
- Infinite requeue
- Returning a poison message to the queue forever wastes capacity and, on ordered queues, blocks all later messages.
- Redrive before fixing
- Replaying messages without fixing the cause sends them straight back to the DLQ and clutters the investigation.
- Dead-lettering transient failures immediately
- A dependency blip turns into a flood of manual redrives that retries with backoff would have handled.
Related lessons
Interview questions
What is a poison message?
A message that fails processing every time it is delivered, for example because it is malformed or triggers a bug. With at-least-once delivery it would be redelivered forever, wasting capacity and possibly blocking other messages.
How do you choose the maximum delivery count?
High enough that transient failures, given the retry delays, have time to resolve, and low enough that a poison message does not consume much capacity. Five to ten attempts with growing delays is common, and permanent failures should bypass the count by being dead-lettered immediately.
What should happen after a message lands in the DLQ?
An alert should fire, someone should investigate the recorded reason, fix the code or data, and redrive the message to the main queue, relying on idempotent consumers. Messages that are invalid by design are archived with a note.
Why can redriving messages cause problems?
Redriven messages arrive later than newer messages that were already processed, so consumers that assume ordering may apply stale updates. Version checks or timestamps on the target record prevent an old event from overwriting newer state.