Idempotent Producer in Kafka
An idempotent producer in Kafka guarantees that a record is written to a partition exactly once, even when the producer has to retry a send because a broker or the network failed. Without it, a retry after a lost acknowledgement writes the same record twice. Since Kafka 3.0, idempotence is switched on by default, which is why most applications get this protection without knowing it, and why it is easy to switch it off by accident.
This tutorial explains what idempotence guarantees, how the producer ID and sequence numbers work inside the broker, which settings it needs, how it can be disabled without warning, and what it does not protect you from. Examples use the Java client and Spring Boot with Kafka 4.4.
1. What Is an Idempotent Producer?
An operation is idempotent when doing it several times has the same effect as doing it once. Applied to Kafka, an idempotent producer can send the same batch of records to a partition as many times as it needs to, and the partition still contains one copy of each record, in the order they were sent.
The feature is controlled by one producer setting, enable.idempotence, which defaults to true since Kafka 3.0. It needs no code changes: you keep calling send() as usual, and the producer and broker cooperate to remove duplicates caused by retries.
2. Why It Is Needed
A producer only knows a write succeeded when the broker’s acknowledgement arrives. If the acknowledgement is lost, for example because the connection dropped or the request timed out, the producer cannot tell whether the write happened. The only safe choice is to retry, and that retry creates two problems when idempotence is off:
| Problem without idempotence | How the idempotent producer solves it |
|---|---|
| Duplicates: the first write succeeded, only its acknowledgement was lost, so the retry writes the batch a second time. | The broker recognises the retried batch by its sequence numbers and acknowledges it without writing it again. |
| Reordering: with several requests in flight, batch 1 fails and is retried after batch 2 succeeded, so batch 2 lands first. | The broker only accepts the next expected sequence number, so batches stay in send order, with up to 5 requests in flight. |
Duplicates are not a theoretical concern: a payment event written twice can charge a customer twice, and an order event written twice can ship two parcels, unless every consumer is written defensively.
3. How It Works Internally
Idempotence is built on three pieces of metadata that the producer attaches to every batch it sends: a producer ID, an epoch and a sequence number.
3.1 Producer ID and epoch
When an idempotent producer starts, it sends an InitProducerId request to the cluster and receives a unique producer ID (PID) and an epoch. The PID identifies this producer instance; the epoch is mainly used to fence off old instances of transactional producers. You never set either value yourself.
3.2 Sequence numbers per partition
For every partition it writes to, the producer keeps a counter that starts at 0. Each batch carries the sequence number of its first record, and the counter advances by the number of records in the batch. A batch of five records starting at 0 covers sequence numbers 0 to 4; the next batch to that partition starts at 5.
3.3 What the partition leader checks
For each producer ID, the partition leader remembers the sequence numbers of the last few batches it appended (the last five). When a batch arrives, it compares the batch’s sequence number with what it expects next:
| Incoming batch | Broker decision |
|---|---|
| The next expected sequence number | Appends the batch to the log and acknowledges it. |
| A sequence number it has already appended | A duplicate caused by a retry: acknowledges it without writing it again. |
| A sequence number higher than expected (a gap) | Rejects it with OutOfOrderSequenceException, because an earlier batch is missing. |
This state is part of the partition, so it is replicated to followers and survives a leader change: a retry that reaches the new leader is still recognised as a duplicate.
4. Configuration
Idempotence works only when the producer is allowed to retry and waits for all in-sync replicas. The defaults already satisfy this:
| Property | Required for idempotence | Default (Kafka 4.4) |
|---|---|---|
enable.idempotence | true | true |
acks | all (same as -1) | all |
retries | greater than 0 | Integer.MAX_VALUE |
max.in.flight.requests.per.connection | 5 or less | 5 |
delivery.timeout.ms | upper bound on the total time for a send, including retries | 120000 (2 minutes) |
producer.id.expiration.ms (broker) | how long a partition leader keeps an idle producer ID’s state | 86400000 (1 day) |
enable.idempotence but set a conflicting value, such as acks=1 or max.in.flight.requests.per.connection=10, Kafka quietly turns idempotence off. If you set enable.idempotence=true explicitly together with a conflicting value, the producer fails at startup with a ConfigException. Setting enable.idempotence=true explicitly is therefore the safer choice: a wrong setting fails loudly instead of silently removing your protection.Keep retries unset and let delivery.timeout.ms decide how long the producer keeps trying. Retries are only safe because they happen inside the producer with the same sequence numbers.
5. Practical Example: Java and Spring Boot
5.1 Plain Java producer
An order service publishes order-placed events keyed by order ID. Idempotence is the default, but setting it explicitly protects against a future configuration change that would disable it silently:
package com.javabytechie.kafka;
import java.util.Properties;
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.serialization.StringSerializer;
public class OrderEventProducer implements AutoCloseable {
private final KafkaProducer<String, String> producer;
public OrderEventProducer(String bootstrapServers) {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
// Explicit: a conflicting setting now fails at startup instead of disabling idempotence
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 120_000);
// retries and max.in.flight.requests.per.connection keep their safe defaults
this.producer = new KafkaProducer<>(props);
}
public void publishOrderPlaced(String orderId, String payloadJson) {
ProducerRecord<String, String> record = new ProducerRecord<>("order-placed", orderId, payloadJson);
producer.send(record, (metadata, exception) -> {
if (exception != null) {
// Retries are already exhausted here. Do NOT call send() again:
// an application-level resend gets new sequence numbers and can create a duplicate.
System.err.println("Order event " + orderId + " failed: " + exception);
} else {
System.out.printf("Order %s written to %s-%d at offset %d%n",
orderId, metadata.topic(), metadata.partition(), metadata.offset());
}
});
}
@Override
public void close() {
producer.close();
}
}
The important parts:
ENABLE_IDEMPOTENCE_CONFIG = trueturns a silent downgrade into a startup error.- The callback does not resend. When it reports an error, the producer has already retried until
delivery.timeout.ms. A manualsend()would be a new record with new sequence numbers, which the broker cannot recognise as a duplicate. - The key is the order ID, so all events of one order go to the same partition and keep their order.
On startup, the client logs its effective configuration. Check it once to confirm idempotence is really active (acks = -1 is how all is printed):
INFO o.a.k.clients.producer.ProducerConfig : ProducerConfig values:
acks = -1
delivery.timeout.ms = 120000
enable.idempotence = true
max.in.flight.requests.per.connection = 5
retries = 2147483647
Order 1001 written to order-placed-2 at offset 57
5.2 Spring Boot
Spring Boot does not change Kafka’s idempotence default; it creates the producer from spring.kafka.producer.* properties. Settings without a dedicated Spring Boot property go under properties:
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
acks: all
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JacksonJsonSerializer
properties:
enable.idempotence: true # explicit, so a conflicting acks value fails fast
delivery.timeout.ms: 120000
@Service
public class OrderEventPublisher {
private static final Logger log = LoggerFactory.getLogger(OrderEventPublisher.class);
private final KafkaTemplate<String, OrderPlaced> kafkaTemplate;
public OrderEventPublisher(KafkaTemplate<String, OrderPlaced> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void publish(OrderPlaced event) {
kafkaTemplate.send("order-placed", event.orderId(), event)
.whenComplete((result, ex) -> {
if (ex != null) {
// The producer already retried internally; record the failure, do not resend here
log.error("Could not publish order {}", event.orderId(), ex);
}
});
}
}
A common Spring Boot trap is setting spring.kafka.producer.acks: 1 for speed while leaving idempotence implicit: the producer then silently runs without idempotence. With enable.idempotence: true set as above, the same mistake stops the application at startup.
6. What Idempotence Does Not Cover
The idempotent producer removes one specific kind of duplicate: a retry inside one producer session, to one partition. It does not help in these cases:
- Application-level resends. If your code calls
send()again after a failure, the record gets new sequence numbers and is written again. - Producer restarts. A restarted producer gets a new producer ID, so it cannot be matched with records the old instance sent before crashing. A
transactional.idkeeps the identity across restarts. - Atomic writes to several partitions. Each partition is protected on its own; writing to two topics all-or-nothing needs Kafka transactions.
- Duplicates on the consumer side. A consumer that processes a record and crashes before committing its offset will process it again. That needs an idempotent consumer; the Offset Management tutorial explains why redelivery happens.
- The database and Kafka together. Saving an order and publishing its event are two systems; idempotence cannot make them consistent. That is the job of the transactional outbox pattern.
7. Idempotent vs Transactional Producer
| Idempotent producer | Transactional producer | |
|---|---|---|
| Enabled by | enable.idempotence=true (default) | Setting a transactional.id |
| Guarantee | No duplicates or reordering from retries, per partition | Several writes, across partitions and topics, commit or abort together |
| Survives producer restart | No, a new producer ID is assigned | Yes, the transactional.id maps to the same producer ID, and old instances are fenced |
| Code changes | None | initTransactions(), beginTransaction(), commitTransaction() |
| Consumer setting needed | None | isolation.level=read_committed to hide aborted records |
| Overhead | Negligible | Extra coordinator round trips per transaction |
A transactional producer is always idempotent as well. Use plain idempotence for ordinary event publishing, and transactions for consume–process–produce pipelines that must be exactly-once end to end.
8. Real-World Use Cases
- Payments and ledgers: a
payment-capturedevent written twice would trigger two settlements downstream. - Order and inventory events: duplicate
stock-reservedevents would reserve stock twice and show items as sold out. - Metrics and billing counters: usage events are often summed; a duplicate directly inflates a customer’s bill.
- Unreliable networks: producers running across availability zones or regions see more timeouts and therefore more retries, which is exactly when idempotence matters.
9. Common Mistakes
- Setting
acks=1for performance without noticing that it silently disables idempotence. - Raising
max.in.flight.requests.per.connectionabove 5 for throughput, with the same silent effect. - Resending in the send callback or a
catchblock, which creates exactly the duplicates idempotence is meant to prevent. - Assuming idempotence means exactly-once end to end. It covers the producer-to-partition hop only.
- Setting
retries=0to “avoid duplicates”. With idempotence this is unnecessary, and it turns every transient error into a lost record.
10. Best Practices
- Set
enable.idempotence=trueexplicitly so conflicting settings fail at startup. - Leave
retriesandmax.in.flight.requests.per.connectionat their defaults, and bound retry time withdelivery.timeout.ms. - Never resend from application code; on a final failure, log, alert, or fall back to an outbox table.
- Check the
ProducerConfig valueslog once per service to confirmenable.idempotence = true. - Use a
transactional.idwhen you need protection across restarts or atomic writes to several partitions. - Still make consumers idempotent; producer idempotence does not stop redelivery to consumers.
11. Summary
The idempotent producer in Kafka assigns each producer an ID and numbers every batch per partition, so the partition leader can drop retried duplicates and reject out-of-order batches. It is enabled by default since Kafka 3.0 and needs acks=all, retries and at most 5 in-flight requests, but a conflicting setting can silently disable it, so set enable.idempotence=true explicitly. It protects one producer session writing to one partition; for restarts, multi-partition atomicity, consumer duplicates and database consistency you need transactions, idempotent consumers and the outbox pattern.
12. References
- Apache Kafka 4.4: Producer configs (enable.idempotence, acks, max.in.flight.requests.per.connection)
- Apache Kafka 4.4: Broker configs (producer.id.expiration.ms)
- Apache Kafka design: Message delivery semantics
- Apache Kafka 4.4 Javadoc: KafkaProducer (idempotence and transactions)
- Spring for Apache Kafka: Sending messages
Kafka Idempotent Producer Interview Questions and Answers
Common interview questions on Kafka Idempotent Producer, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is an idempotent producer in Kafka?
Answer: A producer that guarantees each record is written to a partition exactly once and in order, even when it retries sends after network or broker failures. It is controlled by enable.idempotence, which defaults to true since Kafka 3.0, and needs no code changes: the producer and the partition leader cooperate using a producer ID and sequence numbers.
Q. What are the producer ID, epoch and sequence number, and who assigns them?
Answer: The producer ID and epoch are assigned by the cluster when the producer starts, through an InitProducerId request; the ID identifies the producer instance and the epoch is used to fence old instances of transactional producers. The sequence number is maintained by the producer itself, one counter per partition, starting at 0 and advancing by the number of records in each batch. The partition leader uses the pair (producer ID, sequence) to detect retried duplicates and gaps.
Intermediate questions
Q. Idempotence is the default. How can it end up disabled without anyone noticing?
Answer: If enable.idempotence is not set explicitly and a conflicting setting is present, such as acks=1, acks=0 or max.in.flight.requests.per.connection above 5, Kafka silently disables idempotence. If it is set to true explicitly, the same conflict throws a ConfigException at startup. That is why teams set it explicitly, and check the ProducerConfig values startup log for enable.idempotence = true.
Q. What is the difference between an idempotent producer and a transactional producer?
Answer: The idempotent producer prevents duplicates and reordering caused by retries, per partition, within one producer session, with no code changes. A transactional producer, enabled by setting a transactional.id, makes several writes across partitions and topics commit or abort together, keeps its identity across restarts and fences zombie instances. It needs beginTransaction()/commitTransaction() calls and read_committed consumers. Every transactional producer is also idempotent.
Q. What happens when the partition leader receives a batch with a sequence number higher than it expects?
Answer: A gap means an earlier batch from this producer is missing, so the leader rejects the batch with OutOfOrderSequenceException instead of appending it out of order. The affected sends fail and the error reaches the application’s callback. Gaps are rare in a healthy cluster; they point to data loss on the broker side, for example after an unclean leader election, or to producer state that expired after producer.id.expiration.ms.
Tricky and scenario questions
Q. A send fails after all retries, and the code catches the error and calls send() again. Does idempotence prevent a duplicate?
Answer: No. Idempotence only deduplicates retries the producer performs internally with the same sequence numbers. A new send() from application code is a new record with new sequence numbers, so if the first attempt was actually written, the record now exists twice. Do not resend from callbacks or catch blocks; record the failure, alert, or store the event in an outbox table and publish it from there.
Q. A producer crashes and restarts while some sends were in flight. Can the restarted instance create duplicates?
Answer: Yes, if the application re-sends those records after restarting. The new instance receives a new producer ID, so the broker cannot link its records to those the old instance already wrote. Idempotence is per producer session. To survive restarts, use a transactional.id, which maps to the same producer ID and fences the old instance, or make the consumers idempotent so a duplicate is harmless.
Q. Producer idempotence is enabled, yet the database behind a consumer contains duplicate orders. How is that possible?
Answer: Producer idempotence only guarantees one copy per record in the log. Duplicates can still appear later: the consumer processes a record, writes to the database and crashes before committing its offset, so after a restart or rebalance it processes the record again. Or the upstream service published the event twice through its own resend logic. The fix is on the consumer side: an idempotent consumer, for example a unique constraint on the order ID or a table of processed message IDs, written in the same database transaction as the business change.