Programming Search⌘K

Patterncore

Dead Letter Channel

Also called Dead Letter Channel pattern, dead letter queue, dead-letter queue, DLQ, dead message queue, dead-letter topic.

A dead letter channel holds the messages that the messaging system cannot or should not deliver, so that one bad message does not block the others and a person can look at it later.

Family
integration
Intent
Move a message that cannot be delivered or processed to a separate channel, with the reason, so that the other messages go on and the failed message is kept for a later decision.
Also called
dead letter queue, DLQ, dead message queue, dead-letter topic

Intent

Give the messaging system a place for the messages that it cannot deliver. The book asks: "What will the messaging system do with a message it cannot deliver?"12 A Dead Letter Channel keeps such a message out of the way of the others, with the reason that it failed, until a person or a program decides what to do with it.

Problem

A payment program reads a queue of payments. One message has an amount that the program cannot read. The program throws an exception, does not acknowledge the message, and the broker gives the message to it again. The message fails again, and again.

The forces are these. The broker must not lose a message only because a receiver failed once, because the failure can be temporary: a database that is down for a minute, or a network error. But a message that always fails must not stay in the queue for ever. It uses the work of the receivers, it can delay the messages after it, and it hides the error from the people who can fix it. And the broker cannot know if a failure is temporary or permanent: only a count of the attempts, or a time limit, can tell it to stop.

Solution

"When a messaging system determines that it cannot or should not deliver a message, it may elect to move the message to a Dead Letter Channel".1 The messaging system also records information with the message, such as the channel where the message was to go.1

  sender --> [ payments ] --> receiver
                  |   ^         | fails, no ack
                  |   +---------+ deliver again (count + 1)
                  |
                  +-- count = limit --> [ payments.dead ] --> operator, alert, redrive
                                         reason, source, count

The participants are the sender, the source channel, the receiver, the dead letter channel and the program or person that reads the dead letters. The messaging system usually decides when a message is dead. These are the usual rules:

  • Too many deliveries. In Amazon SQS, "The maxReceiveCount is the number of times a consumer can receive a message from a source queue before it is moved to a dead-letter queue."3 Azure Service Bus counts the deliveries under a peek lock, and when the count is more than the limit, which is 10 by default, it moves the message and sets the reason MaxDeliveryCountExceeded.4 In Google Cloud Pub/Sub, the maximum number of delivery attempts is 5 by default, and it can be from 5 to 100.5
  • A rejection. RabbitMQ dead-letters a message when a consumer rejects it and does not ask to requeue it. It also dead-letters a message that expires because of a per-message TTL, a message that is dropped because the queue is over its length limit, and a message that is returned to a quorum queue more times than the delivery limit.6
  • Expiry. When dead-lettering is on in Service Bus, "all expiring messages are moved to the DLQ", with the reason TTLExpiredException.4
  • A decision of the receiver. In Service Bus, "applications can use the DLQ to explicitly reject unacceptable messages."4 The book gives a separate pattern for this case, the Invalid Message Channel: "The receiver should move the improper message to an Invalid Message Channel", which is "a special channel for messages that could not be processed by their receivers".7

The program below follows a message through a dead letter channel and back. The receiver cannot read the amount 12,50. After 3 deliveries, the queue moves the message to orders.dead with the reason and the source. An operator reads the reason, the handler is fixed, and the dead letter is moved back to its source queue. Amazon SQS calls this last step a dead-letter queue redrive.3

from collections import deque

MAX_DELIVERIES = 3


class Queue:
    def __init__(self, name, dead_letter=None):
        self.name = name
        self.items = deque()
        self.dead_letter = dead_letter

    def send(self, body):
        self.items.append({"body": body, "deliveries": 0, "headers": {}})


def consume(queue, handler):
    while queue.items:
        msg = queue.items.popleft()
        msg["deliveries"] += 1
        try:
            handler(msg["body"])
        except ValueError as e:
            print(f"failed {msg['body']['id']}, delivery {msg['deliveries']}")
            if msg["deliveries"] < MAX_DELIVERIES:
                queue.items.append(msg)
            else:
                msg["headers"] = {"reason": str(e), "source": queue.name}
                queue.dead_letter.items.append(msg)


