Sub topic 11
Handling listener errors with retries and back-off
This chapter assumes you can run a Spring Boot application with @KafkaListener, you know what a consumer group and an offset are, and you have the configuration from the setup chapter. Here you will decide what happens when a listener method throws an exception.
What happens when a listener throws
A listener container polls records from Kafka and passes each one to your method. If the method throws, the container needs a policy. Without one, the same record would be redelivered forever and block its partition, because the offset never moves past it.
Spring for Apache Kafka delegates this decision to a CommonErrorHandler. Spring Boot's default is DefaultErrorHandler. It retries the failed record a limited number of times, and then logs it and moves on. Retries are controlled by a back-off policy, which defines how many attempts to make and how long to wait between them.
Retrying with a fixed back-off
Declare a DefaultErrorHandler bean. Spring Boot applies a single CommonErrorHandler bean to its auto-configured listener containers.
package com.example.orders;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.FixedBackOff;
@Configuration
public class KafkaRetryConfig {
@Bean
public DefaultErrorHandler errorHandler() {
// Wait 1 second between attempts, retry 3 times after the first failure.
return new DefaultErrorHandler(new FixedBackOff(1000L, 3L));
}
}FixedBackOff(1000L, 3L) means 1000 ms between attempts and a maximum of 3 retries. The listener therefore runs up to four times in total: the first delivery plus three retries. When the retries are used up, the default recoverer logs the record at ERROR level and the container commits its offset, so the record is skipped.
How the retry works internally
The error handler does not call your method again in a loop. It seeks the consumer back to the failed record's offset, and the next poll fetches the same record again. The wait between attempts happens inside the container thread.
Two consequences follow from this design:
- Retries block the partition. Records behind the failing one on the same partition wait until it succeeds or is recovered.
- Long back-offs can exceed
max.poll.interval.ms. If the total wait is longer than this consumer setting (5 minutes by default), the broker considers the consumer dead and triggers a rebalance. Keep total back-off time well below it.
Growing delays with exponential back-off
For failures that clear up on their own, such as a database that is briefly unavailable, waiting longer after each attempt gives the dependency time to recover.
package com.example.orders;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.ExponentialBackOffWithMaxRetries;
@Configuration
public class KafkaExponentialRetryConfig {
@Bean
public DefaultErrorHandler errorHandler() {
ExponentialBackOffWithMaxRetries backOff = new ExponentialBackOffWithMaxRetries(4);
backOff.setInitialInterval(500L);
backOff.setMultiplier(2.0);
backOff.setMaxInterval(5000L);
return new DefaultErrorHandler(backOff);
}
}This waits 500 ms, 1 s, 2 s and 4 s, giving four retries. If you keep this class and the previous one in the same project, only one errorHandler bean should be active, so remove or rename one of them.
Exceptions that should not be retried
Some failures never succeed on retry. A record that cannot be deserialized or that fails validation will fail the same way every time. DefaultErrorHandler already treats several exception types as not retryable, including DeserializationException and MessageConversionException, and skips straight to recovery. You can add your own:
package com.example.orders;
import org.springframework.kafka.listener.DefaultErrorHandler;
public class RetryClassification {
public static void configure(DefaultErrorHandler handler) {
handler.addNotRetryableExceptions(IllegalArgumentException.class);
}
}Throw a retryable exception, such as a timeout, only for transient problems. Use a non-retryable one for bad data.
Common mistakes
- Swallowing the exception in a
try/catchinside the listener. The container sees a normal return, commits the offset, and the record is lost without any retry. - Using a long back-off on a high-volume partition. Every record behind the failing one is delayed.
- Assuming a skipped record is stored somewhere. With the default recoverer it is only logged. The next chapter shows how to keep failed records in a dead-letter topic.
Exercise
A listener uses new DefaultErrorHandler(new FixedBackOff(2000L, 4L)). A record always causes an exception. How many times is the listener method invoked for that record, how long does the container wait in total, and what happens to the record afterwards?
Show answer
The method runs 5 times: the first delivery plus 4 retries. The container waits about 8 seconds in total (4 retries at 2 seconds each). After the last failure the default recoverer logs the record at ERROR level and the offset is committed, so the record is skipped and the partition moves on.
Exercise
Why can a listener that catches all exceptions with a try/catch and only logs them lose messages, even though an error handler is configured?
Show answer
The error handler is only called when an exception propagates out of the listener method. If the method catches the exception and returns normally, the container treats the record as processed and commits its offset, so no retry or recovery happens.