Kafka Producer Retries
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.
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 |
NotEnoughReplicasException | SerializationException (thrown from send()) |
| Request timeouts and disconnections | TopicAuthorizationException |
CoordinatorNotAvailable-type errors | InvalidTopicException |
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
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
| Property | Default (Kafka 4.4) | Purpose |
|---|---|---|
retries | 2147483647 | Maximum retry count; leave it unset and control retries with delivery.timeout.ms |
delivery.timeout.ms | 120000 | Total time to report success or failure after send() returns |
request.timeout.ms | 30000 | Time to wait for one response |
retry.backoff.ms | 100 | Initial backoff between attempts |
retry.backoff.max.ms | 1000 | Maximum backoff (exponential growth with jitter) |
max.in.flight.requests.per.connection | 5 | Unacknowledged requests per broker; must be ≤ 5 with idempotence |
enable.idempotence | true | No duplicates or reordering from retries |
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.
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):
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.*:
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
| Advantages | Limitations |
|---|---|
| Transient failures are invisible to the application | A send can take up to delivery.timeout.ms to fail, holding buffer memory |
| With idempotence: no duplicates and preserved order | Idempotence only covers retries inside one producer session |
| Exponential backoff avoids hammering a recovering broker | Application-level resends (calling send() again) can still duplicate |
8. Common Mistakes
- Setting
retries=0to "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 secondsend()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=trueand the defaultretries; tune behaviour withdelivery.timeout.ms. - Size
delivery.timeout.msto 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
Kafka Producer Retries Interview Questions and Answers
Common interview questions on Kafka Producer Retries, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. How many times does a Kafka producer retry by default?
Answer: retries defaults to Integer.MAX_VALUE, so in practice the count is unlimited. The real limit is delivery.timeout.ms (2 minutes by default): retries stop when the batch succeeds, a non-retriable error occurs, or the delivery timeout expires.
Q. Which errors are retried and which are not?
Answer: Errors that extend RetriableException are retried, such as a moved leader (NotLeaderOrFollowerException), NotEnoughReplicasException, timeouts and disconnections. Errors that retrying cannot fix fail immediately, for example RecordTooLargeException, authorization errors and invalid topics. Serialization errors are thrown from send() itself.
Intermediate questions
Q. How can producer retries cause duplicates, and how does Kafka prevent them?
Answer: If the broker writes a batch but the response is lost, the producer resends it and, without protection, the batch is written twice. The idempotent producer assigns a producer ID and sequence numbers per partition; the broker recognises a repeated sequence and acknowledges without writing again. It is on by default since Kafka 3.0 when no conflicting settings (such as acks=1) are used.
Q. Can retries change the order of messages within a partition?
Answer: Only without idempotence. If batch 1 fails, batch 2 succeeds and batch 1 is retried, batch 2 lands first when max.in.flight.requests.per.connection is greater than 1. With idempotence enabled, the broker rejects out-of-order sequence numbers, so order is kept for up to 5 in-flight requests. Without idempotence, set max.in.flight.requests.per.connection=1 to keep ordering.
Tricky and scenario questions
Q. Your web service blocks for two minutes when Kafka is down. How would you fix it?
Answer: Two settings cause this: max.block.ms (default 60 seconds), which makes send() block while waiting for metadata or buffer space, and delivery.timeout.ms (2 minutes) for completing the send. Lower both for request-driven code, never wait on send().get() in the request thread, and write events that could not be sent to an outbox table or fallback store so they can be republished later.
Q. Why must max.in.flight.requests.per.connection be 5 or less when idempotence is enabled?
Answer: For each producer and partition, the broker keeps the metadata of the last five batches it appended, so it can recognise a retried batch as a duplicate and detect gaps in the sequence numbers. With more than five unacknowledged requests, a retried batch could fall outside that window, and the broker could no longer guarantee ordering and de-duplication. That is why the client rejects an idempotent configuration with a higher value; five in-flight requests are enough to keep throughput high while retries stay safe.