def handle_v1(order):
    total = float(order["total"])
    print(f"handled {order['id']} total {total:.2f}")


def handle_v2(order):
    total = float(order["total"].replace(",", "."))
    print(f"handled {order['id']} total {total:.2f}")


dead = Queue("orders.dead")
orders = Queue("orders", dead_letter=dead)
orders.send({"id": "order-1", "total": "10.00"})
orders.send({"id": "order-2", "total": "12,50"})
orders.send({"id": "order-3", "total": "7.25"})
consume(orders, handle_v1)

# An operator reads the dead letters and finds the cause.
for msg in dead.items:
    h = msg["headers"]
    print(f"dead letter {msg['body']['id']} from {h['source']} "
          f"after {msg['deliveries']} deliveries: {h['reason']}")

# The handler is fixed. Redrive: move the dead letters back to their source.
moved = 0
while dead.items:
    msg = dead.items.popleft()
    orders.send(msg["body"])
    moved += 1
print(f"redrive {moved} message to orders")
consume(orders, handle_v2)
print(f"dead letters left: {len(dead.items)}")
Output
handled order-1 total 10.00
failed order-2, delivery 1
handled order-3 total 7.25
failed order-2, delivery 2
failed order-2, delivery 3
dead letter order-2 from orders after 3 deliveries: could not convert string to float: '12,50'
redrive 1 message to orders
handled order-2 total 12.50
dead letters left: 0

Dead letters must be read. A dead letter channel only moves a failure to another place. In Service Bus, "There's no automatic cleanup of the DLQ."4 A message there stays until a program receives it and completes it.4 A team that sends dead letters to a queue that nobody reads loses the messages as surely as a broker that drops them, only more slowly. Give each dead letter channel an owner, an alert on its length, and a way to redrive or delete its messages.

Example

Each example file runs a queue in memory with a limit of 3 deliveries. The handler fails for the message pay-2, because its amount is x. The queue puts the message back at the end after each failure, and after the third failure it moves the message to a list of dead letters with the reason and the source. The other two messages are processed, and they do not wait for the bad one.

The examples use the standard library only, in place of a broker. With a broker, the delivery count, the limit and the move are usually the work of the broker, and the receiver only fails or rejects the message.364

PythonGitHub
from collections import deque

MAX_DELIVERIES = 3


def handle(body):
    name, amount = body.split()
    if not amount.isdigit():
        raise ValueError(f"bad amount {amount}")
    print(f"ok {name} amount {amount}")


queue = deque({"body": b, "deliveries": 0} for b in ["pay-1 10", "pay-2 x", "pay-3 5"])
dead_letters = []
processed = 0
while queue:
    msg = queue.popleft()
    msg["deliveries"] += 1
    try:
        handle(msg["body"])
        processed += 1
    except ValueError as e:
        print(f"fail {msg['body'].split()[0]} delivery {msg['deliveries']}: {e}")
        if msg["deliveries"] < MAX_DELIVERIES:
            queue.append(msg)
        else:
            msg["reason"] = str(e)
            msg["source"] = "payments"
            dead_letters.append(msg)

for msg in dead_letters:
    print(f"dead letter {msg['body'].split()[0]}: deliveries={msg['deliveries']} "
          f"reason={msg['reason']} source={msg['source']}")
