Sub topic 11
Handling listener errors with retries and back-off
This chapter assumes you can write a @KafkaListener and understand offsets and consumer groups from the earlier chapters. It covers what happens when a listener method throws, how to retry with a delay between attempts, and which failures should never be retried. Dead-letter topics, which catch records that still fail, are the next chapter.
What happens when a listener throws
Kafka has no per-message acknowledgment or negative acknowledgment. A consumer reads a batch of records with poll(), and its position in each partition only moves forward when offsets are committed. A failed record therefore has to be handled in the client.
Spring for Apache Kafka routes every exception thrown by your listener method to a CommonErrorHandler. Spring Boot's default is DefaultErrorHandler, which does the following:
- It catches the exception from the failed record.
- It seeks the consumer back to that record's offset. Records after it in the same poll are also discarded and fetched again.
- It waits for the back-off interval.
- The next
poll()delivers the failed record again. - When the back-off is exhausted, it calls a recoverer and moves on.
The default configuration is FixedBackOff with no delay and 9 retries, so a record is delivered 10 times in total. The default recoverer only logs the record at ERROR level. After that the offset is committed and the record is skipped, so the message is lost unless you configure something better.
Configuring retries and back-off
Declare a DefaultErrorHandler bean. Spring Boot's auto-configured listener container factory picks up a single CommonErrorHandler bean automatically.
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 ListenerRetryConfig {
@Bean
public DefaultErrorHandler errorHandler() {
// 3 retries, 1 second apart: 4 deliveries in total
return new DefaultErrorHandler(new FixedBackOff(1000L, 3L));
}
}FixedBackOff(interval, maxAttempts) counts retries, not deliveries. A value of 3L means the initial delivery plus three retries. Use FixedBackOff.UNLIMITED_ATTEMPTS to retry forever, which is rarely wise because the partition is blocked the whole time.
Choosing a back-off policy
| Policy | Behavior | Typical use |
|---|---|---|
| `FixedBackOff` | Same delay between every attempt | Short transient glitches |
| `ExponentialBackOff` | Delay grows by a multiplier up to a cap | Downstream service recovering from an outage |
| `ExponentialBackOffWithMaxRetries` | Exponential, with a fixed retry count | Same, but with a bounded number of attempts |
Plain ExponentialBackOff stops by elapsed time (maxElapsedTime), not by attempt count, which makes the number of retries hard to predict. ExponentialBackOffWithMaxRetries is usually easier to reason about.
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.kafka.support.ExponentialBackOffWithMaxRetries;
@Configuration
public class ExponentialRetryConfig {
@Bean
public DefaultErrorHandler errorHandler() {
ExponentialBackOffWithMaxRetries backOff = new ExponentialBackOffWithMaxRetries(4);
backOff.setInitialInterval(500L);
backOff.setMultiplier(2.0);
backOff.setMaxInterval(8000L);
return new DefaultErrorHandler(backOff);
}
}This waits 0.5 s, 1 s, 2 s and 4 s before the four retries. Keep only one of the two configuration classes in a project, or errorHandler becomes a duplicate bean name.
Which exceptions are retried
Retrying only helps if the next attempt can succeed. A malformed payload fails identically every time. DefaultErrorHandler classifies exceptions, and for these types it skips the retries and goes straight to the recoverer:
DeserializationExceptionMessageConversionExceptionandConversionExceptionMethodArgumentResolutionExceptionNoSuchMethodExceptionClassCastException
You can adjust the classification for your own exception types:
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 ClassifiedRetryConfig {
@Bean
public DefaultErrorHandler errorHandler() {
DefaultErrorHandler handler = new DefaultErrorHandler(new FixedBackOff(1000L, 3L));
handler.addNotRetryableExceptions(IllegalArgumentException.class);
return handler;
}
}Use addRetryableExceptions(...) for the opposite case. Calling setClassifications(map, defaultValue) replaces the whole table, including the built-in entries, so prefer the add... methods unless you want a clean slate. Classification also checks the exception's cause chain, so a listener exception wrapping an IllegalArgumentException is matched.
Surviving poison messages at deserialization time
Deserialization happens inside the consumer, before your listener runs. A bad payload makes poll() itself throw, and the consumer cannot get past that offset, so it fails on the same record in an endless loop. The fix is ErrorHandlingDeserializer. It wraps the real deserializer, catches its exception, and passes the failure on to the listener container as a DeserializationException. The error handler can then treat it as non-retryable.
spring:
kafka:
consumer:
group-id: order-service
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.springframework.kafka.support.serializer.JsonDeserializer
spring.json.trusted.packages: com.example.orders
spring.json.value.default.type: com.example.orders.OrderEventWithout this wrapper, one invalid record can stall a partition indefinitely.
Observing retries
DefaultErrorHandler accepts RetryListener instances, which are called on each failed attempt and when recovery happens. This helps with metrics and with log lines that show the attempt number.
package com.example.orders;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.listener.RetryListener;
import org.springframework.util.backoff.FixedBackOff;
@Configuration
public class ObservedRetryConfig {
private static final Logger log = LoggerFactory.getLogger(ObservedRetryConfig.class);
@Bean
public DefaultErrorHandler errorHandler() {
DefaultErrorHandler handler = new DefaultErrorHandler(new FixedBackOff(1000L, 3L));
handler.setRetryListeners(new RetryListener() {
@Override
public void failedDelivery(ConsumerRecord<?, ?> record, Exception ex, int deliveryAttempt) {
log.warn("Attempt {} failed for {}-{}@{}: {}",
deliveryAttempt, record.topic(), record.partition(),
record.offset(), ex.getMessage());
}
});
return handler;
}
}Gotchas and failure modes
These are blocking retries. While a record is being retried, its whole partition waits. Ordering is preserved, but one bad record delays everything behind it, and consumer lag grows.
Other points to keep in mind:
- Redelivery means duplicates. If the listener performed a side effect (a database write, an HTTP call) before it threw, the retry repeats it. Make listeners idempotent, for example by deduplicating on
orderId. - Records before the failure in the same poll are not affected. They were already processed. Only the failed record and those after it are re-fetched.
- Batch listeners behave differently. If a listener takes a
List<OrderEvent>, the handler cannot tell which record failed. ThrowBatchListenerFailedExceptionwith the failed record's index so only the remainder is retried. Otherwise the whole batch is retried. - Retries stop being useful for long outages. If a downstream system is down for ten minutes, blocking retries either exhaust quickly or trigger a rebalance. Non-blocking retries with
@RetryableTopicmove failures to separate retry topics so the main partition keeps flowing. They give up strict ordering in exchange, so use them deliberately. - Exhausted retries lose data by default. With no recoverer configured, the record is logged and skipped. Pair the handler with a dead-letter recoverer in production, as shown in the next chapter.
Decision criteria
- Use a short
FixedBackOffwhen failures are brief and ordering matters. - Use
ExponentialBackOffWithMaxRetrieswhen a dependency may need time to recover, and keep the total belowmax.poll.interval.ms. - Mark validation and mapping errors as not retryable.
- Move to non-retryable handling plus dead-lettering, or
@RetryableTopic, when delays would block too much traffic.
Exercise
A listener throws a RuntimeException for every record. The error handler is new DefaultErrorHandler(new FixedBackOff(2000L, 4L)) with no custom recoverer. How many times is each record delivered to the listener, how long does the partition wait on that record, and what happens to the record afterwards?
Show answer
Each record is delivered 5 times: the initial delivery plus 4 retries. The partition waits about 8 seconds (4 back-off intervals of 2 seconds) on each record, plus processing time. After the last failure, the default recoverer logs the record at ERROR level, the offset is committed, and the record is skipped, so it is lost unless a dead-letter recoverer is configured.
Exercise
A producer publishes a record whose JSON cannot be parsed into OrderEvent. The consumer uses JsonDeserializer directly as its value deserializer, and the DefaultErrorHandler is configured with 3 retries. Why does the consumer keep failing on this record, and what change fixes it?
Show answer
The deserializer throws inside the consumer's poll(), before the listener container can hand a record to the error handler, so the retry and recovery logic never runs and the consumer cannot advance past that offset. Wrap the deserializers in ErrorHandlingDeserializer and set spring.deserializer.value.delegate.class to JsonDeserializer. The failure then arrives as a DeserializationException, which DefaultErrorHandler treats as not retryable and passes straight to the recoverer.