Kafka dead letter topics: handling records that fail
A record that cannot be processed blocks its whole partition unless the consumer moves it aside. This page explains how dead letter topics and retry topics do that, and runs each step with the plain Kafka clients: retries and classification, non-blocking retry topics, the ordering trap, poison records and replay.
Contents
What a dead letter topic is for
A Kafka consumer processes the records of a partition in order, and it commits one offset per partition. That makes failures awkward: a record that cannot be processed blocks every record behind it, because skipping it means losing it, and retrying it for ever means stopping the partition. A dead letter topic (DLT) is the usual way out. The consumer writes the failed record, with details of the failure, to a separate topic, commits past it, and carries on. Someone can then inspect, fix and replay it later.
Kafka itself has no built-in dead letter topic for consumers: a DLT is an ordinary topic, and the consumer code, or a framework, decides what goes there. Three kinds of failure need different treatment:
| Failure | Example | Retrying helps? | Handling |
|---|---|---|---|
| Transient | A timeout, a database restarting, rate limiting | Usually | Retry with backoff, then the DLT |
| Permanent, in the data | A negative quantity, a missing required field | Never | Straight to the DLT |
| Deserialization | Bytes in the wrong format, a poison pill | Never | Raw bytes to the DLT, then seek |
Other parts of the Kafka ecosystem have the idea built in. Kafka Connect sink connectors write failed records to a topic named by errors.deadletterqueue.topic.nameerrors.tolerance=allDeadLetterPublishingRecoverer@RetryableTopicgroup.share.delivery.count.limit
This page builds the pattern with the plain clients of kafka-clientsEmbeddedKafkaKraftBrokerspring-kafka-test
Retry, classify, then dead-letter
An order service processes five orders. One succeeds after a timeout, one is invalid, and one keeps failing because a downstream service is down, so each path of the handler runs once:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class RetryThenDlt {
// a failure that may go away: a timeout, a database that is restarting
static class TransientException extends RuntimeException {
TransientException(String message) {
super(message);
}
}
// a failure that will never go away: the record itself is wrong
static class InvalidOrderException extends RuntimeException {
InvalidOrderException(String message) {
super(message);
}
}
static final int MAX_ATTEMPTS = 3;
static final Map<String, Integer> calls = new HashMap<>();
static String servers;
// the business logic: fails in different ways for some orders
static void process(String order) {
int call = calls.merge(order, 1, Integer::sum);
if (order.contains("qty=-")) {
throw new InvalidOrderException("quantity must be positive: " + order);
}
if (order.startsWith("o-2") && call < 2) {
throw new TransientException("stock service timed out");
}
if (order.startsWith("o-4")) {
throw new TransientException("stock service unavailable");
}
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try (KafkaProducer<String, String> producer = producer()) {
broker.addTopics("orders", "orders.DLT");
for (String order : List.of("o-1 qty=2", "o-2 qty=1", "o-3 qty=-5", "o-4 qty=3",
"o-5 qty=1")) {
producer.send(new ProducerRecord<>("orders", order.substring(0, 3), order));
}
producer.flush();
consumeOrders(producer);
System.out.println("dead letter topic:");
readDlt();
} finally {
broker.destroy();
}
}
static void consumeOrders(KafkaProducer<String, String> dltProducer) throws Exception {
try (KafkaConsumer<String, String> consumer = consumer("order-service")) {
consumer.subscribe(List.of("orders"));
int handled = 0;
while (handled < 5) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
handle(r, dltProducer);
handled++;
// commit only after the record is processed or safely in the DLT
consumer.commitSync(Map.of(new TopicPartition(r.topic(), r.partition()),
new OffsetAndMetadata(r.offset() + 1)));
}
}
}
}
static void handle(ConsumerRecord<String, String> r, KafkaProducer<String, String> dlt)
throws Exception {
for (int attempt = 1; ; attempt++) {
try {
process(r.value());
System.out.println(r.value() + ": done after " + attempt + " attempt(s)");
return;
} catch (TransientException e) {
if (attempt == MAX_ATTEMPTS) {
toDlt(r, e, attempt, dlt);
return;
}
Thread.sleep(100L * attempt); // back off a little longer each time
} catch (RuntimeException e) { // anything else: retrying cannot help
toDlt(r, e, attempt, dlt);
return;
}
}
}
static void toDlt(ConsumerRecord<String, String> r, Exception e, int attempts,
KafkaProducer<String, String> dlt) throws Exception {
ProducerRecord<String, String> dead = new ProducerRecord<>("orders.DLT", null,
r.key(), r.value(), r.headers()); // keep the key, value and headers
Headers h = dead.headers();
h.add("dlt.original.topic", bytes(r.topic()));
h.add("dlt.original.partition", bytes("" + r.partition()));
h.add("dlt.original.offset", bytes("" + r.offset()));
h.add("dlt.exception.class", bytes(e.getClass().getSimpleName()));
h.add("dlt.exception.message", bytes(e.getMessage()));
h.add("dlt.attempts", bytes("" + attempts));
dlt.send(dead).get(); // wait: the offset may only be committed once this is stored
System.out.println(r.value() + ": to orders.DLT after " + attempts + " attempt(s), "
+ e.getClass().getSimpleName());
}
static void readDlt() {
try (KafkaConsumer<String, String> consumer = consumer("dlt-reader")) {
consumer.subscribe(List.of("orders.DLT"));
int seen = 0;
while (seen < 2) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
seen++;
System.out.println(" offset " + r.offset() + ", key " + r.key()
+ ", value \"" + r.value() + "\"");
for (Header header : r.headers()) {
System.out.println(" " + header.key() + " = "
+ new String(header.value(), StandardCharsets.UTF_8));
}
}
}
}
}
static byte[] bytes(String s) {
return s.getBytes(StandardCharsets.UTF_8);
}
static KafkaProducer<String, String> producer() {
return new KafkaProducer<>(Map.of("bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class));
}
static KafkaConsumer<String, String> consumer(String group) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", servers,
"group.id", group,
"enable.auto.commit", false,
"auto.offset.reset", "earliest",
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class));
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// 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.OFF);
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);
}
}
}
o-1 qty=2: done after 1 attempt(s)
o-2 qty=1: done after 2 attempt(s)
o-3 qty=-5: to orders.DLT after 1 attempt(s), InvalidOrderException
o-4 qty=3: to orders.DLT after 3 attempt(s), TransientException
o-5 qty=1: done after 1 attempt(s)
dead letter topic:
offset 0, key o-3, value "o-3 qty=-5"
dlt.original.topic = orders
dlt.original.partition = 0
dlt.original.offset = 2
dlt.exception.class = InvalidOrderException
dlt.exception.message = quantity must be positive: o-3 qty=-5
dlt.attempts = 1
offset 1, key o-4, value "o-4 qty=3"
dlt.original.topic = orders
dlt.original.partition = 0
dlt.original.offset = 3
dlt.exception.class = TransientException
dlt.exception.message = stock service unavailable
dlt.attempts = 3
- o-2 failed once with a
and succeeded on the second attempt, after a 100 ms backoff. Most transient failures end like this, which is why retrying in place comes first.TransientException - o-3 has a negative quantity.
is not transient, so it went toInvalidOrderException after a single attempt; retrying it would only have delayed the partition.orders.DLT - o-4 failed all three attempts and went to the DLT with
.dlt.attempts = 3 - o-5 was processed normally. The two bad records did not stop the partition.
- Each DLT record kept the original key and value, and gained headers naming the original topic, partition and offset, the exception class and message, and the number of attempts. With these, an operator can find the source record and understand the failure without searching logs.
Two details make the pattern safe. The DLT write is synchronous (send(...).get()max.poll.interval.ms
Retry topics: retrying without blocking
When a failure may last for minutes, retrying in place stalls the partition. A retry topic moves the record out of the way: the consumer writes it to orders-retry
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class RetryTopic {
static final int MAX_RETRIES = 2;
static final Map<String, Integer> calls = new HashMap<>();
static String servers;
static int finished;
// o-2 fails once; o-4 fails every time
static void process(String order) {
int call = calls.merge(order, 1, Integer::sum);
if ((order.equals("o-2") && call == 1) || order.equals("o-4")) {
throw new IllegalStateException("payment service unavailable");
}
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class));
KafkaConsumer<String, String> main = consumer("payments");
KafkaConsumer<String, String> retry = consumer("payments-retry")) {
broker.addTopics("orders", "orders-retry", "orders.DLT");
for (int i = 1; i <= 5; i++) {
producer.send(new ProducerRecord<>("orders", "o-" + i, "o-" + i));
}
producer.flush();
main.subscribe(List.of("orders"));
retry.subscribe(List.of("orders-retry"));
TopicPartition retryPartition = new TopicPartition("orders-retry", 0);
while (finished < 5) {
for (ConsumerRecord<String, String> r : main.poll(Duration.ofMillis(100))) {
attempt(r, 0, producer);
}
for (ConsumerRecord<String, String> r : retry.poll(Duration.ofMillis(100))) {
long due = Long.parseLong(header(r, "retry.due"));
if (System.currentTimeMillis() < due) {
// not due yet: rewind and wait; records behind it are due later still
retry.seek(retryPartition, r.offset());
break;
}
attempt(r, Integer.parseInt(header(r, "retry.count")), producer);
}
main.commitSync();
retry.commitSync();
}
} finally {
broker.destroy();
}
}
static void attempt(ConsumerRecord<String, String> r, int retries,
KafkaProducer<String, String> producer) throws Exception {
String from = retries == 0 ? "orders" : "retry " + retries;
try {
process(r.value());
log(r.value() + " done (from " + from + ")");
finished++;
} catch (IllegalStateException e) {
String target = retries < MAX_RETRIES ? "orders-retry" : "orders.DLT";
ProducerRecord<String, String> next = new ProducerRecord<>(target, r.key(),
r.value());
next.headers().add("retry.count", bytes("" + (retries + 1)));
// wait 1 s before the first retry and 2 s before the second
long delay = 1000L * (retries + 1);
next.headers().add("retry.due", bytes("" + (System.currentTimeMillis() + delay)));
next.headers().add("error", bytes(e.getMessage()));
producer.send(next).get();
log(r.value() + " failed (from " + from + ") -> " + target
+ (target.equals("orders.DLT") ? "" : ", due in " + delay / 1000 + " s"));
if (target.equals("orders.DLT")) {
finished++;
}
}
}
static void log(String event) {
System.out.println(event);
}
static String header(ConsumerRecord<String, String> r, String key) {
Header h = r.headers().lastHeader(key);
return new String(h.value(), StandardCharsets.UTF_8);
}
static byte[] bytes(String s) {
return s.getBytes(StandardCharsets.UTF_8);
}
static KafkaConsumer<String, String> consumer(String group) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", servers,
"group.id", group,
"enable.auto.commit", false,
"auto.offset.reset", "earliest",
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class));
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// 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.OFF);
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);
}
}
}
o-1 done (from orders)
o-2 failed (from orders) -> orders-retry, due in 1 s
o-3 done (from orders)
o-4 failed (from orders) -> orders-retry, due in 1 s
o-5 done (from orders)
o-2 done (from retry 1)
o-4 failed (from retry 1) -> orders-retry, due in 2 s
o-4 failed (from retry 2) -> orders.DLT
- o-2 and o-4 failed on the main topic and were moved to
. o-3 and o-5 were processed straight after them: the main topic was never blocked.orders-retry - A second later, o-2 was due and succeeded on its first retry.
- o-4 failed again, went back to the retry topic with a 2-second delay, failed a third time, and was sent to
.orders.DLT - When the retry consumer met a record that was not yet due, it called
back to that offset and stopped the batch. Records in one retry topic all have the same delay, so the ones behind it are due later still.seek
Production setups usually have one retry topic per delay, such as orders-retry-1sorders-retry-1morders-retry-10m@RetryableTopic
The ordering trap of retry topics
A retry topic gives up one of Kafka's guarantees: the order of records with the same key. A customer moves twice, and the first address update hits a transient error. The first run only moves the failed record to a retry topic; the second also parks every later record of the same key behind it:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class RetryOrderTrap {
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
broker.addTopics("addresses", "addresses-retry-a", "addresses-retry-b");
// a customer moves twice; the first update hits a transient failure
producer.send(new ProducerRecord<>("addresses", "cust-7", "Elm Street"));
producer.send(new ProducerRecord<>("addresses", "cust-7", "Oak Avenue"));
producer.send(new ProducerRecord<>("addresses", "cust-9", "Pine Road"));
producer.flush();
run(producer, "addresses-retry-a", false);
run(producer, "addresses-retry-b", true);
} finally {
broker.destroy();
}
}
static void run(KafkaProducer<String, String> producer, String retryTopic,
boolean parkKey) throws Exception {
Map<String, String> saved = new HashMap<>(); // the "database"
Set<String> parked = new HashSet<>(); // keys with a record in the retry topic
boolean[] failedOnce = {false};
try (KafkaConsumer<String, String> consumer = consumer(retryTopic)) {
consumer.subscribe(List.of("addresses", retryTopic));
int done = 0;
while (done < 3) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(200))) {
boolean fromRetry = r.topic().equals(retryTopic);
if (!fromRetry && parkKey && parked.contains(r.key())) {
// keep the key's order: queue behind the record already waiting
producer.send(new ProducerRecord<>(retryTopic, r.key(), r.value()))
.get();
continue;
}
if (!fromRetry && r.value().equals("Elm Street") && !failedOnce[0]) {
failedOnce[0] = true; // the address service timed out
producer.send(new ProducerRecord<>(retryTopic, r.key(), r.value()))
.get();
parked.add(r.key());
continue;
}
saved.put(r.key(), r.value());
done++;
}
}
}
System.out.println((parkKey ? "retry, parking the key's later records: "
: "retry topic only: ") + saved);
}
static KafkaConsumer<String, String> consumer(String group) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", servers,
"group.id", group,
"auto.offset.reset", "earliest",
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class));
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// 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.OFF);
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);
}
}
}
retry topic only: {cust-9=Pine Road, cust-7=Elm Street}
retry, parking the key's later records: {cust-9=Pine Road, cust-7=Oak Avenue}
- With the retry topic alone, "Oak Avenue" was saved first, then the retried "Elm Street" overwrote it. The customer's stored address is now the old one, and no error was reported anywhere.
- With parking, "Oak Avenue" followed "Elm Street" into the retry topic because cust-7 already had a record waiting there. Both were applied in their original order, and the final address is correct. cust-9 was not affected either way.
Use retry topics only when records are independent, or when the processing is order-insensitive, such as appending to a log. For state updates per key, either park the key's later records as here (and keep the set of parked keys in durable storage, not in memory), retry in place and accept the pause, or make updates carry a version so that older ones are ignored.
Deserialization failures and replaying the DLT
A record that cannot be deserialized never reaches the business logic, so it needs its own path to the DLT: the raw bytes, taken from the exception. Afterwards, the DLT must be drained somehow. Here a stock topic of 4-byte integers receives one quantity written as text; an operator later repairs it and sends it back:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.RecordDeserializationException;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class DltReplay {
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try (KafkaProducer<String, byte[]> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", ByteArraySerializer.class))) {
broker.addTopics("stock", "stock.DLT");
// 4-byte ints, but one producer wrote the quantity as text
producer.send(new ProducerRecord<>("stock", "sku-1", new byte[] {0, 0, 0, 5}));
producer.send(new ProducerRecord<>("stock", "sku-2", bytes("12")));
producer.send(new ProducerRecord<>("stock", "sku-3", new byte[] {0, 0, 0, 9}));
producer.flush();
System.out.println("1. consuming stock:");
consumeStock(producer, 3);
// 2. later, an operator inspects the DLT and repairs what can be repaired
System.out.println("2. replaying stock.DLT:");
try (KafkaConsumer<String, byte[]> dlt = new KafkaConsumer<>(Map.of(
"bootstrap.servers", servers,
"group.id", "dlt-replayer",
"auto.offset.reset", "earliest",
"key.deserializer", StringDeserializer.class,
"value.deserializer", ByteArrayDeserializer.class))) {
dlt.subscribe(List.of("stock.DLT"));
int replayed = 0;
while (replayed < 1) {
for (ConsumerRecord<String, byte[]> r : dlt.poll(Duration.ofSeconds(1))) {
String text = new String(r.value(), StandardCharsets.UTF_8);
int fixed = Integer.parseInt(text); // the repair: text to int
byte[] value = ByteBuffer.allocate(4).putInt(fixed).array();
ProducerRecord<String, byte[]> again = new ProducerRecord<>("stock",
r.key(), value);
again.headers().add("dlt.replayed-from", bytes("stock.DLT@"
+ r.offset()));
producer.send(again).get();
System.out.println(" " + r.key() + ": \"" + text + "\" repaired to "
+ fixed + " and sent back to stock");
replayed++;
}
}
dlt.commitSync();
}
System.out.println("3. the stock consumer picks it up:");
consumeStock(producer, 1);
} finally {
broker.destroy();
}
}
static void consumeStock(KafkaProducer<String, byte[]> producer, int expected)
throws Exception {
try (KafkaConsumer<String, Integer> consumer = new KafkaConsumer<>(Map.of(
"bootstrap.servers", servers,
"group.id", "inventory",
"auto.offset.reset", "earliest",
"key.deserializer", StringDeserializer.class,
"value.deserializer", IntegerDeserializer.class))) {
consumer.subscribe(List.of("stock"));
int handled = 0;
while (handled < expected) {
try {
for (ConsumerRecord<String, Integer> r
: consumer.poll(Duration.ofSeconds(1))) {
Header replayed = r.headers().lastHeader("dlt.replayed-from");
System.out.println(" offset " + r.offset() + ": " + r.key() + " = "
+ r.value() + (replayed == null ? "" : " (replayed from "
+ new String(replayed.value(), StandardCharsets.UTF_8) + ")"));
handled++;
}
} catch (RecordDeserializationException e) {
byte[] raw = new byte[e.valueBuffer().remaining()];
e.valueBuffer().get(raw);
String key = e.keyBuffer() == null ? null
: StandardCharsets.UTF_8.decode(e.keyBuffer()).toString();
ProducerRecord<String, byte[]> dead = new ProducerRecord<>("stock.DLT",
key, raw);
dead.headers().add("dlt.original.offset", bytes("" + e.offset()));
dead.headers().add("dlt.exception.message",
bytes(e.getCause().getMessage()));
producer.send(dead).get();
System.out.println(" offset " + e.offset() + ": cannot deserialize ("
+ e.getCause().getMessage() + "), raw bytes sent to stock.DLT");
TopicPartition tp = e.topicPartition();
consumer.seek(tp, e.offset() + 1);
handled++;
}
}
consumer.commitSync();
}
}
static byte[] bytes(String s) {
return s.getBytes(StandardCharsets.UTF_8);
}
// Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the broker logs at INFO and prints its storage setup, so both are turned off.
// 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.OFF);
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);
}
}
}
1. consuming stock:
offset 0: sku-1 = 5
offset 1: cannot deserialize (Size of data received by IntegerDeserializer is not 4), raw bytes sent to stock.DLT
offset 2: sku-3 = 9
2. replaying stock.DLT:
sku-2: "12" repaired to 12 and sent back to stock
3. the stock consumer picks it up:
offset 3: sku-2 = 12 (replayed from stock.DLT@0)
threwpoll() for offset 1. The handler took the raw key and value from the exception, wrote them unchanged toRecordDeserializationException with the error message, and calledstock.DLT . Offsets 0 and 2 were processed normally.seek(offset + 1)- The replay tool read
as plain bytes, found the text "12", converted it to the integer 12 and sent it back tostock.DLT with astock header.dlt.replayed-from - The stock consumer received it as a new record at offset 3. The header shows where it came from, and loops can be detected by checking it before replaying a second time.
A replayed record arrives after records that were written while it sat in the DLT, so the ordering caveat of the previous section applies here too. Replay only once the cause is fixed, and only to consumers that are idempotent: a record that failed after a partial side effect may otherwise apply that effect twice.
Running dead letter topics in production
- Naming: one DLT per source topic, such as
ororders.DLT , makes ownership and replay simple. A shared DLT for many topics needs the original topic in a header, which the examples add anyway.orders-dlt - Partitions and retention: keep the key, so that a DLT with the same partition count keeps records of one key together. Give the DLT a longer retention than the source topic; records there wait for people.
- Monitoring: alert on any growth of the DLT's end offset. A DLT that fills silently is a data-loss incident that nobody has noticed yet. The
lag monitoring page shows how to read end offsets. - Sensitive data: the DLT holds the same data as the source topic, so it needs the same access control and the same handling of personal data.
- Size: a record near the source topic's size limit can fail to enter the DLT once headers are added; give the DLT a slightly larger
.max.message.bytes
Choosing a failure strategy
| Situation | Strategy |
|---|---|
| Short outages of a dependency | A few retries in place with backoff, then the DLT |
| Invalid data | Classify as permanent and send to the DLT at once |
| Long outages, independent records | Retry topics with increasing delays, then the DLT |
| Long outages, per-key state updates | Retry in place, or retry topics with key parking |
| Bytes that do not deserialize | Catch RecordDeserializationException |
| Fixing the records later | A replay tool that repairs, republishes and marks records with a header |
| Spring applications | DefaultErrorHandlerDeadLetterPublishingRecoverer@RetryableTopic |
Related pages: