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 @KafkaListenerCommonErrorHandlerDefaultErrorHandler
- 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.
- It waits according to a
, then lets the container poll and redeliver the record.BackOff - 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)@RetryableTopic
| Setting | Default | What it controls |
|---|---|---|
BackOff | FixedBackOff(0, 9) | How often and how long to retry |
ConsumerRecordRecoverer | Log at ERROR | What to do with a record after the last retry |
| Not-retryable exceptions | Deserialization and conversion errors, ClassCastExceptionNoSuchMethodException | Exceptions that go to the recoverer at once |
RetryListener | None | A callback for each failed delivery, for logging or metrics |
commitRecovered | Commit after recovery | Whether the recovered record's offset is committed |
The programs are Spring Boot 4.1 applications with spring-boot-starter-kafkaEmbeddedKafkaKraftBrokerspring-kafka-teststartBrokerCommonErrorHandler
The default: ten deliveries, then skip
With no error handler configured, the payment listener below fails on the value badgood
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);
}
}
}
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
was delivered 10 times, the first delivery plus nine retries ofbad , with no pause in between.FixedBackOff(0, 9) - After the tenth failure, the default recoverer logged the record and its offset was committed.
was processed after it.good - Nothing else happened to
: it is gone from this consumer group's point of view, and only an ERROR log line remains.bad
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
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);
}
}
}
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
, which is why the program prints its cause.ListenerExecutionFailedException
In a real application, the recoverer stores the record somewhere it can be found again: a database table, or a dead letter topic with DeadLetterPublishingRecoverermax.poll.interval.msExponentialBackOffWithMaxRetriesmaxInterval
Exceptions that should not be retried
Some failures can never succeed on retry. An email address without an @IllegalArgumentException
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);
}
}
}
IllegalArgumentException, attempts: 1
IllegalStateException, attempts : 4
- The record that threw
was attempted once, then passed straight to the recoverer.IllegalArgumentException - The record that threw
, a temporary problem, was attempted 4 times: the first delivery and the three retries ofIllegalStateException .FixedBackOff(100, 3)
DefaultErrorHandlerClassCastExceptionNoSuchMethodExceptionMethodArgumentResolutionExceptionaddNotRetryableExceptionsdefaultFalse()addRetryableExceptions
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()ErrorHandlingDeserializer
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);
}
}
}
processed: [s1=21.5, s2=19.0]
skipped : [offset 1: DeserializationException]
- The two valid readings, s1 and s2, were deserialized into
records and processed.Reading - The text
at offset 1 failed inside the delegatenot json at all .JacksonJsonDeserializer caught the exception and passed the record on with aErrorHandlingDeserializer instead of a value.DeserializationException - The container raised that exception before calling the listener.
is not retryable, so the recoverer received the record at once, although the back-off allowed two retries, and s2 was processed after it.DeserializationException
The deserializers are set per listener with the annotation's propertiesspring.kafka.consumer.value-deserializerspring.kafka.consumer.properties.spring.deserializer.value.delegate.classDeserializationExceptionDeadLetterPublishingRecoverer
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:
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);
}
}
}
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
Failures in batch listeners
A batch listener receives many records at once, so the error handler needs to know which one failed. Throwing BatchListenerFailedException
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);
}
}
}
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
with that index.BatchListenerFailedException - 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
Choosing an error strategy
| Failure | Handling |
|---|---|
| A short outage of a downstream service | DefaultErrorHandler |
| Outages that can last minutes, where order does not matter | Non-blocking retries with @RetryableTopic |
| Invalid data, validation errors | addNotRetryableExceptions |
| Values that cannot be deserialized | ErrorHandlingDeserializer |
| Records that must not be lost after the last retry | DeadLetterPublishingRecoverer |
| Batch listeners with side effects | BatchListenerFailedException |
| Strict per-key ordering | Blocking 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