print(f"processed {processed}, dead letters {len(dead_letters)}")
Output
ok pay-1 amount 10
fail pay-2 delivery 1: bad amount x
ok pay-3 amount 5
fail pay-2 delivery 2: bad amount x
fail pay-2 delivery 3: bad amount x
dead letter pay-2: deliveries=3 reason=bad amount x source=payments
processed 2, dead letters 1
  • Verdict: idiom. Python has no dead letter channel. A collections.deque is the queue, a count in each message is the delivery count, and a list is the dead letter channel.
  • A message that fails goes back to the end of the queue, so pay-3 is processed before the second delivery of pay-2. A broker that puts the message back at the head would make the next messages wait.
  • With a broker, the receiver does not count. A Pika consumer calls basic_nack with requeue=False, and RabbitMQ moves the message to the dead-letter exchange of the queue.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Main {
    static final int MAX_DELIVERIES = 3;

    static final class Message {
        final String body;
        int deliveries;
        String reason;
        String source;

        Message(String body) {
            this.body = body;
        }

        String name() {
            return body.split(" ")[0];
        }
    }

    static void handle(String body) {
        String amount = body.split(" ")[1];
        if (!amount.chars().allMatch(Character::isDigit)) {
            throw new IllegalArgumentException("bad amount " + amount);
        }
        System.out.println("ok " + body.split(" ")[0] + " amount " + amount);
    }

    public static void main(String[] args) {
        Deque<Message> queue = new ArrayDeque<>();
        for (String b : List.of("pay-1 10", "pay-2 x", "pay-3 5")) {
            queue.add(new Message(b));
        }
        List<Message> deadLetters = new ArrayList<>();
        int processed = 0;
        while (!queue.isEmpty()) {
            Message msg = queue.poll();
            msg.deliveries++;
            try {
                handle(msg.body);
                processed++;
            } catch (IllegalArgumentException e) {
                System.out.println("fail " + msg.name() + " delivery " + msg.deliveries + ": " + e.getMessage());
                if (msg.deliveries < MAX_DELIVERIES) {
                    queue.add(msg);
                } else {
                    msg.reason = e.getMessage();
                    msg.source = "payments";
                    deadLetters.add(msg);
                }
            }
        }
        for (Message msg : deadLetters) {
            System.out.println("dead letter " + msg.name() + ": deliveries=" + msg.deliveries
                    + " reason=" + msg.reason + " source=" + msg.source);
        }
        System.out.println("processed " + processed + ", dead letters " + deadLetters.size());
    }
}
Output
ok pay-1 amount 10
fail pay-2 delivery 1: bad amount x
ok pay-3 amount 5
fail pay-2 delivery 2: bad amount x
fail pay-2 delivery 3: bad amount x
dead letter pay-2: deliveries=3 reason=bad amount x source=payments
processed 2, dead letters 1
  • Verdict: idiom. Java has no dead letter channel. An ArrayDeque is the queue, a field of the message is the delivery count, and an ArrayList is the dead letter channel.
  • The handler throws IllegalArgumentException for a bad message. A handler that catches all exceptions would also move messages that failed because of a temporary error, such as a lost database connection, after the same 3 deliveries.
  • In Jakarta Messaging, the provider must set the property JMSXDeliveryCount to the number of delivery attempts. A receiver can use it to find a message that the broker gives again and again, and move that message itself.
const int MaxDeliveries = 3;

var queue = new Queue<Message>();
foreach (var b in new[] { "pay-1 10", "pay-2 x", "pay-3 5" })
{
    queue.Enqueue(new Message(b));
}
var deadLetters = new List<Message>();
int processed = 0;
while (queue.TryDequeue(out var msg))
{
    msg.Deliveries++;
    try
    {
        Handle(msg.Body);
        processed++;
    }
    catch (FormatException e)
    {
        Console.WriteLine($"fail {msg.Name} delivery {msg.Deliveries}: {e.Message}");
        if (msg.Deliveries < MaxDeliveries)
        {
            queue.Enqueue(msg);
        }
        else
        {
            msg.Reason = e.Message;
            msg.Source = "payments";
            deadLetters.Add(msg);
        }
    }
}
foreach (var msg in deadLetters)
{
    Console.WriteLine($"dead letter {msg.Name}: deliveries={msg.Deliveries} reason={msg.Reason} source={msg.Source}");
}
Console.WriteLine($"processed {processed}, dead letters {deadLetters.Count}");

static void Handle(string body)
{
    var parts = body.Split(' ');
    if (!int.TryParse(parts[1], out _))
    {
        throw new FormatException("bad amount " + parts[1]);
    }
    Console.WriteLine($"ok {parts[0]} amount {parts[1]}");
}

