00:00

Retry Mechanism in Apache Kafka

Last updated:

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 KafkaProducer resends a batch on retriable errors until delivery.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:

Retry layers in a Kafka pipelineThe producer sends to the orders topic and retries automatically until delivery.timeout.ms. The orders consumer polls the record and makes a few quick blocking retries. If the error is transient and still failing, the record is published to orders-retry-10s, whose consumer processes it after a 10 second delay; if it fails again it goes to orders-retry-1m, and when attempts are exhausted to orders-dlt. A permanent error such as invalid data goes from the orders consumer straight to orders-dlt. A successful attempt at any stage commits the offset and continues. Producerauto retries, idempotent ordersmain topic orders consumer2–3 quick blocking retries ① send ② poll ③ transient,still failing permanent error (invalid data): straight to the DLT orders-retry-10sattempt after 10 s orders-retry-1mattempt after 1 min orders-dltparked for a human ④ fails ⑤ exhausted Success at any stage: commit the offset and continue. Every hop keeps the key, value and headers.
Retry layers: automatic producer retries, short blocking retries in the consumer, delayed retry topics, and a dead letter topic for records that cannot be processed.
LayerHandlesProvided byBlocks the partition?
Producer retriesLeader changes, timeouts, NOT_ENOUGH_REPLICASKafka client (retries, delivery.timeout.ms)No (the producer’s own batches only)
Blocking consumer retriesShort glitches: a deadlock, one failed HTTP callApplication or frameworkYes, briefly
Retry topicsLonger outages of a dependencyApplication or frameworkNo, the record leaves the main topic
Dead letter topicPermanent errors and exhausted retriesApplication or frameworkNo

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 timeoutPayload cannot be deserialized
Downstream HTTP 503, 429 or a socket timeoutValidation failure: missing field, negative amount
Optimistic locking conflictReferenced entity does not exist and never will
Temporary authorisation token expiryA 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.

BlockingRetryLoop.java
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() plus break discards 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 below max.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:

RetryRouter.java
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:

DelayedRetryConsumer.java (poll loop)
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:

ConceptSpring for Apache Kafka
Blocking retries with seek-backDefaultErrorHandler (default: FixedBackOff(0L, 9), so 10 deliveries in total)
Error classificationaddNotRetryableExceptions(...); deserialization and conversion errors are not retried by default
Publishing to a DLTDeadLetterPublishingRecoverer, 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 payloadsErrorHandlingDeserializer wraps the real deserializer so failures reach the error handler
KafkaErrorHandlingConfig.java
@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.ms and 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=all for 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.

13. References