Sub topic 12
Routing failed records to a dead-letter topic
This chapter assumes you can run a Spring Boot application with @KafkaListener, and that you have read the previous chapter on retries and back-off with DefaultErrorHandler. You should also know what a partition and an offset are.
Why a dead-letter topic exists
A listener sometimes fails on a record that will never succeed. The payload may be malformed, a required field may be missing, or the business rule may reject it. Retrying does not help. If the consumer keeps failing on that record, it either blocks the partition or loses the record.
A dead-letter topic (DLT) is a separate Kafka topic where you park records that the listener could not process. The main flow continues, and the failed record is kept with enough information to inspect and replay it later.
Spring for Apache Kafka provides this through two classes that work together:
DefaultErrorHandlercatches listener exceptions, retries according to a back-off policy, and calls a recoverer when retries are used up.DeadLetterPublishingRecovereris the recoverer that publishes the failed record to another topic.
The flow of a failing record
The diagram shows what happens to a record that always fails.
The key point is that the handler does not skip the record until the recoverer has finished. If publishing to the DLT succeeds, the container commits past the failed record and moves on.
Configuring the recoverer
This is the configuration from the plan. It retries a failing record three times, one second apart, and then publishes it to orders.DLT.
package com.example.orders;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.FixedBackOff;
@Configuration
public class KafkaErrorHandlingConfig {
@Bean
public DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(template);
return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3L));
}
}Points to note:
FixedBackOff(1000L, 3L)means a 1000 ms interval and a maximum of 3 retries. The listener therefore runs up to four times: the first delivery plus three retries.- Spring Boot applies a single
DefaultErrorHandlerbean to its auto-configured listener container factory. You do not need to wire it manually. - The recoverer needs a
KafkaTemplateto publish. Spring Boot auto-configures one, but its generic types areKafkaTemplate<?, ?>, which is why the bean method can ask forKafkaTemplate<Object, Object>.
Where the record goes
By default the recoverer publishes to a topic named after the original topic plus .DLT. A failure on orders goes to orders.DLT. It uses the same partition number as the original record.
That second detail has a practical consequence. If orders has three partitions and orders.DLT has only one, publishing a record from partition 2 fails because partition 2 does not exist on the DLT. The failure is then logged, and the handler treats the record as not recovered, so it is redelivered.
Declare the DLT with at least as many partitions as the source topic. You can use a NewTopic bean as in the earlier chapter on declaring topics:
package com.example.orders;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;
@Configuration
public class DeadLetterTopicConfig {
@Bean
public NewTopic ordersDeadLetterTopic() {
return TopicBuilder.name("orders.DLT")
.partitions(3)
.replicas(1)
.build();
}
}Choosing a different destination
The recoverer accepts a function that maps the failed record and the exception to a TopicPartition. Use it to change the topic name or to let Kafka choose the partition by returning a partition of -1.
package com.example.orders;
import org.apache.kafka.common.TopicPartition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.FixedBackOff;
@Configuration
public class CustomDeadLetterConfig {
@Bean
public DefaultErrorHandler customErrorHandler(KafkaTemplate<Object, Object> template) {
DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(
template,
(record, ex) -> new TopicPartition("orders.failed", -1));
return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3L));
}
}With a partition of -1, the producer's partitioner decides, using the record key. The DLT then does not have to match the source topic's partition count.
If you define this bean next to the previous one, Spring Boot finds two DefaultErrorHandler beans and cannot choose. Keep only one in a real application, or mark one as @Primary.
What the DLT record contains
The recoverer publishes the original key and value unchanged. It adds headers that describe where the record came from and why it failed.
| Header | Content |
|---|---|
| `kafka_dlt-original-topic` | Topic the record was read from |
| `kafka_dlt-original-partition` | Partition of the original record |
| `kafka_dlt-original-offset` | Offset of the original record |
| `kafka_dlt-original-timestamp` | Timestamp of the original record |
| `kafka_dlt-exception-fqcn` | Class name of the exception |
| `kafka_dlt-exception-message` | Exception message |
| `kafka_dlt-exception-stacktrace` | Stack trace as text |
These headers let you find the original record in the source topic and see the cause without searching logs. The stack trace can be large, so check your broker's maximum message size if you have deep stacks.
Deserialization failures
Some failures happen before your listener runs. If a record contains invalid JSON, the JsonDeserializer throws inside the consumer's poll(), and the container cannot hand you a record at all. Without special handling, the consumer fails on the same offset repeatedly. This is called a poison pill.
Wrap the deserializers with ErrorHandlingDeserializer. It catches the exception, hands the container a record with a null value and the failure in a header, and lets the error handler treat it like any other failure.
spring:
kafka:
consumer:
group-id: order-service
key-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
properties:
spring.deserializer.key.delegate.class: org.apache.kafka.common.serialization.StringDeserializer
spring.deserializer.value.delegate.class: org.springframework.kafka.support.serializer.JsonDeserializer
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventWhen the recoverer publishes such a record, the value is null, so the original bytes would be lost. DeadLetterPublishingRecoverer handles this case. It detects the deserialization failure header and republishes the original raw bytes. For this to work, the DLT producer must be able to send raw bytes. The KafkaTemplate configured earlier uses JsonSerializer for values, which cannot serialize a byte[] correctly.
To support both cases, give the recoverer a map of templates keyed by value type:
package com.example.orders;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.FixedBackOff;
@Configuration
public class PoisonPillConfig {
@Bean
public DefaultErrorHandler poisonPillErrorHandler(
KafkaTemplate<String, OrderEvent> jsonTemplate,
KafkaProperties properties) {
Map<String, Object> bytesConfig = properties.buildProducerProperties(null);
bytesConfig.put("value.serializer", ByteArraySerializer.class);
bytesConfig.put("key.serializer", ByteArraySerializer.class);
KafkaTemplate<byte[], byte[]> bytesTemplate =
new KafkaTemplate<>(new DefaultKafkaProducerFactory<>(bytesConfig));
Map<Class<?>, KafkaTemplate<?, ?>> templates = new LinkedHashMap<>();
templates.put(OrderEvent.class, jsonTemplate);
templates.put(byte[].class, bytesTemplate);
DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(templates);
return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3L));
}
}The recoverer picks the template whose key matches the value's runtime type.
Choosing which exceptions to retry
Not every failure deserves three retries. A NullPointerException from bad data will fail the same way every time. DefaultErrorHandler already treats several exception types as fatal, such as DeserializationException and MessageConversionException. Those go straight to the recoverer with no retries.
You can add your own fatal types:
package com.example.orders;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.FixedBackOff;
public class FatalExceptionExample {
public static DefaultErrorHandler build(DeadLetterPublishingRecoverer recoverer) {
DefaultErrorHandler handler =
new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3L));
handler.addNotRetryableExceptions(IllegalArgumentException.class);
return handler;
}
}Here IllegalArgumentException skips the retries and goes to the DLT on the first failure. Use the opposite approach, defaultFalse classification, only when most of your failures are permanent.
Operating a dead-letter topic
Publishing to a DLT is the easy part. A DLT that nobody reads is a silent data loss. Plan for these points:
- Monitor the DLT. Alert on its lag or message count.
- Record the root cause in logs, correlated by the original topic, partition and offset headers.
- Decide how to replay. Common approaches are a small tool that reads the DLT and republishes to the original topic after a fix, or a separate listener on
orders.DLTthat stores failures for review. - Set retention on the DLT long enough for people to react, for example several days.
- Keep the DLT listener simple. If it throws, you must not route its failures to another DLT in an endless chain.
A minimal listener that logs the failure details:
package com.example.orders;
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.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class OrderDeadLetterListener {
private static final Logger log = LoggerFactory.getLogger(OrderDeadLetterListener.class);
@KafkaListener(topics = "orders.DLT", groupId = "order-service-dlt")
public void onDeadLetter(ConsumerRecord<String, byte[]> record) {
Header message = record.headers().lastHeader("kafka_dlt-exception-message");
log.warn("Dead letter for key {} from original offset: {}",
record.key(),
message == null ? "unknown" : new String(message.value()));
}
}This listener uses its own groupId so that it does not compete with the main consumers. Its value is read as byte[], so it needs a deserializer that accepts bytes. In practice you would configure a separate container factory for it.
Delivery semantics to keep in mind
The recoverer publishes to the DLT and then the container commits the offset of the failed record. These are two separate operations. If the application crashes between them, the record is published to the DLT and then redelivered after restart. It can end up in the DLT twice. Make the DLT consumer idempotent, or use Kafka transactions, covered in a later chapter, so that the publish and the commit succeed or fail together.
Also remember that retries block the partition. With three retries one second apart, a failing record delays all following records on that partition by about three seconds. For long delays, the blocking approach is a poor fit. Non-blocking retry topics are an alternative that moves retries to separate topics, but they change record ordering.
Summary of the pieces
| Component | Responsibility |
|---|---|
| `DefaultErrorHandler` | Retries a failing record with a back-off, then calls the recoverer |
| `FixedBackOff` | Sets the retry interval and the maximum number of retries |
| `DeadLetterPublishingRecoverer` | Publishes the failed record and failure headers to the DLT |
| `ErrorHandlingDeserializer` | Converts deserialization errors into records the handler can process |
| `orders.DLT` | Holds failed records for inspection and replay |
Exercise
Your orders topic has 6 partitions and you declare orders.DLT with 1 partition. You use the default DeadLetterPublishingRecoverer. What happens when a record from partition 4 exhausts its retries, and how do you fix it?
Show answer
The recoverer publishes to the same partition number on the DLT, which is partition 4. That partition does not exist on a 1-partition topic, so the publish fails and the record is not recovered. The handler redelivers it. Fix it by declaring orders.DLT with at least 6 partitions, or by passing a destination resolver that returns a TopicPartition with partition -1 so the producer's partitioner chooses the partition.
Exercise
A producer writes invalid JSON to orders. The consumer uses a plain JsonDeserializer and keeps failing on the same offset without ever reaching the listener or the DLT. What change makes the bad record reach the DLT with its original bytes?
Show answer
Wrap the key and value deserializers with ErrorHandlingDeserializer, and set the real deserializers as delegates with spring.deserializer.key.delegate.class and spring.deserializer.value.delegate.class. The container then receives a record carrying the failure, and the DefaultErrorHandler sends it to the recoverer. Give the recoverer a template that can serialize byte[] so the original bytes are published.