Skip to content

AxonOps — AI-Native Control Plane for Open Source Data Platforms

Kafka Idempotent Producer

The idempotent producer prevents duplicate messages caused by producer retries within a single session. This document covers configuration and usage patterns.


Duplicate outcome with and without producer idempotence The idempotent producer assigns sequence numbers to records in each partition batch, allowing brokers to detect and deduplicate retries.


# Explicitly require idempotence
enable.idempotence=true

Idempotence is enabled by default when no conflicting configuration is present. If it is not set explicitly, a conflicting acks, retries, or max.in.flight.requests.per.connection value disables it. If enable.idempotence=true is explicit, the same conflict causes a ConfigException during producer construction.

When enabled, these settings are enforced:

ConfigurationRequired ValueReason
acksallAcknowledge after all current in-sync replicas have the record
retries> 0Allow retries
max.in.flight.requests.per.connection≤ 5Maintain sequence ordering

ComponentPurpose
Producer ID (PID)Unique identifier assigned on startup
Sequence NumberPer-partition counter advanced by the number of records in each batch
EpochFences zombie producers

The broker validates sequences:

ConditionResult
seq == expectedAccept, increment expected
seq < expectedDetect the duplicate and return the prior batch outcome
seq > expectedReject the gap with an out-of-order sequence error

CoveredNot Covered
Internal retries within one producer sessionProducer restart or a new PID
Network timeoutsMultiple producer instances
Transient broker failuresCalling send() again for the same logical record

Application Retries Are New Sends

Idempotence deduplicates retries performed internally by one producer instance. If application code handles an error by creating and sending the record again, Kafka treats it as a new send and it can create a duplicate.

For cross-session or cross-partition atomicity, use transactions.


Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
for (int i = 0; i < 100; i++) {
producer.send(new ProducerRecord<>("events", "key-" + i, "value-" + i),
(metadata, exception) -> {
if (exception != null) {
log.error("Send failed", exception);
}
});
}
}