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 step

The orders listener throws on offset 7: the payment service answers 503. Retrying in place would hold up offset 8 and everything behind it.

Step 1 of 6
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.

What to do with a record that failsIf the failure can never succeed, such as a record that cannot be deserialized, send it straight to the Dead Letter Topic. If it is transient, retry it. When the order of records per key matters, retry in place, which blocks the partition. When throughput matters more, use retry topics. When retries run out, the record also goes to the Dead Letter Topic.no: poison pillyesyesnoattempts used upattempts used upListener throwsCan a retryever succeed?Dead Letter Topicat onceMust order perkey be kept?Blocking retriesin placeRetry topicswith delays
What to do with a record that failsIf the failure can never succeed, such as a record that cannot be deserialized, send it straight to the Dead Letter Topic. If it is transient, retry it. When the order of records per key matters, retry in place, which blocks the partition. When throughput matters more, use retry topics. When retries run out, the record also goes to the Dead Letter Topic.no: poison pillyesyesnoattempts used upattempts used upListener throwsCan a retryever succeed?Dead Letter Topicat onceMust order perkey be kept?Blocking retriesin placeRetry topicswith delays
What to do with a record that fails

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
Non-blocking retries with @RetryableTopic, and a handler for the 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
}
Blocking retries in place, then the Dead Letter Topic
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
Let a record that cannot be deserialized reach the error handler
// 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));
Unlimited retries let one bad record stop its partition for good
Blocking retries with the DefaultErrorHandlerThe container polls records 7 to 9 and calls the listener with 7, which throws. The DefaultErrorHandler seeks the partition back to 7, waits for the back-off, and the next poll returns 7 again. After the last attempt, the recoverer publishes 7 to orders-dlt with exception headers, the offset is committed, and the listener goes on with 8.orders-dltDefaultErrorHandlerListenerListener containerrecord 7throwshandle 7seek back to 7, waitrecord 7 again, until attempts run outpublish 7 with exception headersrecord 8
Blocking retries with the DefaultErrorHandlerThe container polls records 7 to 9 and calls the listener with 7, which throws. The DefaultErrorHandler seeks the partition back to 7, waits for the back-off, and the next poll returns 7 again. After the last attempt, the recoverer publishes 7 to orders-dlt with exception headers, the offset is committed, and the listener goes on with 8.orders-dltDefaultErrorHandlerListenerListener containerrecord 7throwshandle 7seek back to 7, waitrecord 7 again, until attempts run outpublish 7 with exception headersrecord 8
Blocking retries with the DefaultErrorHandler

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.

  1. 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.
  2. Let the error reach the handler. Wrap the JSON deserializer in ErrorHandlingDeserializer. The failure becomes a DeserializationException delivered to the error handler, instead of an exception inside poll.
  3. Do not retry what cannot succeed. DefaultErrorHandler classifies DeserializationException as not retryable, so with a DeadLetterPublishingRecoverer the record goes straight to orders-dlt and the offset is committed.
  4. 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.
  5. Check. In a test, publish raw bytes not json to orders: the record appears in orders-dlt with 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");
    });
}
Bad bytes go to the DLT once; good records keep flowing

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

1. A record on orders cannot be deserialized. What should the error handler do with it?
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.
2. With retry topics, a failed update for customer 42 waits in orders-retry-1000 while a later update for customer 42 succeeds on orders. What was given up?
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.