00:00

Exception Handling in Apache Kafka

Last updated:

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.

Key idea: Kafka does not remove a record from a partition when processing fails. The consumer decides what happens by choosing which offset to commit.

2. Where Exceptions Happen

2.1 Producer side

WhereExamplesHow to handle
Thrown by send()SerializationException, buffer full after max.block.ms (TimeoutException)Catch around send(); fix data or capacity
Passed to the callbackTimeoutException after delivery.timeout.ms, RecordTooLargeException, authorization errorsLog, alert, store in an outbox for later resend
Fatal producer errorsProducerFencedException, OutOfOrderSequenceExceptionClose 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

WhereExamplesRisk if ignored
Deserialization in poll()Invalid JSON, wrong schemaRecordDeserializationException on every poll: the consumer is stuck
Your processing codeValidation failure, database down, bugRecord skipped (if committed) or reprocessed forever
CommitsCommitFailedException after a rebalanceDuplicate 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.

Error handling flow in a Spring Kafka listenerA record from the payments topic goes to the listener. If processing succeeds, the offset is committed. If it throws a retryable exception, DefaultErrorHandler seeks back and redelivers the record after a backoff. When attempts are exhausted, or for a non-retryable exception, DeadLetterPublishingRecoverer publishes the record with exception headers to payments-dlt and the offset is committed so the consumer continues. paymentstopic @KafkaListenerprocess record commit offset success DefaultErrorHandlerseek back, backoff throws redeliver (retryable) payments-dlt+ error headers exhausted ornot retryable
Failed records are retried a limited number of times, then parked in a dead-letter topic so the partition keeps moving.

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.

application.yml
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
KafkaErrorConfig.java
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.

PaymentListener.java
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);
    }
}
PaymentErrorApplication.java
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):

Output
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:

Poison pill handling
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