Exception Handling in Apache Kafka
Errors in a Kafka application fall into a few clear groups: the producer cannot deliver a record, the consumer cannot deserialize a record, or your processing code throws. Each group needs a different response, and getting it wrong leads to lost events or a consumer that is stuck on one bad record forever.
This tutorial explains where exceptions happen on both sides, how the plain Java clients report them, and how Spring for Apache Kafka handles them with DefaultErrorHandler, dead-letter topics and ErrorHandlingDeserializer. Retry strategies are covered in more depth in Kafka Retry Mechanism.
1. What Is Exception Handling in Kafka?
Exception handling in Kafka means deciding, for each kind of failure, whether to retry, skip and record (for example in a dead-letter topic), or stop the application, while keeping offsets consistent so that no record is lost silently.
2. Where Exceptions Happen
2.1 Producer side
| Where | Examples | How to handle |
|---|---|---|
Thrown by send() | SerializationException, buffer full after max.block.ms (TimeoutException) | Catch around send(); fix data or capacity |
| Passed to the callback | TimeoutException after delivery.timeout.ms, RecordTooLargeException, authorization errors | Log, alert, store in an outbox for later resend |
| Fatal producer errors | ProducerFencedException, OutOfOrderSequenceException | Close the producer and create a new one |
Transient errors such as leader changes are retried inside the client; see Kafka Producer Retries.
2.2 Consumer side
| Where | Examples | Risk if ignored |
|---|---|---|
Deserialization in poll() | Invalid JSON, wrong schema | RecordDeserializationException on every poll: the consumer is stuck |
| Your processing code | Validation failure, database down, bug | Record skipped (if committed) or reprocessed forever |
| Commits | CommitFailedException after a rebalance | Duplicate processing |
A record that always fails is called a poison pill. The fix is never to retry it forever: send it to a dead-letter topic (DLT) and continue.
3. Exception Handling in Spring for Apache Kafka
3.1 DefaultErrorHandler
DefaultErrorHandler is the default error handler of listener containers. When a listener throws, it seeks the partition back so that the failed record is redelivered, waits for the configured BackOff, and after the last attempt calls a recoverer. Without a recoverer, the record is logged and skipped. The default is 10 attempts in total with no delay (FixedBackOff(0, 9)). Some exceptions are never retried because retrying cannot help, for example DeserializationException, MessageConversionException, ClassCastException and MethodArgumentResolutionException. You can add your own with addNotRetryableExceptions(...).
3.2 DeadLetterPublishingRecoverer
This recoverer publishes the failed record to a dead-letter topic, by default named <topic>-dlt with the same partition number (Spring Kafka 4.x; older versions used .DLT). It adds headers such as kafka_dlt-exception-fqcn, kafka_dlt-exception-message, kafka_dlt-original-topic and kafka_dlt-original-offset. The DLT must have at least as many partitions as the original topic, or you supply a destination resolver.
3.3 ErrorHandlingDeserializer
Deserialization happens inside poll(), before your listener runs. Wrap the real deserializer in ErrorHandlingDeserializer: a bad payload then becomes a DeserializationException passed to the error handler, which sends it straight to the DLT instead of failing every poll.
4. Spring Boot Example: Retry, Then Dead-Letter
The listener processes payment messages. A temporary failure is retried twice, and an invalid amount goes directly to the DLT.
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: payment-processor
auto-offset-reset: earliest
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.apache.kafka.common.serialization.StringDeserializer
package com.javabytechie.kafka;
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;
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 KafkaErrorConfig {
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template);
var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 2)); // 1 + 2 attempts
handler.addNotRetryableExceptions(IllegalArgumentException.class);
return handler;
}
@Bean
NewTopic payments() {
return TopicBuilder.name("payments").partitions(1).replicas(1).build();
}
@Bean
NewTopic paymentsDlt() {
return TopicBuilder.name("payments-dlt").partitions(1).replicas(1).build();
}
}
Spring Boot applies a CommonErrorHandler bean such as this one to the auto-configured listener container factory.
package com.javabytechie.kafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
@Component
public class PaymentListener {
private int gatewayCalls = 0;
@KafkaListener(topics = "payments")
public void process(String amount) {
if (Double.parseDouble(amount) <= 0) {
throw new IllegalArgumentException("Invalid amount " + amount);
}
gatewayCalls++;
System.out.println("Attempt " + gatewayCalls + " for amount " + amount);
throw new IllegalStateException("Payment gateway unavailable"); // simulate an outage
}
@KafkaListener(topics = "payments-dlt", groupId = "payment-dlt-auditor")
public void audit(String amount,
@Header(KafkaHeaders.DLT_EXCEPTION_MESSAGE) String error) {
System.out.println("DLT: " + amount + " | " + error);
}
}
package com.javabytechie.kafka;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
@SpringBootApplication
public class PaymentErrorApplication {
public static void main(String[] args) {
SpringApplication.run(PaymentErrorApplication.class, args);
}
@Bean
ApplicationRunner sendSamples(KafkaTemplate<String, String> template) {
return args -> {
template.send("payments", "-5");
template.send("payments", "250.00");
};
}
}
Output (Spring Boot 4.2.0, Spring for Apache Kafka 4.2.0, local Kafka 4.4 broker; error-handler log lines omitted):
DLT: -5 | Listener method 'public void com.javabytechie.kafka.PaymentListener.process(java.lang.String)' threw exception; Invalid amount -5
Attempt 1 for amount 250.00
Attempt 2 for amount 250.00
Attempt 3 for amount 250.00
DLT: 250.00 | Listener method 'public void com.javabytechie.kafka.PaymentListener.process(java.lang.String)' threw exception; Payment gateway unavailable
The record -5 throws IllegalArgumentException, which is marked as not retryable, so it goes to payments-dlt immediately. The record 250.00 fails with IllegalStateException, is retried twice with a one-second pause (three attempts in total), and is then dead-lettered. The exception message in the header is wrapped by Spring's ListenerExecutionFailedException, which is why it starts with the listener method name. Because the DLT is read by a separate listener container, its line for -5 can appear before the first retry.
5. Handling Errors with the Plain Java Consumer
Without Spring, catch RecordDeserializationException from poll(), record the bad position, and seek past it so the consumer can continue:
try {
records = consumer.poll(Duration.ofMillis(500));
} catch (RecordDeserializationException e) {
System.out.println("Skipping bad record at " + e.topicPartition() + "@" + e.offset());
consumer.seek(e.topicPartition(), e.offset() + 1);
}
For processing errors, catch exceptions per record, publish the record to a DLT with your own producer, and commit only after it is handled.
6. Common Mistakes
- Retrying a poison pill forever, which blocks the whole partition.
- Catching every exception and committing, which hides real outages and loses data.
- Forgetting
ErrorHandlingDeserializer, so one malformed message stops the consumer before the error handler can act. - Creating the DLT with fewer partitions than the source topic while keeping the default same-partition resolver.
- Never reading the DLT: dead-lettered records need monitoring and a replay process.
7. Best Practices
- Classify exceptions: retry transient ones (timeouts, database unavailable) and send permanent ones (validation, deserialization) straight to the DLT.
- Limit retries with backoff, so the time spent on one record stays well below
max.poll.interval.ms. - Keep the original key and headers in the DLT record; the recoverer does this by default.
- Alert on DLT traffic and build a tool to replay records after a fix.
- On the producer side, handle the callback exception and use an outbox for events that must not be lost.
8. Conclusion
Kafka errors happen when producing, when deserializing and when processing. Let the producer retry transient errors and handle its final exception, protect consumers with ErrorHandlingDeserializer, and use DefaultErrorHandler with a DeadLetterPublishingRecoverer so that failing records are retried a few times and then parked, not lost. See Apache Kafka with Spring Boot for the basic setup.
9. References
Kafka Exception Handling Interview Questions and Answers
Common interview questions on Kafka Exception Handling, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is a poison pill in Kafka?
Answer: A record that a consumer can never process successfully, for example invalid JSON or data that breaks a validation rule. If the consumer keeps retrying it, the partition makes no progress. The usual fix is to send it to a dead-letter topic and commit past it.
Q. What is a dead-letter topic?
Answer: A separate topic where an application publishes records it could not process, together with information about the error. It lets the main consumer continue while keeping the failed records for inspection and replay. Spring Kafka names it <topic>-dlt by default in version 4.
Intermediate questions
Q. Why is ErrorHandlingDeserializer needed if you already have an error handler?
Answer: Deserialization happens inside poll(), before the listener is called, so the listener's error handler never sees the record. ErrorHandlingDeserializer catches the exception and returns a null value with the failure stored in a header. The container then passes a DeserializationException to the error handler, which can dead-letter the record.
Q. Which exceptions does DefaultErrorHandler not retry by default?
Answer: Exceptions that will fail the same way every time, such as DeserializationException, MessageConversionException, ConversionException, MethodArgumentResolutionException, NoSuchMethodException and ClassCastException. These go straight to the recoverer. You can add or remove types with addNotRetryableExceptions and removeClassification.
Tricky and scenario questions
Q. Why should retries in DefaultErrorHandler be short?
Answer: These retries are blocking: the consumer seeks back and redelivers the record on the same thread, so no other records from that partition are processed meanwhile. Long backoffs can exceed max.poll.interval.ms and trigger a rebalance. For long waits use non-blocking retry topics with @RetryableTopic.
Q. Your producer callback reports TimeoutException for a critical event. What should the application do?
Answer: The record was not stored, and the client has already retried until delivery.timeout.ms. The application must not drop it silently: write it to a durable fallback such as an outbox table and republish later, raise an alert, and, for a request-driven flow, return an error to the caller. Resending immediately in a loop usually just repeats the failure.