Spring Kafka error handling and retries

When a @KafkaListener throws, the record is neither lost nor skipped by default: the listener container retries it, then logs it and moves on. This page explains what the DefaultErrorHandler does with a failed record, then runs each important setting against a real Kafka broker inside the program, from back-off and recoverers to poison pills and batch failures.

Contents

What happens when a listener throws

Kafka itself knows nothing about failed records. A consumer reads a partition in offset order and commits how far it got, so to "retry" a record, a consumer reads it again. When a @KafkaListener method throws, Spring's listener container hands the exception and the remaining records of the poll to its CommonErrorHandler. Since Spring for Apache Kafka 2.8, the default is DefaultErrorHandler, and it works like this:

  1. It seeks the consumer back to the failed record, and to the first unprocessed record of every other partition in the poll, so that the next poll returns them again.
  2. It waits according to a BackOff, then lets the container poll and redeliver the record.
  3. When the back-off is exhausted, it calls a recoverer with the record and the exception, commits the record's offset, and processing moves on to the next record.

The default back-off is FixedBackOff(0, 9): no wait and nine retries, so ten deliveries in all. The default recoverer only logs the failure at ERROR level. Retries happen inside the consumer, in memory, so they block the partition: later records wait until the failed one is retried or given up. The dead letter topics page covers sending failed records to another topic, and non-blocking retries with @RetryableTopic.

DefaultErrorHandler settings
SettingDefaultWhat it controls
BackOffFixedBackOff(0, 9)How often and how long to retry
ConsumerRecordRecovererLog at ERRORWhat to do with a record after the last retry
Not-retryable exceptionsDeserialization and conversion errors, ClassCastException, NoSuchMethodExceptionExceptions that go to the recoverer at once
RetryListenerNoneA callback for each failed delivery, for logging or metrics
commitRecoveredCommit after recoveryWhether the recovered record's offset is committed

The programs are Spring Boot 4.1 applications with spring-boot-starter-kafka, which brings Spring for Apache Kafka 4.1. Each starts a single Kafka broker inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test, in the startBroker method at the end. Logging is off, so that the error handler's own log lines with timestamps do not hide the program output. To use a custom error handler, a program declares a CommonErrorHandler bean, and Spring Boot passes it to its listener container factory.

The default: ten deliveries, then skip

With no error handler configured, the payment listener below fails on the value bad and succeeds on good, which is sent right after it to the same partition:

