00:00

Kafka Producer Retries

Last updated:

Kafka producer retries are the automatic resends the Kafka client performs when a write fails with a temporary error, such as a leader election or a short network problem. They run inside the producer library, before your code sees any error, and in modern Kafka they are both unlimited in count and bounded in time.

This tutorial explains which errors are retried, how the retry timeouts fit together, how backoff works since Kafka 3.7, why retries no longer cause duplicates or reordering with the default settings, and how to handle the errors that retries cannot fix.

1. What Are Producer Retries?

When a produce request fails with a retriable error, the producer puts the batch back into its queue and sends it again after a backoff. It keeps doing so until the batch succeeds, a non-retriable error occurs, or delivery.timeout.ms expires. Only then does the producer complete the send with an exception in your callback or future.

Definition: Producer retries are client-side resends of failed produce requests for transient errors, bounded by delivery.timeout.ms (default 2 minutes) rather than by a retry count.

2. Why Retries Are Needed

In a healthy cluster, short failures are normal: a broker restarts during a rolling upgrade, a partition leader moves, a request times out under load, or the ISR is briefly smaller than min.insync.replicas. Without retries, every one of these events would surface as an application error. With retries, the producer refreshes its metadata, finds the new leader and completes the write, and the application never notices.

3. How Retries Work

3.1 Retriable and non-retriable errors

Retriable (resent automatically)Non-retriable (fail immediately)
NotLeaderOrFollowerException (leader moved)RecordTooLargeException
NotEnoughReplicasExceptionSerializationException (thrown from send())
Request timeouts and disconnectionsTopicAuthorizationException
CoordinatorNotAvailable-type errorsInvalidTopicException

In the Java client, retriable errors extend org.apache.kafka.common.errors.RetriableException, which is a useful check in callbacks.

3.2 How the timeouts fit together

Producer retry timelineAfter send() returns, a record waits up to linger.ms in a batch. Each attempt waits up to request.timeout.ms for a response. Failed attempts are retried after an exponential backoff from retry.backoff.ms up to retry.backoff.max.ms. The whole time from send() to success or failure is bounded by delivery.timeout.ms. send() returns batchinglinger.ms attempt 1 fails≤ request.timeout.ms backoff100 ms attempt 2 failsleader moved backoff200 ms attempt 3 succeedscallback: metadata delivery.timeout.ms (default 120000): total time to report success or failure Backoff doubles per failed attempt (retry.backoff.ms = 100) up to retry.backoff.max.ms = 1000, with ±20% jitter. If delivery.timeout.ms expires first, the callback receives a TimeoutException; retries = Integer.MAX_VALUE never limits it.
Retries are limited by time, not by count: every attempt and backoff must fit inside delivery.timeout.ms.

3.3 Backoff

Since Kafka 3.7 (KIP-580), the wait between attempts starts at retry.backoff.ms (100 ms) and grows exponentially up to retry.backoff.max.ms (1 second), with ±20% random jitter so that many clients do not retry in lockstep.

3.4 Ordering and duplicates

A retry can cause two problems in principle: a duplicate, when the first attempt was actually written but its response was lost, and reordering, when batch 1 fails and is retried after batch 2 succeeded. The idempotent producer (default since Kafka 3.0) solves both: the broker tracks a producer ID and a sequence number per partition, discards a batch it has already written, and rejects out-of-order sequences. Ordering is preserved for up to 5 in-flight requests per connection.

4. Configuration

PropertyDefault (Kafka 4.4)Purpose
retries2147483647Maximum retry count; leave it unset and control retries with delivery.timeout.ms
delivery.timeout.ms120000Total time to report success or failure after send() returns
request.timeout.ms30000Time to wait for one response
retry.backoff.ms100Initial backoff between attempts
retry.backoff.max.ms1000Maximum backoff (exponential growth with jitter)
max.in.flight.requests.per.connection5Unacknowledged requests per broker; must be ≤ 5 with idempotence
enable.idempotencetrueNo duplicates or reordering from retries
Rule: delivery.timeout.ms must be at least request.timeout.ms + linger.ms, otherwise the producer refuses to start.

