Errors, retries and Dead Letter Topic
Mid-level Frequently asked 5 min
On this page
The question
What is a poison pill in Kafka, and how do you handle it?
30-second answer
A poison pill is a record that fails every time it is processed, typically because it cannot be deserialized or breaks a validation rule. Since a consumer commits positions, not single messages, retrying it forever blocks its whole partition. Handle it by catching deserialization errors with ErrorHandlingDeserializer, classifying such errors as not retryable, and sending the record to a Dead Letter Topic (DLT) at once, with an alert.
Understand it
A failing record through retry topics
Step by stepThe orders listener throws on offset 7: the payment service answers 503. Retrying in place would hold up offset 8 and everything behind it.
View as text
Four topics as rows: orders, orders-retry-1000, orders-retry-2000 and orders-dlt, the Dead Letter Topic. A marker shows where the failing record is and what happened to it; the orders row also shows the next offset its consumer reads.
The orders listener throws on offset 7: the payment service answers 503. Retrying in place would hold up offset 8 and everything behind it.
Spring Kafka publishes the record to orders-retry-1000 and commits offset 7. The main consumer goes on with offset 8, so one failure does not stall the partition.
One second after the failure, the consumer of orders-retry-1000 runs the listener again. Still 503, so the record moves on to orders-retry-2000.
Two seconds later the third and last attempt fails. The record goes to orders-dlt, with headers naming the exception and its original topic, partition and offset.
Offset 9 is not valid JSON: a poison pill. No retry can fix it, so a deserialization error is classified as not retryable and goes straight to orders-dlt.
A DLT handler alerts the team. Once the cause is fixed, they republish the records from orders-dlt to orders. Nothing was lost, and orders never stopped.
Four topics as rows: orders, orders-retry-1000, orders-retry-2000 and orders-dlt, the Dead Letter Topic. A marker shows where the failing record is and what happened to it; the orders row also shows the next offset its consumer reads.
The orders listener throws on offset 7: the payment service answers 503. Retrying in place would hold up offset 8 and everything behind it.
Spring Kafka publishes the record to orders-retry-1000 and commits offset 7. The main consumer goes on with offset 8, so one failure does not stall the partition.
One second after the failure, the consumer of orders-retry-1000 runs the listener again. Still 503, so the record moves on to orders-retry-2000.
Two seconds later the third and last attempt fails. The record goes to orders-dlt, with headers naming the exception and its original topic, partition and offset.
Offset 9 is not valid JSON: a poison pill. No retry can fix it, so a deserialization error is classified as not retryable and goes straight to orders-dlt.
A DLT handler alerts the team. Once the cause is fixed, they republish the records from orders-dlt to orders. Nothing was lost, and orders never stopped.
Takeaway: Non-blocking retries move a failing record to retry topics with growing delays, so the main topic keeps flowing. When attempts run out, or the error can never succeed, the record lands in a Dead Letter Topic.
In code
@RetryableTopic(attempts = "3", backoff = @Backoff(delay = 1000, multiplier = 2),
exclude = ValidationException.class) // a bad order will not improve: no retry
@KafkaListener(topics = "orders", groupId = "payments")
void on(OrderPlaced e) {
payments.charge(e); // throws when the payment service is down
}
@DltHandler
void dead(OrderPlaced e, @Header(KafkaHeaders.DLT_EXCEPTION_MESSAGE) String why) {
alerts.raise("order " + e.orderId() + " in orders-dlt: " + why);
}
// Topics created: orders-retry-1000, orders-retry-2000 and orders-dlt@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var toDlt = new DeadLetterPublishingRecoverer(template); // to orders-dlt, same partition number
var backOff = new ExponentialBackOffWithMaxRetries(3); // 1 s, 2 s, 4 s, then give up
backOff.setInitialInterval(1000);
backOff.setMultiplier(2);
var handler = new DefaultErrorHandler(toDlt, backOff);
handler.addNotRetryableExceptions(ValidationException.class);
return handler; // Spring Boot sets it on the listener container
}spring.kafka.consumer.value-deserializer=\
org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
spring.kafka.consumer.properties.spring.deserializer.value.delegate.class=\
org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties.spring.json.trusted.packages=com.shop.orders// Retries forever: a record that can never succeed blocks every record behind it
Wrong new DefaultErrorHandler(new FixedBackOff(1000L, FixedBackOff.UNLIMITED_ATTEMPTS));
// Three retries 1 s apart, then the Dead Letter Topic, and the partition moves on
Right new DefaultErrorHandler(new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 3L));Solve it
One malformed record stopped the orders consumer for hours
A partner system published one record to orders that is not valid JSON. The payments consumer has logged the same
deserialization error thousands of times since, lag on partition 4 keeps growing, and the other partitions are fine.
Explain what is happening and make the consumer survive the next bad record.
- Recognize a poison pill. The value cannot be deserialized, so it fails on every attempt. The failure happens
inside
poll, before any listener or error handler sees a record, so the consumer fails on the same offset again and again, and partition 4 never moves. - Let the error reach the handler. Wrap the JSON deserializer in
ErrorHandlingDeserializer. The failure becomes aDeserializationExceptiondelivered to the error handler, instead of an exception insidepoll. - Do not retry what cannot succeed.
DefaultErrorHandlerclassifiesDeserializationExceptionas not retryable, so with aDeadLetterPublishingRecovererthe record goes straight toorders-dltand the offset is committed. - Make the dead letters visible. Alert on records arriving in
orders-dlt, keep its retention longer than the source’s, and give it at least as many partitions, since the recoverer keeps the partition number. - Check. In a test, publish raw bytes
not jsontoorders: the record appears inorders-dltwith exception headers, the next valid record is processed, and lag returns to zero.
// value-deserializer = ErrorHandlingDeserializer, delegating to JsonDeserializer (see In code)
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
return new DefaultErrorHandler(new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 2L));
} // DeserializationException is not retryable: no 2 retries for it, straight to orders-dlt
@Test
void poisonPillGoesToTheDltAndTheNextRecordIsProcessed() {
rawTemplate.send("orders", "order-1", "not json".getBytes());
template.send("orders", "order-2", new OrderPlaced("order-2"));
await().untilAsserted(() -> {
assertThat(dltRecords("orders-dlt")).extracting(ConsumerRecord::key).containsExactly("order-1");
assertThat(payments.charged()).containsExactly("order-2");
});
}How to answer
- Lag growing on one partition while others are fine is the typical sign.
- Retries are for transient failures; a poison pill is permanent.
- Schemas and a schema registry stop many poison pills at the producer.
Common mistakes
- Catching every exception in the listener and only logging it, so failed records disappear silently.
- Retrying without a limit, so one bad record stops a partition for good.
Follow-up questions
What are retry topics, and when do you use them instead of blocking retries?
Blocking retries repeat the failed record in place, with a back-off, so the partition waits. That keeps order, but one slow dependency stalls everything behind the record. Retry topics move the failed record to topics such as orders-retry-1000 and orders-retry-2000, consumed after a delay, and commit it in the main topic, which keeps flowing. The cost: records of the same key can now be processed out of order.
- Spring Kafka creates the retry topics and the DLT from @RetryableTopic.
- By default the suffixes carry the delay, such as -retry-1000, and the DLT ends in -dlt.
- Use blocking retries when order per key matters, retry topics when throughput does.
See it in the infographic: A failing record through retry topics
What is a Dead Letter Topic, and what do you do with the records in it?
A Dead Letter Topic (DLT) holds records that could not be processed after the allowed attempts, or that can never succeed. Each record keeps its key and value, plus headers with the exception, the original topic, partition and offset. Someone must own it: alert when records arrive, find the cause, fix the code or the data, then republish the records to the original topic, or discard them deliberately.
- Keep DLT retention longer than the source, so nothing expires before someone looks.
- Replaying from the DLT needs idempotent consumers.
- A DLT that nobody watches is just a slower way to lose data.
See it in the infographic: A failing record through retry topics
How does Spring Kafka handle an exception thrown by a listener?
The listener container passes it to its CommonErrorHandler, by default the DefaultErrorHandler. It seeks the partition back so the record is redelivered, up to 10 deliveries with no delay by default, then logs it and moves on. Give it a back-off and a DeadLetterPublishingRecoverer to publish to a DLT instead. Exceptions such as DeserializationException are not retried. @RetryableTopic switches to non-blocking retries through retry topics.
- Spring Boot applies a CommonErrorHandler bean to the auto-configured listener container.
- addNotRetryableExceptions marks your own permanent errors.
- The recoverer runs after the last failed attempt, then the offset is committed.
See it in the infographic: A failing record through retry topics
Why does a Dead Letter Topic need at least as many partitions as the source topic?
Spring Kafka's DeadLetterPublishingRecoverer sends a failed record to the same partition number in the DLT by default. If the DLT has fewer partitions, publishing fails for the higher ones. Either create it with as many partitions, or give the recoverer a destination resolver that picks a partition.
Check yourself
Show answers
- Send it to the Dead Letter Topic at once, and alert: Correct. No retry can fix bad bytes, so retrying only delays the partition.
- Retry it until it succeeds: Incorrect. It never will, and the partition stays blocked.
- Skip it and log nothing: Incorrect. The record is lost, and nobody learns the producer is broken.
Show answers
- Processing order for that key: Correct. The later update ran before the earlier one is retried.
- Durability of the failed record: Incorrect. The record is safe in the retry topic.
- Throughput of the main topic: Incorrect. Throughput is what retry topics protect.