Spring Kafka: dead letter topics and retry topics

A record that keeps failing must go somewhere it can be inspected and fixed, instead of blocking its partition or being skipped. In Kafka that place is a dead letter topic. This page explains how Spring Kafka publishes failed records there, then runs each approach against a real broker inside the program, from DLT headers and routing to non-blocking retry topics and replaying dead letters.

Contents

What a dead letter topic is for

A dead letter topic (DLT) is an ordinary Kafka topic that holds records a consumer could not process. Instead of retrying a failing record forever, which blocks its partition, or logging and skipping it, which loses it, the consumer publishes it to the DLT, commits its offset and moves on. The record can then be inspected, fixed and replayed, or deliberately discarded.

In Spring for Apache Kafka, two mechanisms put records into dead letter topics:

  • DeadLetterPublishingRecoverer: a recoverer for the DefaultErrorHandler. The error handler retries the record in memory, blocking the partition, and after the last retry the recoverer publishes it, with headers that describe the failure.
  • @RetryableTopic: non-blocking retries. A failed record is published to a retry topic and consumed again after a delay, while the main topic keeps flowing. After the last attempt it goes to the DLT.
Blocking retries with a DLT, compared with retry topics
DefaultErrorHandler + DeadLetterPublishingRecoverer@RetryableTopic
Where retries happenIn the consumer, by seeking backIn separate retry topics
Other records during retriesWait behind the failed recordKeep being processed
Order of records for one keyKeptLost: a retried record is processed after later ones
Long delays (minutes)Hold up the partitionFine
Extra topicsOne DLTOne per retry delay, plus a DLT
ConfigurationA CommonErrorHandler beanOne annotation on the listener

The examples are Spring Boot 4.1 applications with spring-boot-starter-kafka, which brings Spring for Apache Kafka 4.1. Each starts a single Kafka broker inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test, in the startBroker method at the end, and turns logging off so that error log lines with timestamps do not hide the output. The general error handling machinery, back-off and non-retryable exceptions are explained on the error handling page.

DeadLetterPublishingRecoverer and the DLT headers

Order o-7 has a negative quantity, which the listener rejects; o-8, sent right after it to the same partition, is valid. The error handler retries twice, 100 ms apart, then the recoverer publishes o-7 to the dead letter topic, where a second listener prints it with its headers:

