Sub topic 10
Reliable delivery: acks, retries and idempotence
This chapter covers what the producer must be configured to do so that a record the application considers sent is actually stored in Kafka, once and in order. It assumes you can publish with KafkaTemplate and know what partitions, offsets and replicas are. Consumer-side failures are covered in later chapters.
What can go wrong on the producer side
A send can fail in several ways. The broker may be down, the partition leader may change during the send, or the network may drop the response after the broker has already written the record. Each case leads to a different result.
- Lost record. The producer believes the send succeeded, but the broker never durably stored it.
- Duplicate record. The producer retries after a lost response, and the broker stores the same record twice.
- Reordered records. Two records are in flight to one partition, the first fails and is retried, and the second is stored before it.
Three producer settings address these: acks, retries with the related timeouts, and enable.idempotence.
Acknowledgments: the `acks` setting
acks controls how many replicas must confirm a write before the broker tells the producer it succeeded.
| Value | Broker responds when | Risk |
|---|---|---|
| `0` | Immediately, without waiting | The record is lost if the broker never received it. The producer cannot detect this. |
| `1` | The partition leader has written it | The record is lost if the leader fails before followers copy it. |
| `all` (or `-1`) | The leader and all in-sync replicas have written it | Lowest loss risk, slightly higher latency. |
The in-sync replicas (ISR) are the replicas that are currently caught up with the leader. With acks=all, the number of replicas that must confirm is the size of the ISR. This is a problem if the ISR shrinks to just the leader, because acks=all then behaves like acks=1.
The broker-side or topic-level setting min.insync.replicas closes this gap. If fewer replicas than this value are in sync, the broker rejects writes sent with acks=all and the producer receives a NotEnoughReplicasException. A common production combination is replication factor 3, min.insync.replicas=2 and acks=all. This tolerates one broker failure without losing acknowledged data and without blocking writes.
You can set min.insync.replicas on the topic from the same NewTopic bean that declares it:
package com.example.orders;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.config.TopicConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;
@Configuration
public class ReliableTopicConfig {
@Bean
public NewTopic ordersTopic() {
return TopicBuilder.name("orders")
.partitions(3)
.replicas(3)
.config(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "2")
.build();
}
}This bean needs a cluster with at least three brokers. On a single-broker development setup, topic creation fails because the requested replication factor is larger than the number of available brokers.
Retries and timeouts
When a send fails with a retriable error, such as a leader election in progress or a network timeout, the producer retries it automatically. You do not write a retry loop for these cases.
Modern Kafka clients (3.0 and later) default retries to Integer.MAX_VALUE and bound the total effort with a time limit instead:
delivery.timeout.msis the upper limit on the time from thesend()call until success or failure is reported. The default is 120000 (two minutes).request.timeout.msis how long the producer waits for a single response from the broker. The default is 30000.retry.backoff.msis the pause between retries. The default is 100.
So a send is retried until it succeeds or delivery.timeout.ms expires. Only then does the CompletableFuture returned by KafkaTemplate.send complete exceptionally. That is the point at which your whenComplete callback sees an error. Non-retriable errors, such as RecordTooLargeException or a serialization failure, fail at once.
Setting delivery.timeout.ms is a business decision. A shorter value reports failure sooner. A longer value rides out longer broker outages but keeps records in producer memory for longer.
Why retries alone cause duplicates and reordering
Retries fix lost records but introduce the other two problems. Consider this sequence:
- The producer sends record A. The broker writes it.
- The acknowledgment is lost on the network.
- The producer times out and sends A again.
- The broker writes A a second time.
The topic now holds A twice. For reordering, suppose the producer allows several in-flight requests per connection. Batch 1 fails and batch 2 succeeds. Batch 1 is retried and lands after batch 2.
The old workaround was max.in.flight.requests.per.connection=1. It preserves order but cuts throughput, and it does nothing about duplicates.
Idempotent producer
Setting enable.idempotence=true makes retries safe. The broker assigns each producer a producer ID, and the producer attaches a sequence number to every record batch per partition. The broker remembers the last sequence numbers it accepted. It drops a batch it has already seen, and it rejects a batch that skips ahead. The result, per partition and per producer session, is no duplicates and no reordering from retries, even with up to five in-flight requests.
Enabling idempotence requires compatible settings:
acksmust beall.retriesmust be greater than zero.max.in.flight.requests.per.connectionmust be 5 or less.
If you set a conflicting value explicitly, the client throws a ConfigException at startup. Since Kafka 3.0, idempotence is enabled by default when none of these are in conflict. Setting it explicitly in configuration is still worthwhile because it documents the intent, and because an accidental conflicting setting then fails loudly.
The guarantee has limits:
- It covers one producer instance. If the application restarts, it gets a new producer ID, and a record the application re-sends after the restart is not recognized as a duplicate.
- It covers retries inside the client. If your code calls
sendtwice with the same payload, Kafka stores both. - It applies per partition. It does not coordinate writes to several partitions or topics. That requires transactions, covered in a later chapter.
Configuring it in Spring Boot
The spring.kafka.producer properties map to the Kafka client settings. Extra client properties go under properties.
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
acks: all
properties:
enable.idempotence: true
delivery.timeout.ms: 60000
request.timeout.ms: 15000
max.in.flight.requests.per.connection: 5delivery.timeout.ms must be at least request.timeout.ms plus linger.ms. The client rejects a smaller value. Here 60000 is well above 15000 plus the default linger.ms of 5.
Handling the final result in code
Retries and idempotence reduce failures, but they do not remove them. If the broker is unreachable for longer than delivery.timeout.ms, the send fails and your code must decide what happens next. The publisher from the previous chapter logs the failure. For orders, that is not enough, because a lost order is a business problem. The next version surfaces the failure to the caller.
package com.example.orders;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
@Service
public class ReliableOrderPublisher {
private static final Logger log = LoggerFactory.getLogger(ReliableOrderPublisher.class);
private final KafkaTemplate<String, OrderEvent> kafkaTemplate;
public ReliableOrderPublisher(KafkaTemplate<String, OrderEvent> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public CompletableFuture<SendResult<String, OrderEvent>> publish(OrderEvent event) {
return kafkaTemplate.send("orders", event.orderId(), event)
.whenComplete((result, ex) -> {
if (ex != null) {
log.error("Order {} was not stored in Kafka", event.orderId(), ex);
} else {
log.info("Order {} stored at partition {} offset {}",
event.orderId(),
result.getRecordMetadata().partition(),
result.getRecordMetadata().offset());
}
});
}
}The caller can now react to the returned future. For example, it can mark the order as "pending publication" in a database and retry later. Blocking on the future with get(timeout, unit) is also possible when you need a synchronous result, at the cost of throughput.
Common errors
ConfigExceptionabout idempotence at startup. Another setting conflicts with idempotence, usuallyacks=1orretries=0. Remove the conflicting value.NotEnoughReplicasException. Fewer replicas are in sync thanmin.insync.replicas. The producer retries untildelivery.timeout.ms. Check broker health instead of lowering the setting.TimeoutException: Expiring N record(s). The record was not acknowledged withindelivery.timeout.ms. Check the broker address and network first, then the timeouts.- Treating
send()returning as success. The method returns immediately and the record may still be in the producer buffer. Only the completed future confirms the write. - Duplicates after an application restart. Idempotence does not cover this. Make the consumer idempotent, for example by deduplicating on
orderId.
Choosing settings
| Goal | Settings |
|---|---|
| Lowest latency, losses acceptable (metrics, logs) | `acks=1`, idempotence off |
| Default for business events | `acks=all`, `enable.idempotence=true`, `min.insync.replicas=2`, replication factor 3 |
| Order-critical per key | Same as above, with a record key so related events share a partition |
| Atomic writes across topics | Add transactions |
Exercise
A producer runs with acks=all, a topic with replication factor 3, and the default min.insync.replicas=1. Two of the three brokers fail, leaving only the leader in sync. A send is acknowledged. Why is this acknowledged record still at risk, and which setting would have prevented the acknowledgment?
Show answer
With min.insync.replicas=1, acks=all only requires the leader, since the in-sync set has shrunk to the leader alone. The record exists on one broker, so losing it loses the record. Setting min.insync.replicas=2 makes the broker reject the write with NotEnoughReplicasException instead of acknowledging it.
Exercise
Retries are enabled but enable.idempotence is false, and max.in.flight.requests.per.connection is 5. Name two problems that can appear in the topic when a network error causes a retry.
Show answer
A duplicate record, if the first attempt was written but its acknowledgment was lost. Reordering, if an earlier batch fails and is retried after a later batch has already been written to the same partition.
Exercise
Your application restarts after a crash and re-sends an order that it had already sent before the crash. The topic ends up with two copies. Does enable.idempotence=true prevent this? Explain.
Show answer
No. The restarted application gets a new producer ID, so the broker has no sequence history to compare against. Idempotence only deduplicates retries within one producer session. Deduplicate in the consumer, or use a stable business key to make processing idempotent.