5. Java Example: Handling What Retries Cannot Fix

Retries are invisible when they succeed. Your code must still handle the final outcome. The example sends a normal event and a record larger than the default max.request.size (about 1 MB), which is not retriable.

InventoryEventProducer.java
package com.javabytechie.kafka;

import java.util.Properties;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.errors.RetriableException;
import org.apache.kafka.common.serialization.StringSerializer;

public class InventoryEventProducer {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 60_000);  // stop retrying after 1 minute

        Callback callback = (metadata, ex) -> {
            if (ex == null) {
                System.out.println("OK: offset " + metadata.offset());
            } else if (ex instanceof RetriableException) {
                System.out.println("Gave up after retries: " + ex.getClass().getSimpleName());
            } else {
                System.out.println("Not retriable: " + ex.getClass().getSimpleName());
            }
        };

        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
            producer.send(new ProducerRecord<>("inventory", "SKU-42", "{\"stock\":17}"), callback);
            String huge = "x".repeat(2_000_000);                     // about 2 MB
            producer.send(new ProducerRecord<>("inventory", "SKU-43", huge), callback);
        }
    }
}

Output (run against a local Kafka 4.4 cluster with an existing inventory topic):

Output
Not retriable: RecordTooLargeException
OK: offset 0

The oversized record fails at once inside the client, before any request is sent, so its callback runs first. The normal record is written after the batch is sent. A broker outage longer than one minute would instead produce Gave up after retries: TimeoutException.

5.1 Spring Boot

Spring Boot passes producer retry settings through spring.kafka.producer.* and spring.kafka.producer.properties.*:

application.yml
spring:
  kafka:
    producer:
      retries: 2147483647
      properties:
        delivery.timeout.ms: 60000
        retry.backoff.ms: 100
        retry.backoff.max.ms: 1000

6. Real-World Scenarios

  • Rolling broker upgrades: leaders move; producers see NotLeaderOrFollowerException, refresh metadata and continue without errors.
  • Payment events: with idempotence, a lost response no longer creates a duplicate payment record in the topic.
  • Web request handlers: a short delivery.timeout.ms (for example 10–30 seconds) lets the request fail fast and store the event in an outbox for a later retry instead of blocking users.

7. Advantages and Limitations

AdvantagesLimitations
Transient failures are invisible to the applicationA send can take up to delivery.timeout.ms to fail, holding buffer memory
With idempotence: no duplicates and preserved orderIdempotence only covers retries inside one producer session
Exponential backoff avoids hammering a recovering brokerApplication-level resends (calling send() again) can still duplicate

8. Common Mistakes

  • Setting retries=0 to "avoid duplicates": it turns every leader change into an error; idempotence already prevents duplicates.
  • Disabling idempotence with max.in.flight.requests.per.connection > 1: retries can then reorder records within a partition.
  • Retrying in a loop around send(): a second send() is a new record to Kafka, so a slow response can create duplicates.
  • Not handling the final failure: after the timeout the record is gone unless your callback stores or reports it.

9. Best Practices

  • Keep enable.idempotence=true and the default retries; tune behaviour with delivery.timeout.ms.
  • Size delivery.timeout.ms to your use case: long for background pipelines, shorter for request-driven producers that can fall back to an outbox.
  • Distinguish error types in callbacks with RetriableException; non-retriable errors need code or configuration fixes.
  • Use transactions or the outbox pattern when an event must be produced exactly once together with a database change.

10. Conclusion

Kafka producers retry transient errors automatically until delivery.timeout.ms expires, with exponential backoff since Kafka 3.7. With the default idempotent producer, retries create neither duplicates nor reordering inside a partition. Your application still owns the final outcome: handle the exception in the callback and decide whether to store, alert or fail. Read Kafka Producer Acknowledgements for the durability side, and Kafka Retry Mechanism for retries on the consumer side.

11. References