sealed class Message(string body)
{
    public string Body { get; } = body;
    public string Name => Body.Split(' ')[0];
    public int Deliveries { get; set; }
    public string? Reason { get; set; }
    public string? Source { get; set; }
}
Output
ok pay-1 amount 10
fail pay-2 delivery 1: bad amount x
ok pay-3 amount 5
fail pay-2 delivery 2: bad amount x
fail pay-2 delivery 3: bad amount x
dead letter pay-2: deliveries=3 reason=bad amount x source=payments
processed 2, dead letters 1
  • Verdict: idiom. .NET has no dead letter channel. A Queue<T> is the queue, a property of the message is the delivery count, and a List<T> is the dead letter channel.
  • Handle throws FormatException, and only that exception counts as a failure of the message. Other exceptions stop the program.
  • With Azure Service Bus, ServiceBusReceiver.DeadLetterMessageAsync moves a message to the dead-letter subqueue with a reason and a description, and the service moves a message there itself when the delivery count is more than MaxDeliveryCount.
package main

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
)

const maxDeliveries = 3

type message struct {
	body       string
	deliveries int
	reason     string
	source     string
}

func handle(body string) error {
	f := strings.Fields(body)
	if _, err := strconv.Atoi(f[1]); err != nil {
		return errors.New("bad amount " + f[1])
	}
	fmt.Printf("ok %s amount %s\n", f[0], f[1])
	return nil
}

func main() {
	var queue []*message
	for _, b := range []string{"pay-1 10", "pay-2 x", "pay-3 5"} {
		queue = append(queue, &message{body: b})
	}
	var deadLetters []*message
	processed := 0
	for len(queue) > 0 {
		msg := queue[0]
		queue = queue[1:]
		msg.deliveries++
		err := handle(msg.body)
		if err == nil {
			processed++
			continue
		}
		name := strings.Fields(msg.body)[0]
		fmt.Printf("fail %s delivery %d: %v\n", name, msg.deliveries, err)
		if msg.deliveries < maxDeliveries {
			queue = append(queue, msg)
		} else {
			msg.reason, msg.source = err.Error(), "payments"
			deadLetters = append(deadLetters, msg)
		}
	}
	for _, msg := range deadLetters {
		fmt.Printf("dead letter %s: deliveries=%d reason=%s source=%s\n",
			strings.Fields(msg.body)[0], msg.deliveries, msg.reason, msg.source)
	}
	fmt.Printf("processed %d, dead letters %d\n", processed, len(deadLetters))
}
Output
ok pay-1 amount 10
fail pay-2 delivery 1: bad amount x
ok pay-3 amount 5
fail pay-2 delivery 2: bad amount x
fail pay-2 delivery 3: bad amount x
dead letter pay-2: deliveries=3 reason=bad amount x source=payments
processed 2, dead letters 1
  • Verdict: idiom. Go has no dead letter channel. A slice of pointers is the queue, a field of the message is the delivery count, and a second slice is the dead letter channel.
  • handle returns an error, and the loop decides from the error and the count. The reason that is kept with the dead letter is the text of the error.
  • A slice is used in place of a channel because the loop puts messages back into the queue that it reads. With a buffered channel, a send back into a full channel from its only reader would block for ever.

Consequences

Benefits.

  • The queue goes on. A message that always fails leaves the queue after a limit, so it stops using the receivers.
  • No message is lost because of a bad message. The message and its reason are kept for a person or a program.
  • A place to watch. The length of the dead letter channel is a simple signal that something is wrong.

