Spring Kafka DefaultErrorHandler and Backoff Policies
Master Spring Kafka's DefaultErrorHandler, configure exponential backoff, and implement DeadLetterPublishingRecoverer with rich diagnostic headers.
Spring for Apache Kafka provides an error-handling mechanism via DefaultErrorHandler. Introduced in Spring Kafka 2.8 and standardized in Spring Boot 3, it unifies record-level retry policies, exception classification, and dead-letter recovery into a single container-level interceptor.
Understanding how DefaultErrorHandler manages consumer partition state during backoff is essential for preventing partition rebalance storms while maintaining delivery guarantees.
01How DefaultErrorHandler works
When a @KafkaListener method throws an unhandled exception, the listener container catches it and passes control to DefaultErrorHandler. Rather than letting the exception crash the consumer container or silently discarding the record, DefaultErrorHandler initiates an in-memory retry loop:
- Exception evaluation: Checks whether the thrown exception is registered in the non-retryable list. If fatal, retries are skipped immediately.
- Backoff pause: If retryable, the error handler calculates the sleep duration based on the configured
BackOffstrategy. - Partition repositioning: The error handler seeks the consumer's partition offset back to the failing record's offset.
- Redelivery: When the backoff interval expires, the container invokes the listener method again with the exact same record.
- Recovery delegation: If the record fails repeatedly until the maximum attempt threshold is exhausted,
DefaultErrorHandlerhands the record to aConsumerRecordRecoverer(such asDeadLetterPublishingRecoverer). - Offset commit: Once the recoverer successfully forwards the record, the consumer marks the offset as committed and proceeds to the next record.
Loading the rest of the lesson…