Java
package demo.kafka.defaults;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class DefaultRetries {

    static final AtomicInteger BAD_ATTEMPTS = new AtomicInteger();
    static final CountDownLatch GOOD_DONE = new CountDownLatch(1);

    @Bean
    NewTopic payments() {
        return TopicBuilder.name("payments").partitions(1).replicas(1).build();
    }

    @Component
    static class PaymentListener {
        // no error handler configured: Spring Kafka's DefaultErrorHandler is used
        @KafkaListener(id = "payments", topics = "payments", groupId = "payments")
        void on(String payment) {
            if (payment.equals("bad")) {
                System.out.println("  attempt " + BAD_ATTEMPTS.incrementAndGet()
                        + " for 'bad': throwing");
                throw new IllegalStateException("bank timeout");
            }
            System.out.println("  processed '" + payment + "'");
            GOOD_DONE.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(DefaultRetries.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("payments", "bad").get();
            template.send("payments", "good").get();
            GOOD_DONE.await(60, TimeUnit.SECONDS);
            System.out.println("'bad' was delivered " + BAD_ATTEMPTS.get()
                    + " times, then skipped; 'good' was processed after it");
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
attempt 1 for 'bad': throwing
  attempt 2 for 'bad': throwing
  attempt 3 for 'bad': throwing
  attempt 4 for 'bad': throwing
  attempt 5 for 'bad': throwing
  attempt 6 for 'bad': throwing
  attempt 7 for 'bad': throwing
  attempt 8 for 'bad': throwing
  attempt 9 for 'bad': throwing
  attempt 10 for 'bad': throwing
  processed 'good'
'bad' was delivered 10 times, then skipped; 'good' was processed after it
  • The record bad was delivered 10 times, the first delivery plus nine retries of FixedBackOff(0, 9), with no pause in between.
  • After the tenth failure, the default recoverer logged the record and its offset was committed. good was processed after it.
  • Nothing else happened to bad: it is gone from this consumer group's point of view, and only an ERROR log line remains.

Ten immediate retries rarely help: a bank timeout does not go away in a few milliseconds. And skipping the record after logging it is data loss in most systems. The rest of this page changes both.

Back-off and a recoverer

An invoice listener depends on a PDF service that is down. The error handler below waits longer between attempts with ExponentialBackOffWithMaxRetries, reports each failed delivery to a retry listener, and passes the record to a recoverer after the last retry:

Java
package demo.kafka.backoff;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.support.ExponentialBackOffWithMaxRetries;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class BackOffAndRecoverer {

    static final CountDownLatch DONE = new CountDownLatch(1);
    static volatile long previous;

    // time since the previous attempt, rounded to 100 ms
    static String gap() {
        long now = System.nanoTime();
        String text = previous == 0 ? "first" : "+" + Math.round((now - previous)
                / 1000000 / 100.0) * 100 + " ms";
        previous = now;
        return text;
    }

    @Bean
    NewTopic invoices() {
        return TopicBuilder.name("invoices").partitions(1).replicas(1).build();
    }

    // Spring Boot passes a CommonErrorHandler bean to its listener container factory
    @Bean
    CommonErrorHandler errorHandler() {
        ExponentialBackOffWithMaxRetries backOff = new ExponentialBackOffWithMaxRetries(3);
        backOff.setInitialInterval(500);
        backOff.setMultiplier(2.0);
        DefaultErrorHandler handler = new DefaultErrorHandler((record, exception) -> {
            System.out.println("  " + gap() + ": recoverer gives up on '"
                    + record.value() + "' (offset " + record.offset() + "): "
                    + exception.getCause().getMessage());
            DONE.countDown();
        }, backOff);
        handler.setRetryListeners((record, ex, attempt) -> System.out.println(
                "  retry listener: delivery " + attempt + " failed"));
        return handler;
    }

    @Component
    static class InvoiceListener {
        @KafkaListener(id = "invoices", topics = "invoices", groupId = "invoices")
        void on(String invoice) {
            System.out.println("  " + gap() + ": processing '" + invoice + "'");
            throw new IllegalStateException("PDF service unavailable");
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(BackOffAndRecoverer.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("invoices", "invoice-42").get();
            System.out.println("recovered: " + DONE.await(60, TimeUnit.SECONDS));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
first: processing 'invoice-42'
  retry listener: delivery 1 failed
  +500 ms: processing 'invoice-42'
  retry listener: delivery 2 failed
  +1000 ms: processing 'invoice-42'
  retry listener: delivery 3 failed
  +2000 ms: processing 'invoice-42'
  retry listener: delivery 4 failed
  +0 ms: recoverer gives up on 'invoice-42' (offset 0): PDF service unavailable
recovered: true
  • The record was processed four times: the first delivery and three retries.
  • The gaps between deliveries were 500, 1000 and 2000 ms: the initial interval of 500 ms, doubled each time by the multiplier of 2.
  • The retry listener was called after every failed delivery, numbered 1 to 4.
  • Right after the fourth failure, the recoverer received the record, with its offset, and the exception. The listener's exception arrives wrapped in a ListenerExecutionFailedException, which is why the program prints its cause.

In a real application, the recoverer stores the record somewhere it can be found again: a database table, or a dead letter topic with DeadLetterPublishingRecoverer. The consumer thread sleeps through each back-off interval before its next poll, so keep every interval well below max.poll.interval.ms, five minutes by default, or the broker will remove the consumer from the group. ExponentialBackOffWithMaxRetries caps single intervals at 30 seconds unless you change maxInterval. Every record behind the failed one waits for the whole sequence.

Exceptions that should not be retried

Some failures can never succeed on retry. An email address without an @ stays invalid however often it is processed. The handler below retries three times with 100 ms between attempts, but classifies IllegalArgumentException as not retryable:

Java
package demo.kafka.classify;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class RetryableOrNot {

    static final Map<String, AtomicInteger> ATTEMPTS = new ConcurrentHashMap<>();
    static final CountDownLatch RECOVERED = new CountDownLatch(2);

    @Bean
    NewTopic signups() {
        return TopicBuilder.name("signups").partitions(1).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler() {
        DefaultErrorHandler handler = new DefaultErrorHandler(
                (record, e) -> RECOVERED.countDown(), new FixedBackOff(100, 3));
        // retrying cannot fix bad input: skip it on the first failure
        handler.addNotRetryableExceptions(IllegalArgumentException.class);
        return handler;
    }

    @Component
    static class SignupListener {
        @KafkaListener(id = "signups", topics = "signups", groupId = "signups")
        void on(String email) {
            ATTEMPTS.computeIfAbsent(email, k -> new AtomicInteger()).incrementAndGet();
            if (!email.contains("@")) {
                throw new IllegalArgumentException("not an email address: " + email);
            }
            throw new IllegalStateException("mail server busy");
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(RetryableOrNot.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("signups", "no-at-sign").get();
            template.send("signups", "ann@example.com").get();
            RECOVERED.await(60, TimeUnit.SECONDS);
            System.out.println("IllegalArgumentException, attempts: "
                    + ATTEMPTS.get("no-at-sign"));
            System.out.println("IllegalStateException, attempts   : "
                    + ATTEMPTS.get("ann@example.com"));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
IllegalArgumentException, attempts: 1
IllegalStateException, attempts   : 4
  • The record that threw IllegalArgumentException was attempted once, then passed straight to the recoverer.
  • The record that threw IllegalStateException, a temporary problem, was attempted 4 times: the first delivery and the three retries of FixedBackOff(100, 3).

DefaultErrorHandler already treats deserialization and conversion errors, ClassCastException, NoSuchMethodException and MethodArgumentResolutionException as not retryable. Add your own validation exceptions with addNotRetryableExceptions, or turn the logic round with defaultFalse() and addRetryableExceptions, so that only known temporary errors are retried.

Poison pills: values that cannot be deserialized

A poison pill is a record whose bytes cannot be turned into the expected type, such as a text value on a JSON topic. If the Kafka deserializer itself throws, the error happens inside poll(), before any listener code runs. The listener below is protected with ErrorHandlingDeserializer, which wraps the real JSON deserializer and catches its failures:

Java
package demo.kafka.poison;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class PoisonPill {

    record Reading(String sensor, double celsius) { }

    static final List<String> SAFE = new CopyOnWriteArrayList<>();
    static final List<String> SKIPPED = new CopyOnWriteArrayList<>();

    @Bean
    NewTopic readings() {
        return TopicBuilder.name("readings").partitions(1).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler() {
        return new DefaultErrorHandler((record, e) -> SKIPPED.add("offset " + record.offset()
                + ": " + e.getCause().getClass().getSimpleName()), new FixedBackOff(0, 2));
    }

    @Component
    static class ReadingListener {
        // the JSON deserializer is wrapped, so a bad value reaches the error handler
        @KafkaListener(id = "safe", topics = "readings", groupId = "safe", properties = {
                "value.deserializer=org.springframework.kafka.support.serializer"
                        + ".ErrorHandlingDeserializer",
                "spring.deserializer.value.delegate.class=org.springframework.kafka.support"
                        + ".serializer.JacksonJsonDeserializer",
                "spring.json.value.default.type=demo.kafka.poison.PoisonPill$Reading"})
        void safe(Reading reading) {
            SAFE.add(reading.sensor() + "=" + reading.celsius());
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(PoisonPill.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("readings", "{\"sensor\":\"s1\",\"celsius\":21.5}").get();
            template.send("readings", "not json at all").get();
            template.send("readings", "{\"sensor\":\"s2\",\"celsius\":19.0}").get();
            Thread.sleep(5000);
            System.out.println("processed: " + SAFE);
            System.out.println("skipped  : " + SKIPPED);
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
processed: [s1=21.5, s2=19.0]
skipped  : [offset 1: DeserializationException]
  • The two valid readings, s1 and s2, were deserialized into Reading records and processed.
  • The text not json at all at offset 1 failed inside the delegate JacksonJsonDeserializer. ErrorHandlingDeserializer caught the exception and passed the record on with a DeserializationException instead of a value.
  • The container raised that exception before calling the listener. DeserializationException is not retryable, so the recoverer received the record at once, although the back-off allowed two retries, and s2 was processed after it.

The deserializers are set per listener with the annotation's properties attribute here; in an application they usually go in spring.kafka.consumer.value-deserializer and spring.kafka.consumer.properties.spring.deserializer.value.delegate.class. The DeserializationException keeps the original bytes, so a DeadLetterPublishingRecoverer can publish them unchanged for later inspection. Converting in the listener instead, with a message converter as on the @KafkaListener page, avoids the problem in the deserializer altogether.

Retries block the consumer

Blocking retries keep records in order, which is often exactly what is needed. The cost is that nothing else moves while a record is being retried. Here shipment A fails twice before it succeeds, with one second between attempts. B is behind A in partition 0, and C is sent to partition 1 right after A's first failure:

Java
package demo.kafka.blocking;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class BlockingRetries {

    static final CountDownLatch DONE = new CountDownLatch(3);
    static final CountDownLatch FIRST_FAILURE = new CountDownLatch(1);
    static final AtomicInteger SLOW_ATTEMPTS = new AtomicInteger();
    static volatile long start;

    static long elapsed() {
        return Math.round((System.nanoTime() - start) / 1000000 / 100.0) * 100;
    }

    @Bean
    NewTopic shipments() {
        return TopicBuilder.name("shipments").partitions(2).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler() {
        return new DefaultErrorHandler(new FixedBackOff(1000, 4));
    }

    @Component
    static class ShipmentListener {
        @KafkaListener(id = "shipments", topics = "shipments", groupId = "shipments",
                autoStartup = "false")
        void on(String shipment) {
            if (shipment.startsWith("A") && SLOW_ATTEMPTS.incrementAndGet() < 3) {
                if (start == 0) {
                    start = System.nanoTime();
                }
                System.out.println("  " + elapsed() + " ms: " + shipment + " fails");
                FIRST_FAILURE.countDown();
                throw new IllegalStateException("carrier API down");
            }
            System.out.println("  " + elapsed() + " ms: " + shipment + " processed");
            DONE.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(BlockingRetries.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            template.send("shipments", 0, null, "A (partition 0)").get();
            template.send("shipments", 0, null, "B (partition 0)").get();
            context.getBean(KafkaListenerEndpointRegistry.class)
                    .getListenerContainer("shipments").start();
            FIRST_FAILURE.await(30, TimeUnit.SECONDS);
            template.send("shipments", 1, null, "C (partition 1)").get();
            System.out.println("  " + elapsed() + " ms: C sent to partition 1");
            DONE.await(60, TimeUnit.SECONDS);
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
0 ms: A (partition 0) fails
  0 ms: C sent to partition 1
  1000 ms: C (partition 1) processed
  1100 ms: A (partition 0) fails
  2100 ms: A (partition 0) processed
  2100 ms: B (partition 0) processed
  • A failed at 0 ms and at about 1000 ms, and succeeded at about 2000 ms on its third delivery.
  • B, in the same partition, was processed only after A succeeded. This is the order guarantee: B never overtook A.
  • C was sent at 0 ms to another partition, but was processed only at about 1000 ms. The listener has one consumer thread for both partitions, and that thread was waiting out A's back-off.

Everything a consumer thread owns waits during a back-off. With concurrency set to the number of partitions, each partition has its own thread and only the failing partition stalls. When ordering does not matter and failures may last minutes, non-blocking retries through retry topics avoid the stall, at the cost of ordering; they are covered on the dead letter topics page.

Failures in batch listeners

A batch listener receives many records at once, so the error handler needs to know which one failed. Throwing BatchListenerFailedException with the index of the failed record tells it. This loader saves five rows in one batch, and row 3 violates a constraint the first time:

Java
package demo.kafka.batchfail;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.BatchListenerFailedException;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class BatchFailures {

    static final CountDownLatch DONE = new CountDownLatch(1);
    static final AtomicBoolean FAILED_ONCE = new AtomicBoolean();

    @Bean
    NewTopic rows() {
        return TopicBuilder.name("rows").partitions(1).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler() {
        return new DefaultErrorHandler(new FixedBackOff(0, 2));
    }

    @Component
    static class RowLoader {
        @KafkaListener(id = "rows", topics = "rows", groupId = "loader", batch = "true",
                autoStartup = "false")
        void on(List<ConsumerRecord<String, String>> batch) {
            System.out.println("  batch: " + batch.stream().map(ConsumerRecord::value).toList());
            for (int i = 0; i < batch.size(); i++) {
                boolean firstTime = !FAILED_ONCE.get();
                if (batch.get(i).value().equals("row-3") && firstTime) {
                    FAILED_ONCE.set(true);
                    System.out.println("  row-3 fails; rows before it are saved");
                    throw new BatchListenerFailedException("constraint violated", i);
                }
            }
            if (batch.getLast().value().equals("row-5")) {
                DONE.countDown();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(BatchFailures.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            for (int i = 1; i <= 5; i++) {
                template.send("rows", "row-" + i).get();
            }
            context.getBean(KafkaListenerEndpointRegistry.class).getListenerContainer("rows")
                    .start();
            System.out.println("all rows loaded: " + DONE.await(60, TimeUnit.SECONDS));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
batch: [row-1, row-2, row-3, row-4, row-5]
  row-3 fails; rows before it are saved
  batch: [row-3, row-4, row-5]
all rows loaded: true
  • The first batch held all five rows. Row 3, at index 2, failed, and the listener threw BatchListenerFailedException with that index.
  • The error handler committed the offsets of rows 1 and 2, which had succeeded, and seeked back to row 3.
  • The redelivered batch started at row 3 and held rows 3, 4 and 5. This time row 3 succeeded, and the whole load finished.

If a batch listener throws any other exception, the handler cannot tell which records succeeded, so it retries the whole batch, and after the retries the recoverer receives every record of the batch. Rows 1 and 2 would then be saved twice, so always throw BatchListenerFailedException from batch listeners that have partial side effects.

Choosing an error strategy

Failure types and the handling that fits them
FailureHandling
A short outage of a downstream serviceDefaultErrorHandler with a back-off of seconds
Outages that can last minutes, where order does not matterNon-blocking retries with @RetryableTopic
Invalid data, validation errorsaddNotRetryableExceptions, then a recoverer
Values that cannot be deserializedErrorHandlingDeserializer around the real deserializer
Records that must not be lost after the last retryDeadLetterPublishingRecoverer or a recoverer that stores them
Batch listeners with side effectsBatchListenerFailedException with the failed index
Strict per-key orderingBlocking retries, with enough concurrency that one stalled partition does not stop the others

Whatever the strategy, count failed deliveries and recovered records, for example from a retry listener, so that a failing listener shows up on a dashboard rather than only in the logs; the Kafka monitoring page shows how. Producing and consuming basics are on the KafkaTemplate and @KafkaListener pages.