Liabilities.

  • The order changes. A message that leaves the queue is no longer in its place in the order. Amazon SQS says: "Don't use a dead-letter queue with a FIFO queue if you don't want to break the exact order of messages or operations."3
  • Temporary failures can end in the channel. A limit that is too low moves messages that a retry would process. SQS advises to set the maxReceiveCount "high enough to allow for sufficient retries".3
  • The messages can expire there. For SQS standard queues, the expiry of a message is based on the time it was first put in the source queue, so "it is a best practice to always set the retention period of a dead-letter queue to be longer than the retention period of the original queue."3
  • The move can fail. RabbitMQ says that dead-lettering is a form of publishing, and "using DLX in a clustered RabbitMQ environment is not guaranteed to be safe."6 Pub/Sub counts delivery attempts on a best-effort basis, so a subscriber can get a message more times than the limit.5
  • Cycles. A dead letter channel that sends the message back to its source can make a loop. RabbitMQ finds such a cycle and drops the message "if there was no rejection in the entire cycle".6

When not to use it

As the retry mechanism. A dead letter channel is for the messages that cannot be processed. For a temporary failure, use a retry with a delay first; see Retry with backoff. RabbitMQ compares the two and says that "Dead lettering remains the right tool for messages that cannot be processed at all".6

When a lost message is acceptable and nobody will read the dead letters. For data such as a periodic measurement, the next message replaces the last one. Discard the bad message and count it.

When the order of all messages is a requirement. A message that leaves the queue breaks the order. Stop the queue and alert a person, or use a channel for each key so that only one key stops.

Invalid Message Channel. The receiver, not the messaging system, decides that a message is bad and moves it. The book asks: "How can a messaging receiver gracefully handle receiving a message that makes no sense?"7 Some brokers use one channel for both cases, and the reason tells them apart: Service Bus sets its own reasons and lets applications define their own codes.4

Dead-letter exchange and dead-letter topic. RabbitMQ publishes a dead letter to an exchange, which routes it to one or more queues, and adds an x-death header with the history of the message.6 Pub/Sub forwards a dead letter to a topic, and it wraps the original message in a new one with attributes that identify the source subscription.5

Redelivery before the dead letter channel. In Apache Camel, the Dead Letter Channel is an error handler that tries again with a redelivery policy, and "Only when all redelivery attempts have failed, then the message is moved to the dead letter queue."8 The default is no redelivery: maximumRedeliveries is 0.8

Guaranteed Delivery. A dead letter channel keeps a failed message, and Guaranteed Delivery keeps the messages that are on the way. Together they make sure that a message is either delivered or kept.

Point-to-Point Channel. The redelivery that comes before a dead letter is the at-least-once delivery of a Point-to-Point Channel.

Known uses

  • Apache Camel: DeadLetterChannel.java at camel-4.14.0 is the error handler that moves a message to a dead letter endpoint after it tries to redeliver it with a RedeliveryPolicy.9
  • Amazon SQS dead-letter queues, with a redrive policy and a redrive back to the source.3 The book site gives SQS as an example of the pattern.1
  • RabbitMQ dead-letter exchanges.6
  • Azure Service Bus: a dead-letter subqueue for each queue and each topic subscription.4
  • Google Cloud Pub/Sub dead-letter topics.5

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Dead Letter Channel (problem and solution under CC BY), problem and solution statements; pattern text; examples for Amazon SQS and Kafka Connect
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 4, Messaging Channels, Dead Letter Channel and Invalid Message Channel
  3. Amazon SQS Developer Guide, Using dead-letter queues in Amazon SQS, Using policies for dead-letter queues; Understanding message retention periods for dead-letter queues
  4. Azure Service Bus dead-letter queues, Maximum delivery count; Time to live; Application-level dead-lettering
  5. Google Cloud Pub/Sub documentation, Dead-letter topics, How dead-letter topics work; How maximum delivery attempts are calculated
  6. RabbitMQ documentation, Dead Letter Exchanges, What is a Dead Letter Exchange; Dead-letter cycle; Delayed Retries; Safety
  7. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Invalid Message Channel (problem and solution under CC BY), problem and solution statements
  8. Apache Camel 4.14.0 documentation source, Dead Letter Channel, Redelivery; Redelivery default values
  9. Apache Camel 4.14.0 source, DeadLetterChannel.java, class DeadLetterChannel, lines 29 to 33

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/XMPVT7/text.yaml