00:00

Idempotent Producer in Kafka

Last updated:

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.

Analogy: Think of numbered cheques. If the bank receives cheque number 17 twice, the clerk sees it has already been paid and does not pay it again. The idempotent producer numbers every batch in the same way, so the broker can refuse to “pay” a batch twice.

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 idempotenceHow 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 batchBroker decision
The next expected sequence numberAppends the batch to the log and acknowledges it.
A sequence number it has already appendedA 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.

How the idempotent producer removes a duplicate caused by a retryA producer with producer ID 42 sends a batch with sequence numbers 0 to 4 to the partition leader, which appends it. The acknowledgement is lost, so the producer retries the same batch with the same sequence numbers. The leader sees that sequence 0 to 4 was already appended and acknowledges without writing it again. The next batch, sequence 5 to 9, is appended normally. The log contains each record once. ProducerPID 42, epoch 0 Partition leaderorders-0, expects seq 0 ① send batch, seq 0–4 append, now expects 5 ✕② acknowledgement lost ③ retry same batch, seq 0–4 duplicate: no write ④ acknowledged (already written) ⑤ next batch, seq 5–9 append, now expects 10 ⑥ acknowledged Log of orders-0: records 0–9, each exactly once
The retried batch carries the same producer ID and sequence numbers, so the leader recognises it as a duplicate and acknowledges it without appending it a second time.

4. Configuration

Idempotence works only when the producer is allowed to retry and waits for all in-sync replicas. The defaults already satisfy this:

PropertyRequired for idempotenceDefault (Kafka 4.4)
enable.idempotencetruetrue
acksall (same as -1)all
retriesgreater than 0Integer.MAX_VALUE
max.in.flight.requests.per.connection5 or less5
delivery.timeout.msupper bound on the total time for a send, including retries120000 (2 minutes)
producer.id.expiration.ms (broker)how long a partition leader keeps an idle producer ID’s state86400000 (1 day)
Silent disabling: if you do not set 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:

OrderEventProducer.java
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 = true turns 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 manual send() 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):

Startup log (excerpt)
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:

application.yml
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
OrderEventPublisher.java
@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.id keeps 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 producerTransactional producer
Enabled byenable.idempotence=true (default)Setting a transactional.id
GuaranteeNo duplicates or reordering from retries, per partitionSeveral writes, across partitions and topics, commit or abort together
Survives producer restartNo, a new producer ID is assignedYes, the transactional.id maps to the same producer ID, and old instances are fenced
Code changesNoneinitTransactions(), beginTransaction(), commitTransaction()
Consumer setting neededNoneisolation.level=read_committed to hide aborted records
OverheadNegligibleExtra 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-captured event written twice would trigger two settlements downstream.
  • Order and inventory events: duplicate stock-reserved events 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=1 for performance without noticing that it silently disables idempotence.
  • Raising max.in.flight.requests.per.connection above 5 for throughput, with the same silent effect.
  • Resending in the send callback or a catch block, 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=0 to “avoid duplicates”. With idempotence this is unnecessary, and it turns every transient error into a lost record.

10. Best Practices

  • Set enable.idempotence=true explicitly so conflicting settings fail at startup.
  • Leave retries and max.in.flight.requests.per.connection at their defaults, and bound retry time with delivery.timeout.ms.
  • Never resend from application code; on a final failure, log, alert, or fall back to an outbox table.
  • Check the ProducerConfig values log once per service to confirm enable.idempotence = true.
  • Use a transactional.id when 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