Retry Mechanism in Apache Kafka
The retry mechanism in Apache Kafka is not one feature but a chain of decisions across the whole pipeline: the producer retries sends automatically, while on the consumer side Kafka only redelivers what was not committed. Everything else, such as how often a failing record is retried, how long to wait, and where a record goes when it cannot be processed, is designed by the application.
This tutorial looks at retries end to end with the plain Kafka clients: where retries happen, how to tell transient from permanent errors, how blocking retries and retry topics work internally, how to build a dead letter topic (DLT) and reprocess it, and how the same design maps to Spring for Apache Kafka. For a Spring-only walkthrough of DefaultErrorHandler and @RetryableTopic, see Kafka Retry and Backoff with Spring.
1. What Is the Retry Mechanism in Kafka?
A retry is a second attempt at an operation that failed for a reason that may go away: a broker restarting, a database deadlock, a downstream service returning HTTP 503. In Kafka there are two very different kinds of retry:
- Producer retries are built into the client. The
KafkaProducerresends a batch on retriable errors untildelivery.timeout.ms(2 minutes by default) runs out. With the idempotent producer, these retries cannot create duplicates. - Consumer retries are not built in. The broker does not track failures per record and has no redelivery counter. If your code throws and the offset is not committed, the record is simply read again from the same position. How many times, with what delay and what happens at the end is up to the application, or to a framework such as Spring for Apache Kafka.
2. Where Retries Happen in a Kafka Pipeline
A complete retry design usually has four layers. Each one handles failures that the previous layer could not resolve:
| Layer | Handles | Provided by | Blocks the partition? |
|---|---|---|---|
| Producer retries | Leader changes, timeouts, NOT_ENOUGH_REPLICAS | Kafka client (retries, delivery.timeout.ms) | No (the producer’s own batches only) |
| Blocking consumer retries | Short glitches: a deadlock, one failed HTTP call | Application or framework | Yes, briefly |
| Retry topics | Longer outages of a dependency | Application or framework | No, the record leaves the main topic |
| Dead letter topic | Permanent errors and exhausted retries | Application or framework | No |
Producer retries are covered in Kafka Producer Retries; the rest of this tutorial focuses on the consumer side, which is where most retry design decisions are made.
3. Transient vs Permanent Errors
Retrying only helps when the next attempt can succeed. Classifying errors first is what keeps a single bad record from wasting minutes of retries:
| Transient (retry) | Permanent (send to the DLT at once) |
|---|---|
| Database deadlock or connection timeout | Payload cannot be deserialized |
| Downstream HTTP 503, 429 or a socket timeout | Validation failure: missing field, negative amount |
| Optimistic locking conflict | Referenced entity does not exist and never will |
| Temporary authorisation token expiry | A bug in the handler, such as a NullPointerException on every attempt |
In code, this is usually a small classifier that maps exception types to “retryable” or not. Unknown exceptions are commonly treated as retryable a few times, so a new failure mode does not drop records straight into the DLT.
4. Blocking Retries in the Consumer
A blocking retry keeps the failed record at the head of its partition and tries again after a short pause. With the plain consumer, the clean way to do this is to seek back to the failed offset instead of looping inside the handler. The next poll() then returns the same record again, while the consumer keeps calling poll() and stays a healthy member of the group.
Map<TopicPartition, Integer> attempts = new HashMap<>();
while (running) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
for (TopicPartition tp : records.partitions()) {
for (ConsumerRecord<String, String> record : records.records(tp)) {
try {
handler.process(record);
attempts.remove(tp);
consumer.commitSync(Map.of(tp, new OffsetAndMetadata(record.offset() + 1)));
} catch (Exception e) {
int attempt = attempts.merge(tp, 1, Integer::sum);
if (classifier.isRetryable(e) && attempt < 3) {
consumer.seek(tp, record.offset()); // read the same record again
Thread.sleep(200L * attempt); // short backoff only
} else {
retryRouter.forward(record, e, 0); // first retry topic, or the DLT if permanent
attempts.remove(tp);
consumer.commitSync(Map.of(tp, new OffsetAndMetadata(record.offset() + 1)));
}
break; // skip the rest of this partition's batch; the next poll starts at the right offset
}
}
}
}
seek()plusbreakdiscards the records after the failed one from this poll. They are fetched again, in order, after the retry.- The backoff must stay short. The total time spent between two
poll()calls must stay well belowmax.poll.interval.ms(5 minutes by default), or the consumer is removed from the group and a rebalance starts. - Committing per record keeps the example simple; batching commits is faster in practice.
Blocking retries keep ordering intact, but every record behind the failed one waits. That is acceptable for a few hundred milliseconds, not for a five-minute outage.
5. Non-Blocking Retries with Retry Topics
For longer delays, the failed record is copied to a retry topic and its offset in the main topic is committed, so the main consumer moves on. A separate consumer reads the retry topic and processes each record only after its delay has passed. Several retry topics with growing delays give a backoff schedule; the last stage is the DLT.
5.1 Routing a failed record
The router keeps the original key, so a retried record still goes to a partition chosen by the same key, and adds headers that the later stages need:
package com.javabytechie.retry;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Headers;
public class RetryRouter {
record Stage(String topic, Duration delay) {}
private static final List<Stage> STAGES = List.of(
new Stage("orders-retry-10s", Duration.ofSeconds(10)),
new Stage("orders-retry-1m", Duration.ofMinutes(1)));
private static final String DLT = "orders-dlt";
private final KafkaProducer<String, String> producer; // idempotent, acks=all
private final ErrorClassifier classifier;
public RetryRouter(KafkaProducer<String, String> producer, ErrorClassifier classifier) {
this.producer = producer;
this.classifier = classifier;
}
/** stage = number of retry topics this record has already passed through */
public void forward(ConsumerRecord<String, String> failed, Exception error, int stage) throws Exception {
boolean retryable = classifier.isRetryable(error) && stage < STAGES.size();
String target = retryable ? STAGES.get(stage).topic() : DLT;
ProducerRecord<String, String> out = new ProducerRecord<>(target, failed.key(), failed.value());
Headers h = out.headers();
failed.headers().forEach(h::add); // keep eventId, tracing headers
h.remove("x-retry-stage").remove("x-not-before");
h.add("x-retry-stage", bytes(String.valueOf(stage + 1)));
h.add("x-original-topic", bytes(failed.topic()));
h.add("x-original-offset", bytes(failed.partition() + "@" + failed.offset()));
h.add("x-exception", bytes(error.getClass().getName() + ": " + error.getMessage()));
if (retryable) {
long notBefore = System.currentTimeMillis() + STAGES.get(stage).delay().toMillis();
h.add("x-not-before", bytes(String.valueOf(notBefore)));
}
producer.send(out).get(); // wait: the source offset may only be committed after this succeeds
}
private static byte[] bytes(String s) {
return s.getBytes(StandardCharsets.UTF_8);
}
}
Waiting for the send result before committing the source offset is what makes the hand-over safe: if the process dies in between, the record is processed again rather than lost. Because the main consumer forwards with stage 0 and each retry consumer forwards with its own stage number, a record moves through the stages in order and ends in the DLT.
5.2 Waiting for the due time without blocking the group
A retry consumer must not sleep for a minute inside the poll loop. Instead it pauses the partition, seeks back to the record and keeps polling; paused partitions return no records, but the consumer stays in the group:
Map<TopicPartition, Long> resumeAt = new HashMap<>();
while (running) {
long now = System.currentTimeMillis();
resumeAt.entrySet().removeIf(e -> {
if (e.getValue() <= now) { consumer.resume(List.of(e.getKey())); return true; }
return false;
});
for (ConsumerRecord<String, String> record : consumer.poll(Duration.ofMillis(500))) {
TopicPartition tp = new TopicPartition(record.topic(), record.partition());
if (resumeAt.containsKey(tp)) continue; // partition paused in this batch
long notBefore = Long.parseLong(header(record, "x-not-before"));
if (notBefore > now) {
consumer.seek(tp, record.offset()); // read it again when due
consumer.pause(List.of(tp));
resumeAt.put(tp, notBefore);
continue;
}
try {
handler.process(record);
} catch (Exception e) {
retryRouter.forward(record, e, stage(record)); // stage = value of the x-retry-stage header
}
consumer.commitSync(Map.of(tp, new OffsetAndMetadata(record.offset() + 1)));
}
}
Records in a retry topic are in due-time order per partition, because they were written with the same fixed delay, so pausing at the first record that is not yet due never holds back a record that is already due. This is also why each delay gets its own topic. Partition assignment changes still need care: clear resumeAt entries for revoked partitions in a ConsumerRebalanceListener.
6. Dead Letter Topic: Store, Monitor, Reprocess
A DLT is an ordinary Kafka topic. What makes it useful is what you put in it and what you do with it afterwards:
- Keep the original record unchanged (key, value, headers) and add diagnostic headers: original topic, partition and offset, exception class and message, number of attempts, and a timestamp.
- Give it enough retention for people to investigate, often longer than the main topic, and enough partitions if you plan to preserve the original partition number.
- Alert on it. A DLT nobody watches is silent data loss. Alert on the arrival rate, not just the total size.
- Reprocess deliberately. After a fix is deployed, a small tool or a consumer group that is started on demand reads the DLT and republishes records to the main topic, or calls the handler directly. Because the records already went through the handler at least once, the handler must be an idempotent consumer.
Scenario, a message with invalid data fails every time: classify the validation or deserialization error as permanent, forward the record to the DLT with diagnostic headers, commit its offset and continue. The next records are processed normally, and the bad one is waiting in the DLT for a fix. In a plain consumer, a deserialization failure surfaces as a RecordDeserializationException from poll(), which tells you the partition and offset to skip with seek(offset + 1) after recording it.
7. The Same Design in Spring for Apache Kafka
Spring for Apache Kafka implements all of these layers, so in a Spring Boot service you configure them instead of writing the loops above:
| Concept | Spring for Apache Kafka |
|---|---|
| Blocking retries with seek-back | DefaultErrorHandler (default: FixedBackOff(0L, 9), so 10 deliveries in total) |
| Error classification | addNotRetryableExceptions(...); deserialization and conversion errors are not retried by default |
| Publishing to a DLT | DeadLetterPublishingRecoverer, default topic <topic>-dlt and the same partition |
| Delayed retry topics | @RetryableTopic, topics such as orders-retry-0, …, orders-dlt; since 4.1 one retry topic is reused for attempts with the same delay |
| Bad payloads | ErrorHandlingDeserializer wraps the real deserializer so failures reach the error handler |
@Configuration
public class KafkaErrorHandlingConfig {
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
var recoverer = new DeadLetterPublishingRecoverer(template); // sends to <topic>-dlt
var backOff = new ExponentialBackOffWithMaxRetries(3); // 3 retries after the first attempt
backOff.setInitialInterval(500);
backOff.setMultiplier(2.0);
var handler = new DefaultErrorHandler(recoverer, backOff);
handler.addNotRetryableExceptions(InvalidOrderException.class); // permanent: straight to the DLT
return handler;
}
}
Spring Boot wires a single DefaultErrorHandler bean into the auto-configured listener container factory. Full Spring examples, including @RetryableTopic and @DltHandler, are in Kafka Retry and Backoff and Exception Handling in Kafka.
8. Retries and Message Ordering
Kafka keeps order within a partition. A retry topic breaks that: when record 1 for order-17 moves to a retry topic, record 2 for the same order can be processed first. Choose deliberately:
- Order matters per key (account balances, order state machines): use blocking retries only, or park later records of a key that already has a record in retry, which needs extra state.
- Records are independent (notifications, audit events): retry topics give much better throughput during outages.
See Kafka Message Ordering and Concurrent Processing for strategies that keep per-key order.
9. Common Mistakes
- Retrying every exception, so a validation error is tried for minutes before reaching the DLT.
- Sleeping inside the listener for long backoffs, which exceeds
max.poll.interval.msand causes rebalances that redeliver the same batch. - Committing the source offset before the retry or DLT write is acknowledged, which loses the record if the send fails.
- Dropping headers when forwarding, so the event ID and tracing context are lost.
- Using retry topics for ordered data without accepting that order per key is no longer guaranteed.
- Never looking at the DLT.
10. Best Practices
- Classify errors first; send permanent errors straight to the DLT.
- Combine layers: a few short blocking retries, then retry topics with growing delays, then the DLT.
- Bound the total retry time by the business need: a notification can wait an hour, a payment authorisation cannot.
- Make every handler idempotent, because retries and DLT reprocessing repeat work by design.
- Use an idempotent producer with
acks=allfor retry and DLT writes, and wait for the result before committing. - Monitor retry-topic lag, DLT arrival rate and the share of records that needed a retry.
11. Summary
Kafka retries producer sends automatically, but consumer retries are an application design. Classify errors as transient or permanent, use short blocking retries by seeking back to the failed offset, move longer waits to retry topics with a due-time header and a paused-partition consumer, and finish in a monitored dead letter topic that you can reprocess after a fix. Spring for Apache Kafka provides all of these building blocks; the trade-off to decide in every design is speed during outages versus strict per-key ordering.
12. Related Reading
- Kafka Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once
- Kafka Message Ordering and Concurrent Processing
- Kafka Consumer Lag and Backpressure
- How to Replay Messages in Kafka
13. References
- Apache Kafka 4.4 Javadoc: KafkaConsumer (seek, pause and resume)
- Apache Kafka 4.4: Producer configs (retries, delivery.timeout.ms)
- Apache Kafka 4.4: Consumer configs (max.poll.interval.ms)
- Spring for Apache Kafka: Handling exceptions (DefaultErrorHandler, DeadLetterPublishingRecoverer)
- Spring for Apache Kafka: Non-blocking retries
Kafka Retries and Dead Letter Topics Interview Questions and Answers
Common interview questions on Kafka Retries and Dead Letter Topics, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is the difference between producer retries and consumer retries in Kafka?
Answer: Producer retries are built into the Kafka client: on a retriable error such as a leader change, the producer resends the batch until delivery.timeout.ms expires, and the idempotent producer makes these resends duplicate-free. Consumer retries are not a broker feature. Kafka only knows the committed offset, so an uncommitted record is read again from the same position. The number of attempts, the delays and the final destination of a failing record are decided by the application or by a framework such as Spring for Apache Kafka.
Q. How do you decide whether a consumer error should be retried?
Answer: Ask whether the next attempt can succeed without anyone changing the data or the code. Timeouts, deadlocks, HTTP 503 or 429 responses and optimistic-lock conflicts are transient and worth retrying. Deserialization failures, validation errors, missing reference data that will never arrive, and bugs that fail on every attempt are permanent and should go straight to the dead letter topic. Unknown exceptions are usually retried a few times before being treated as permanent.
Intermediate questions
Q. Why does a plain-Java blocking retry seek back to the failed offset instead of looping inside the handler?
Answer: Looping with sleeps keeps the thread away from poll(), and if the loop outlasts max.poll.interval.ms the consumer leaves the group, triggering a rebalance and redelivery. Calling seek(partition, failedOffset) and returning to the poll loop makes the next poll return the same record, discards the later records of that partition so they are fetched again in order, and keeps the consumer an active group member. Spring’s DefaultErrorHandler uses the same seek-based approach.
Q. What information should a record carry when it is moved to a retry topic or the DLT?
Answer: The original key, value and headers unchanged, so the event ID and tracing context survive and the key still decides the partition. On top of that: the original topic, partition and offset, the exception class and message, the attempt or stage number, and for retry topics the earliest time the next attempt may run. These headers let the retry consumer wait correctly, and let a person or a tool diagnose and reprocess the record later.
Q. Why must the consumer wait for the retry-topic write to succeed before committing the original offset?
Answer: Committing first creates a gap where the record is neither in the retry topic nor reprocessable from the main topic: if the forwarding send fails or the process crashes, the record is lost. Waiting for the acknowledgement (for example producer.send(record).get() with acks=all) means the worst case is a duplicate: the record is forwarded twice or processed again, which an idempotent consumer handles.
Tricky and scenario questions
Q. A consumer repeatedly fails on one message because of invalid data, and all later messages in that partition are stuck. How do you fix it?
Answer: The record is a poison pill: without classification it is retried forever and blocks its partition. Classify the validation or deserialization error as non-retryable, forward the record with diagnostic headers to the DLT, commit its offset and continue with the next record. With Spring for Apache Kafka, use ErrorHandlingDeserializer plus a DefaultErrorHandler with a DeadLetterPublishingRecoverer and addNotRetryableExceptions(...). Then alert on the DLT, fix the data or the code, and reprocess the record.
Q. After a bug fix, you need to reprocess 20,000 records from the DLT. How do you do it safely?
Answer: Deploy the fix first, then run a dedicated reprocessing consumer with its own group ID that reads the DLT from the first affected offset and either republishes each record to the main topic or calls the handler directly. Throttle it so it does not compete with live traffic, and make sure the handler is idempotent, because some records may have partly succeeded before failing. Records that fail again go to a separate topic or stay in the DLT for another look, instead of looping.
Q. Would you use retry topics for account balance updates that must be applied in order?
Answer: Not on their own. Moving a record to a retry topic lets later records of the same key be processed first, so a debit could be applied before the credit it depends on. For ordered data, prefer blocking retries with a bounded backoff, which hold the partition until the record succeeds or goes to the DLT. If throughput during outages matters, track keys that have a record in retry and route their later records to the same retry path, accepting the extra complexity.