Kafka Retry Mechanism
A consumer that calls a database, a payment gateway or another service will sometimes fail for reasons that fix themselves: a timeout, a lock, a short outage. Retrying is the right answer to those failures, but how you retry decides whether the rest of the partition waits, whether ordering is preserved, and whether a rebalance happens in the middle.
Kafka itself has no consumer-side retry feature; consumers retry by re-reading records. This tutorial compares the two strategies you can build, blocking retries and non-blocking retry topics, and shows both in Spring for Apache Kafka 4.2. Producer-side retries are covered in Kafka Producer Retries.
1. What Is a Retry Mechanism in Kafka?
A consumer retry mechanism processes a failed record again after a delay, a limited number of times, and then sends it to a dead-letter topic if it still fails.
| Blocking retries | Non-blocking retries | |
|---|---|---|
| How | Seek back and redeliver the same record on the same consumer | Publish the failed record to a retry topic and continue |
| Other records in the partition | Wait | Keep flowing |
| Ordering per key | Preserved | Not preserved for retried records |
| Suitable delays | Short (milliseconds to seconds) | Seconds to hours |
| Spring Kafka | DefaultErrorHandler with a BackOff | @RetryableTopic |
2. How Non-Blocking Retries Work
With @RetryableTopic, Spring creates the retry topics and a dead-letter topic, plus a listener container for each. When the listener throws, the record is published to the next retry topic with a header that holds its due time. The retry topic's consumer pauses its partition until that time, then calls the same listener method. Pausing, rather than sleeping, keeps the consumer within max.poll.interval.ms.
3. Blocking Retries with DefaultErrorHandler
For short delays, use the container's error handler with an exponential backoff. The record is redelivered on the same thread and ordering is kept:
package com.javabytechie.kafka;
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 BlockingRetryConfig {
@Bean
DefaultErrorHandler blockingRetries() {
var backOff = new ExponentialBackOffWithMaxRetries(4); // 4 retries after the first attempt
backOff.setInitialInterval(200);
backOff.setMultiplier(2.0); // 200, 400, 800, 1600 ms
backOff.setMaxInterval(2000);
return new DefaultErrorHandler(backOff);
}
}
Keep the total delay well below max.poll.interval.ms, because the consumer cannot poll while it waits.
4. Non-Blocking Example with @RetryableTopic
An inventory service updates stock in a warehouse system that is sometimes unavailable. Records for SKU-1 always fail; records for other SKUs succeed.
package com.javabytechie.kafka;
import org.springframework.kafka.annotation.BackOff;
import org.springframework.kafka.annotation.DltHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.annotation.RetryableTopic;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
@Component
public class StockUpdateListener {
private final long start = System.currentTimeMillis();
@RetryableTopic(attempts = "3", backOff = @BackOff(delay = 1000, multiplier = 2.0),
exclude = IllegalArgumentException.class)
@KafkaListener(topics = "stock-updates", groupId = "inventory")
public void onUpdate(String sku, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
System.out.printf("%4.1fs %s on %s%n", seconds(), sku, topic);
if (sku.equals("SKU-1")) {
throw new IllegalStateException("Warehouse API timeout");
}
}
@DltHandler
public void onDeadLetter(String sku, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
System.out.printf("%4.1fs %s parked in %s%n", seconds(), sku, topic);
}
private double seconds() {
return (System.currentTimeMillis() - start) / 1000.0;
}
}
package com.javabytechie.kafka;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.EnableKafkaRetryTopic;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@SpringBootApplication
@EnableKafkaRetryTopic
public class StockApplication {
public static void main(String[] args) {
SpringApplication.run(StockApplication.class, args);
}
@Bean
TaskScheduler retryTopicScheduler() { // required by the retry topic back-off manager
return new ThreadPoolTaskScheduler();
}
@Bean
ApplicationRunner sendUpdates(KafkaTemplate<String, String> template) {
return args -> {
template.send("stock-updates", "SKU-1");
template.send("stock-updates", "SKU-2");
template.send("stock-updates", "SKU-3");
};
}
}
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
auto-offset-reset: earliest
Retry topics need a TaskScheduler bean to resume paused partitions; without one, startup fails with "Either a RetryTopicSchedulerWrapper or TaskScheduler bean is required".
Output (Spring Boot 4.2.0, Spring for Apache Kafka 4.2.0, local Kafka 4.4 broker; times are seconds since the listener bean was created):
0.8s SKU-1 on stock-updates
1.4s SKU-2 on stock-updates
1.4s SKU-3 on stock-updates
1.9s SKU-1 on stock-updates-retry-1000
3.9s SKU-1 on stock-updates-retry-2000
4.4s SKU-1 parked in stock-updates-dlt
SKU-1 fails on the main topic, but SKU-2 and SKU-3 are processed straight away: the failure did not block them. SKU-1 is retried about one second later on stock-updates-retry-1000 and two seconds after that on stock-updates-retry-2000; with an exponential backoff, the retry topic names end with their delay in milliseconds. After the third attempt it goes to stock-updates-dlt and the @DltHandler method runs. Exact times vary slightly between runs.
5. Choosing Retry Settings
| Setting | Where | Guidance |
|---|---|---|
attempts | @RetryableTopic | Total attempts including the first; default 3 |
backOff | @RetryableTopic | delay, multiplier, maxDelay; default 1 second fixed |
include / exclude | @RetryableTopic | Retry only transient exceptions |
sameIntervalTopicReuseStrategy | @RetryableTopic | With fixed delays, one retry topic is reused for all attempts |
BackOff | DefaultErrorHandler | FixedBackOff or ExponentialBackOffWithMaxRetries for blocking retries |
max.poll.interval.ms | consumer | Must exceed the longest blocking retry sequence |
6. Common Mistakes
- Using retry topics when ordering matters: a retried record is processed after newer records with the same key.
- Sleeping in the listener with
Thread.sleep()to wait before a retry, which blocks the consumer and causes rebalances. - Retrying validation errors: a record with bad data fails on every attempt; exclude such exceptions.
- Unbounded retries: always end in a dead-letter topic and monitor it.
- Non-idempotent processing: a failure after a partial write repeats that write on every attempt.
7. Best Practices
- Blocking retries for short, ordered work, non-blocking retry topics for long waits and high throughput.
- Use exponential backoff with a maximum so that a struggling dependency is not overloaded.
- Make handlers idempotent, for example with an idempotency key stored next to the result.
- Add a circuit breaker in front of fragile dependencies, so that a full outage pauses consumption instead of filling the DLT.
- Plan a replay path from the DLT back to the main topic after fixes.
8. Conclusion
Consumer retries in Kafka are built from re-reading records. Blocking retries with DefaultErrorHandler keep ordering but stall the partition; non-blocking retries with @RetryableTopic keep the main flow moving at the cost of ordering. Both should use backoff, retry only transient errors and end in a dead-letter topic. See Exception Handling in Apache Kafka for classifying errors.
9. References
Kafka Retry Mechanism Interview Questions and Answers
Common interview questions on Kafka Retry Mechanism, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Does Kafka have built-in consumer retries?
Answer: No. The consumer client only reads records and commits offsets. Retrying means reading the same record again, either by seeking back (blocking) or by republishing it to another topic (non-blocking). Frameworks such as Spring for Apache Kafka implement these patterns for you.
Intermediate questions
Q. When should you prefer blocking retries over retry topics?
Answer: When the order of records per key matters and the expected delays are short, for example account balance updates. Blocking retries keep the failed record at its position, so later records of the same partition wait. Retry topics would let later records overtake it.
Q. How does a retry topic consumer wait without breaking max.poll.interval.ms?
Answer: It does not sleep. When it reads a record whose due time has not arrived, it pauses the partition and seeks back to the record. The consumer keeps polling, which keeps it in the group, and resumes the partition when the time has come.
Tricky and scenario questions
Q. What happens to ordering when a record goes to a retry topic?
Answer: The record leaves its original partition, so newer records for the same key are processed first. If the business logic depends on order, for example "created" before "updated", either use blocking retries or detect out-of-order events with a version number and handle them.
Q. How do you avoid filling the DLT during a complete outage of a dependency?
Answer: Retries assume short failures. During a long outage, every record runs through all attempts and ends in the DLT. Add a circuit breaker; when it opens, stop the listener container or pause its partitions, and resume when the dependency is healthy, so records wait in the topic instead of being dead-lettered.