Java
package demo.kafka.dlt;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.header.Header;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class DltBasics {

    static final CountDownLatch DEAD = new CountDownLatch(1);
    static final CountDownLatch GOOD = new CountDownLatch(1);

    @Bean
    NewTopic orders() {
        return TopicBuilder.name("orders").partitions(2).replicas(1).build();
    }

    // same partition count as orders: the recoverer keeps the original partition
    @Bean
    NewTopic ordersDlt() {
        return TopicBuilder.name("orders-dlt").partitions(2).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler(KafkaOperations<Object, Object> template) {
        return new DefaultErrorHandler(new DeadLetterPublishingRecoverer(template),
                new FixedBackOff(100, 2));
    }

    @Component
    static class OrderListener {
        @KafkaListener(id = "orders", topics = "orders", groupId = "orders")
        void on(String order) {
            if (order.contains("qty=-1")) {
                throw new IllegalArgumentException("quantity must be positive");
            }
            GOOD.countDown(); // o-8 waits behind o-7's retries, then succeeds
        }

        @KafkaListener(id = "orders-dlt", topics = "orders-dlt", groupId = "orders-dlt")
        void dead(ConsumerRecord<String, String> record) {
            System.out.println("dead letter in " + record.topic() + "-" + record.partition()
                    + ", key " + record.key() + ", value " + record.value());
            Map<String, String> headers = new TreeMap<>();
            for (Header h : record.headers()) {
                String value = h.key().endsWith("-stacktrace")
                        ? "(the full stack trace)"
                        : h.key().endsWith("-partition") || h.key().endsWith("-offset")
                                || h.key().endsWith("-timestamp")
                        ? "(binary number)"
                        : new String(h.value(), StandardCharsets.UTF_8);
                headers.put(h.key(), value);
            }
            headers.forEach((k, v) -> System.out.println("  " + k + " = " + v));
            DEAD.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(DltBasics.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("orders", 1, "o-7", "o-7 qty=-1").get();
            template.send("orders", 1, "o-8", "o-8 qty=2").get();
            System.out.println("dead letter received: " + DEAD.await(60, TimeUnit.SECONDS)
                    + ", o-8 processed: " + GOOD.await(60, TimeUnit.SECONDS));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
dead letter in orders-dlt-1, key o-7, value o-7 qty=-1
  kafka_dlt-exception-cause-fqcn = java.lang.IllegalArgumentException
  kafka_dlt-exception-fqcn = org.springframework.kafka.listener.ListenerExecutionFailedException
  kafka_dlt-exception-message = Listener method 'void demo.kafka.dlt.DltBasics$OrderListener.on(java.lang.String)' threw exception; quantity must be positive
  kafka_dlt-exception-stacktrace = (the full stack trace)
  kafka_dlt-original-consumer-group = orders
  kafka_dlt-original-offset = (binary number)
  kafka_dlt-original-partition = (binary number)
  kafka_dlt-original-timestamp = (binary number)
  kafka_dlt-original-timestamp-type = CreateTime
  kafka_dlt-original-topic = orders
dead letter received: true, o-8 processed: true
  • The dead letter arrived in orders-dlt, partition 1, the same partition as the original, with the original key and value unchanged.
  • The name orders-dlt is the recoverer's default: the original topic plus -dlt. Older Spring for Apache Kafka releases named it orders.DLT, so check consumers and topic definitions, and the release notes of the version you upgrade from, when you move an older application. If the DLT does not exist and the broker does not create topics on its own, publishing fails and the record is lost.
  • kafka_dlt-exception-fqcn is ListenerExecutionFailedException, Spring's wrapper; kafka_dlt-exception-cause-fqcn names the real cause, IllegalArgumentException, and the message header contains both messages.
  • The original topic, partition, offset, timestamp and consumer group are kept, so the record can be traced back. The partition, offset and timestamp are stored as binary numbers, which the program does not decode. The full stack trace is in a header too.
  • o-8 was processed after o-7 had gone to the DLT: the partition was blocked only during o-7's two retries.

Spring Boot does not create a recoverer on its own; the CommonErrorHandler bean above wires one in, using Boot's KafkaTemplate. Declare the DLT with at least as many partitions as the original topic, because the recoverer publishes to the same partition number by default.

Routing dead letters by failure type

Invalid data and a downstream outage need different follow-up: the first needs a person to fix the data, the second only needs a replay once the service is back. A destination resolver, passed to the recoverer, chooses the topic per record and exception. Here the original topic has three partitions and both dead letter topics have one:

Java
package demo.kafka.routing;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class DltRouting {

    static final List<String> ARRIVED = new CopyOnWriteArrayList<>();

    static class InvalidOrder extends RuntimeException {
        InvalidOrder(String message) {
            super(message);
        }
    }

    @Bean
    NewTopic orders() {
        return TopicBuilder.name("orders").partitions(3).replicas(1).build();
    }

    // one partition each: smaller than orders, so the partition must be left to Kafka
    @Bean
    NewTopic invalid() {
        return TopicBuilder.name("orders.invalid").partitions(1).replicas(1).build();
    }

    @Bean
    NewTopic failed() {
        return TopicBuilder.name("orders.failed").partitions(1).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler(KafkaOperations<Object, Object> template) {
        DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(template,
                (record, exception) -> {
                    String topic = exception.getCause() instanceof InvalidOrder
                            ? "orders.invalid" : "orders.failed";
                    return new TopicPartition(topic, -1); // -1: let the producer choose
                });
        DefaultErrorHandler handler = new DefaultErrorHandler(recoverer, new FixedBackOff(0, 1));
        handler.addNotRetryableExceptions(InvalidOrder.class);
        return handler;
    }

    @Component
    static class Listeners {
        @KafkaListener(id = "orders", topics = "orders", groupId = "orders")
        void on(String order) {
            if (order.startsWith("bad")) {
                throw new InvalidOrder("missing customer");
            }
            throw new IllegalStateException("warehouse API down");
        }

        @KafkaListener(id = "dead", topics = {"orders.invalid", "orders.failed"},
                groupId = "dead")
        void dead(ConsumerRecord<String, String> record) {
            ARRIVED.add(record.value() + " -> " + record.topic() + "-" + record.partition());
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(DltRouting.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("orders", 2, null, "bad order from partition 2").get();
            template.send("orders", 2, null, "good order from partition 2").get();
            for (int i = 0; i < 100 && ARRIVED.size() < 2; i++) {
                Thread.sleep(100);
            }
            ARRIVED.stream().sorted().forEach(System.out::println);
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
bad order from partition 2 -> orders.invalid-0
good order from partition 2 -> orders.failed-0
  • The InvalidOrder exception sent the bad order to orders.invalid. It is also classified as not retryable, so it went there on the first failure.
  • The IllegalStateException sent the other order to orders.failed, after one retry.
  • Both records came from partition 2 of orders and landed in partition 0 of their dead letter topics. The resolver returned partition -1, which leaves the choice to the producer. Returning the original partition 2 would have failed, because these topics have only one partition.

The resolver receives the exception as thrown by the container, so it checks getCause() to find the listener's own exception. A resolver can also return null to drop a record deliberately, for example a duplicate that no one needs to see.

Non-blocking retries with @RetryableTopic

An email to a full mailbox may succeed hours later, and holding up every other email while waiting is not acceptable. @RetryableTopic moves each retry to its own topic. This listener allows four attempts with delays of 1, 2 and 4 seconds; bounce@example.com always fails, and ann@example.com succeeds:

Java
package demo.kafka.retrytopic;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.Admin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.BackOff;
import org.springframework.kafka.annotation.DltHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.RetryableTopic;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class RetryTopics {

    static final CountDownLatch DONE = new CountDownLatch(2);
    static volatile long start;

    static long elapsed() {
        return Math.round((System.nanoTime() - start) / 1000000 / 100.0) * 100;
    }

    @Component
    static class EmailListener {
        // 4 attempts in all, waiting 1 s, then 2 s, then 4 s between them
        @RetryableTopic(attempts = "4", backOff = @BackOff(delay = 1000, multiplier = 2.0))
        @KafkaListener(id = "emails", topics = "emails", groupId = "emails")
        void on(String email, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
            if (start == 0) {
                start = System.nanoTime();
            }
            System.out.println("  " + elapsed() + " ms: " + email + " from " + topic);
            if (email.startsWith("bounce")) {
                throw new IllegalStateException("mailbox unavailable");
            }
            DONE.countDown();
        }

        @DltHandler
        void dead(String email, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
            System.out.println("  " + elapsed() + " ms: " + email + " reached " + topic);
            DONE.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(RetryTopics.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("emails", "bounce@example.com").get();
            template.send("emails", "ann@example.com").get();
            System.out.println("both finished: " + DONE.await(60, TimeUnit.SECONDS));
            try (Admin admin = Admin.create(
                    context.getBean(KafkaAdmin.class).getConfigurationProperties())) {
                System.out.println("topics created: "
                        + new TreeSet<>(admin.listTopics().names().get()));
            }
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
0 ms: bounce@example.com from emails
  600 ms: ann@example.com from emails
  1000 ms: bounce@example.com from emails-retry-1000
  3100 ms: bounce@example.com from emails-retry-2000
  7100 ms: bounce@example.com from emails-retry-4000
  7600 ms: bounce@example.com reached emails-dlt
both finished: true
topics created: [emails, emails-dlt, emails-retry-1000, emails-retry-2000, emails-retry-4000]
  • The bounce failed on emails at 0 ms. ann's email, behind it in the same partition, was processed right away, before any retry: the main topic was not blocked.
  • The failed record was republished to emails-retry-1000, consumed again about 1 second later, then moved to emails-retry-2000 and emails-retry-4000. The gaps between attempts were about 1, 2 and 4 seconds, as configured.
  • After the fourth attempt, the record went to emails-dlt, where the @DltHandler method received it.
  • Spring created all five topics on its own. Because the delays differ, each retry topic is named after its delay; with a fixed delay, one emails-retry topic is reused for every attempt.

Each retry topic has its own listener container in the same consumer group. A delayed record carries a header with its due time; when a container polls a record that is not due yet, it pauses that partition until the time comes. The price is ordering: ann's email was handled before an earlier email to the same consumer. Use retry topics only when records are independent of each other. include and exclude on the annotation limit which exceptions are retried, and exceptionBasedDltRouting sends chosen exceptions to their own DLT.

Processing and replaying dead letters

A dead letter topic is only useful if someone reads it. A common case is a bug: records failed because of a parsing mistake, the fix is deployed, and the dead letters must be processed again. Here prices with a currency prefix, EUR 12.50, fail to parse until the bug is fixed:

Java
package demo.kafka.replay;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class ReplayDlt {

    // the bug: prices with a currency symbol were not parsed. Fixed before the replay.
    static volatile boolean bugFixed = false;
    static volatile CountDownLatch dead = new CountDownLatch(2);
    static volatile CountDownLatch replayed = new CountDownLatch(2);

    @Bean
    NewTopic prices() {
        return TopicBuilder.name("prices").partitions(1).replicas(1).build();
    }

    @Bean
    NewTopic pricesDlt() {
        return TopicBuilder.name("prices-dlt").partitions(1).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler(KafkaOperations<Object, Object> template) {
        DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(template);
        return new DefaultErrorHandler((record, e) -> {
            recoverer.accept(record, e);
            dead.countDown();
        }, new FixedBackOff(0, 0));
    }

    @Component
    static class PriceListener {
        @KafkaListener(id = "prices", topics = "prices", groupId = "prices")
        void on(String price) {
            String digits = bugFixed ? price.replace("EUR ", "") : price;
            System.out.println("  priced " + Double.parseDouble(digits) + " from '" + price + "'");
            if (bugFixed) {
                replayed.countDown();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(ReplayDlt.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            System.out.println("1. Before the fix:");
            for (String price : List.of("9.99", "EUR 12.50", "4.20", "EUR 3.00")) {
                template.send("prices", price).get();
            }
            dead.await(30, TimeUnit.SECONDS);

            System.out.println("2. Deploy the fix, then replay prices-dlt into prices:");
            bugFixed = true;
            ConsumerFactory<?, ?> factory = context.getBean(ConsumerFactory.class);
            List<ConsumerRecord<?, ?>> deadLetters = new ArrayList<>();
            try (Consumer<?, ?> consumer = factory.createConsumer("replay-tool", null)) {
                consumer.subscribe(List.of("prices-dlt"));
                while (deadLetters.size() < 2) {
                    consumer.poll(Duration.ofSeconds(1)).forEach(deadLetters::add);
                }
                consumer.commitSync(); // a second replay run would not repeat these
            }
            System.out.println("  replaying offsets " + deadLetters.stream()
                    .map(ConsumerRecord::offset).toList() + " of prices-dlt");
            for (ConsumerRecord<?, ?> record : deadLetters) {
                // a new record: the dead-letter headers are left behind
                template.send(new ProducerRecord<>("prices", (String) record.key(),
                        (String) record.value())).get();
            }
            System.out.println("replayed records processed: "
                    + replayed.await(30, TimeUnit.SECONDS));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
1. Before the fix:
  priced 9.99 from '9.99'
  priced 4.2 from '4.20'
2. Deploy the fix, then replay prices-dlt into prices:
  replaying offsets [0, 1] of prices-dlt
  priced 12.5 from 'EUR 12.50'
  priced 3.0 from 'EUR 3.00'
replayed records processed: true
  • Before the fix, the plain prices were processed and the two with a currency prefix failed with NumberFormatException. FixedBackOff(0, 0) sent them to prices-dlt on the first failure, since retrying the same bug cannot help.
  • After the fix, a replay consumer with its own group read the two dead letters at offsets 0 and 1 of prices-dlt, committed its position, and republished their keys and values to prices.
  • The listener processed both replayed prices, 12.5 and 3.0.

The replay sends new records with only the key and value. Copying the kafka_dlt-* headers along would mislead anyone who reads them later, and a record that fails again then gets fresh headers. Committing the replay consumer's offsets makes the tool safe to run twice. Replayed records arrive after newer records, so a replay can apply an old update over a newer one; for entity updates, check a version or timestamp before applying.

Operating dead letter topics

These practices come from the behaviour shown above and from the Spring for Apache Kafka reference documentation:

  • Create the topics explicitly: declare each DLT as a NewTopic bean with enough partitions and a retention long enough for someone to react, often days or weeks, rather than relying on broker auto-creation.
  • Alert on arrivals: a record in a DLT means work was not done. Count them, for example in the recoverer or with consumer lag on the DLT, as the Kafka monitoring page shows, and alert when the count rises.
  • Keep the payload intact: the recoverer copies the original bytes, so even a record that could not be deserialized can be published and examined later. Values that failed in an ErrorHandlingDeserializer are published as raw bytes, which needs a template with a ByteArraySerializer for byte[] values.
  • Separate data errors from outages: route them to different topics, so that one can be replayed automatically and the other reviewed by a person.
  • Do not replay blindly: replay only after the cause is fixed, otherwise the records go straight back to the DLT.

These practices are guidance and were not exercised as separate programs on this page.

Choosing a dead letter strategy

Situations and the approach that fits
SituationApproach
Short outages, order mattersDefaultErrorHandler with a back-off and DeadLetterPublishingRecoverer
Long outages, records are independent@RetryableTopic with growing delays and a @DltHandler
Invalid data that retries cannot fixA not-retryable exception, routed to its own DLT
A bug fixed after records failedA replay tool that republishes key and value from the DLT
A DLT with fewer partitions than the sourceA destination resolver returning partition -1
Records that must never be dropped silentlyA DLT, an alert on its growth, and enough retention

For the producer and consumer basics used here, see KafkaTemplate and @KafkaListener.