00:00

Kafka Retry Mechanism

Last updated:

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 retriesNon-blocking retries
HowSeek back and redeliver the same record on the same consumerPublish the failed record to a retry topic and continue
Other records in the partitionWaitKeep flowing
Ordering per keyPreservedNot preserved for retried records
Suitable delaysShort (milliseconds to seconds)Seconds to hours
Spring KafkaDefaultErrorHandler with a BackOff@RetryableTopic

2. How Non-Blocking Retries Work

Non-blocking retry topicsA record fails in the main topic listener and is published to the first retry topic with a due time one second later. Its consumer waits until the due time, then calls the same listener. If it fails again, the record goes to the second retry topic with a two-second delay. After the last attempt the record goes to the dead-letter topic, where a DLT handler logs it. Meanwhile the main topic keeps processing other records. stock-updatesattempt 1 …-retry-1000attempt 2 after 1 s …-retry-2000attempt 3 after 2 s …-dlt@DltHandler failsfailsfails next records continue without waiting Each retry topic has its own consumer that pauses its partition until the record's due time; the delay grows with the backoff multiplier.
With retry topics, a failing record leaves the main partition, so other records are not delayed.

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:

BlockingRetryConfig.java
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.

StockUpdateListener.java
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;
    }
}
StockApplication.java
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");
        };
    }
}
application.yml
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):

Output
 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

SettingWhereGuidance
attempts@RetryableTopicTotal attempts including the first; default 3
backOff@RetryableTopicdelay, multiplier, maxDelay; default 1 second fixed
include / exclude@RetryableTopicRetry only transient exceptions
sameIntervalTopicReuseStrategy@RetryableTopicWith fixed delays, one retry topic is reused for all attempts
BackOffDefaultErrorHandlerFixedBackOff or ExponentialBackOffWithMaxRetries for blocking retries
max.poll.interval.msconsumerMust 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