Exactly-Once Semantics: Idempotence and Transactions
Senior level ยท The guarantee, the mechanism behind it, and the boundaries where it quietly stops applying.
Prerequisites
- !Producer acknowledgements and retries
- !Consumer offset commits
What You'll Learn
- 1State exactly what each of the three delivery guarantees promises and costs
- 2Explain how a producer id is used to reject duplicates at the broker
- 3Build a read-process-write loop whose output and offsets commit together
- 4Name the failures that still produce duplicates under exactly-once configuration
Three guarantees, one honest comparison
Every streaming system eventually faces the same question: what happens when the network drops an acknowledgement and the sender retries. The answer is one of three guarantees, and the differences are much larger in practice than they sound on a slide.
| Guarantee | What can go wrong | Typical mechanism | Cost |
|---|---|---|---|
| At-most-once | Records are lost, never duplicated | No retries, fire and forget | Lowest latency, unacceptable for state changes |
| At-least-once | Records are duplicated, never lost | Retries plus consumer offset commits | Cheap, pushes deduplication onto every reader |
| Exactly-once | Neither loss nor duplication inside Kafka | Idempotent producer plus transactions | Higher latency and a constrained programming model |
At-least-once is the honest description of most production pipelines. Retries guarantee delivery and create duplicates, so consumers must treat every record as potentially repeated. Exactly-once removes that burden inside the Kafka cluster by making the commit of output records and input offsets a single atomic event. It does not make your side effects to databases, email providers or payment gateways idempotent, and confusing the two is the most expensive mistake in this area.
What the idempotent producer actually does
Turning on enable.idempotence gives the producer a broker-assigned producer id and a per-partition sequence number on every record. The broker keeps the last sequence it accepted for each producer id and partition, and uses that to decide what to do with an incoming append.
Properties props = new Properties();
props.put("bootstrap.servers", "kafka1:9092,kafka2:9092,kafka3:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("enable.idempotence", true); // assigns a PID and per-partition sequences
props.put("acks", "all");
props.put("retries", Integer.MAX_VALUE);
// Ordering is preserved because the broker rejects out-of-order appends
props.put("max.in.flight.requests.per.connection", 5);
Producer<String, String> producer = new KafkaProducer<>(props);
The broker's decision table is small. If the incoming sequence is exactly one past the stored value it appends and advances the counter. If it matches or is below the stored value the record is a duplicate from a retry and is dropped without error. If it jumps ahead the record is out of order and the broker returns OutOfOrderSequenceException so the producer can resynchronise rather than corrupt the log.
Two limitations matter. Idempotence only protects against duplicates introduced by the producer's own retries within a single session, and it says nothing about a consumer that crashes after applying a record but before committing its offset. For that second case you need transactions.
โ ๏ธIdempotence is not end to end
Transactions: one atomic decision across topics
A transactional producer writes to several topics and commits consumer offsets as a single unit. Setting transactional.id is what makes this safe across restarts: the id is a durable identity, so a replacement process fencing the old one can resolve any transaction the crashed instance left open.
Properties props = new Properties();
props.put("bootstrap.servers", "kafka1:9092,kafka2:9092");
props.put("transactional.id", "order-funnel-1"); // stable per logical instance
props.put("enable.idempotence", true);
props.put("acks", "all");
props.put("transaction.timeout.ms", 60000);
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
producer.initTransactions(); // fences stale instances and opens the coordinator link
try {
producer.beginTransaction();
producer.send(new ProducerRecord<>("orders", orderId, orderJson));
producer.send(new ProducerRecord<>("inventory", skuId, decrementJson));
producer.send(new ProducerRecord<>("payments", paymentId, paymentJson));
producer.sendOffsetsToTransaction(offsetsFromPoll, consumerGroupId);
producer.commitTransaction();
} catch (ProducerFencedException | InvalidProducerEpochException fatal) {
throw new IllegalStateException("another instance owns this transactional id", fatal);
} catch (RuntimeException recoverable) {
producer.abortTransaction();
}
Abort is mandatory on any recoverable failure. A transaction left open past transaction.timeout.ms is forcibly aborted by the coordinator, but until that happens read-committed consumers simply stop seeing new records for that producer, which looks like an outage rather than a bug.
Isolation levels on the read side
Producing transactionally is only half the contract; readers must agree on what they are allowed to see.
| isolation.level | Sees aborted records | Sees open transactions | Typical reader |
|---|---|---|---|
| read_uncommitted | Visible until aborted | Yes, immediately | Analytics tolerating later disappearance |
| read_committed | Filtered permanently | No, only after commit | Anything feeding state or money |
read_uncommitted is the default and gives the lowest latency because nothing waits on a commit. It also means a consumer can read a record, act on it, and then watch that record vanish when the transaction aborts. read_committed makes the consumer wait behind the transaction marker, which trades a little latency for a log that never lies about what has been finalised.
The read-process-write loop, complete
KafkaConsumer<String, String> consumer = buildConsumer(); // read_committed, auto commit off
KafkaProducer<String, String> producer = buildTransactional(); // transactional.id set
producer.initTransactions();
while (true) {
ConsumerRecords<String, String> batch = consumer.poll(Duration.ofMillis(200));
if (batch.isEmpty()) continue;
try {
producer.beginTransaction();
for (ConsumerRecord<String, String> record : batch) {
Output out = transform(record.value());
producer.send(new ProducerRecord<>("output-topic", record.key(), out.encode()));
}
// Offsets commit inside the same transaction as the output records
producer.sendOffsetsToTransaction(offsetsOf(batch), consumer.groupMetadata());
producer.commitTransaction();
} catch (KafkaException e) {
producer.abortTransaction();
// Do not swallow: loop back and re-poll the same records
log.warn("transaction aborted, batch will be reprocessed", e);
}
}
The critical line is sendOffsetsToTransaction. Output and progress commit together, so a crash after processing but before commit replays the batch, while a crash after commit skips it. Either the batch appears in the output exactly once or not at all.
Where the guarantee stops
Four boundaries are worth stating explicitly in an interview. Work that leaves Kafka, such as a call to a payment API, is outside the transaction and needs its own idempotency key. A rebalance during an open transaction forces an abort, so long handler work and frequent rebalances combine into repeated replays. transaction.timeout.ms shorter than your worst-case processing time converts every slow batch into an abort loop. Finally, a reader configured with read_uncommitted on a transactional topic ignores your guarantee entirely.
How a transaction actually commits
A transactional producer registers with a coordinator that assigns it a producer id and a monotonically increasing epoch. That epoch is what fences zombies: when a new producer with the same transactional id registers, the epoch is raised and any subsequent request from the old instance carrying a stale epoch is rejected. Without this mechanism, a slow or paused old instance could resume writing after a failover and interleave records with the new writer, producing a stream that neither writer fully owns.
Inside a transaction, each batch of records the producer sends is buffered with the batch of input offsets that the application acknowledges via sendOffsetsToTransaction. The broker writes control markers at the start and end of the transaction, and until the end marker lands, every record in the transaction is invisible to read_committed consumers. If the process crashes before the end marker, the coordinator eventually aborts the transaction and the records become permanently invisible; if the end marker lands before the crash, the records become visible together with the offset advance and the batch is complete.
The practical consequence is that a crash mid-batch causes a full reprocess of that batch, not a partial one. That is exactly-once from the consumer's point of view, but it is not zero-latency: the abort path involves a coordinator round trip and a consumer rewind, so a stream of crashes turns into a stream of aborts. Monitoring abort rate per minute is the cheapest early warning that a timeout is misconfigured or a rebalance is happening more often than the transaction cadence can absorb.
The interaction with consumer groups is the part teams miss most often. When a rebalance moves a partition while a transaction is open, the transaction cannot commit because the input offsets being acknowledged now belong to a different member. The coordinator aborts, the new member reprocesses from the last committed offset, and the output from the aborted transaction never becomes visible. This is correct behavior, but it means every rebalance under a transactional workload costs a reprocess, which is another argument for static membership and cooperative assignment on any group that feeds a transactional sink.
Choosing between idempotence alone and full transactions
Idempotence alone is sufficient when a service reads, transforms and writes without needing the output and the input offset to advance atomically. A metrics aggregator that occasionally reprocesses a record and emits a slightly stale average is fine with idempotence, because the duplicate is harmless and the latency of a reprocess is invisible. Transactions are needed when a duplicate is not harmless: when the output feeds a billing system, when the same offset must never be acknowledged without the corresponding output being visible, or when two output topics must be updated in lockstep.
The cost of transactions is not only throughput. It is operational complexity: transactional ids must be unique per instance and stable across restarts, timeouts must be sized against the worst-case batch, and every downstream consumer must be set to read_committed. A team that turns on transactions without turning on read_committed on its consumers has paid the full cost and received none of the guarantee, because the consumers will still see aborted records and process them as if they were committed.
Common Mistakes
Claiming exactly-once once enable.idempotence is switched on
Fix: Idempotence covers producer retries only. Duplicates from consumer replays remain until output and offsets commit in one transaction.
Calling external systems inside the transaction and assuming they are covered
Fix: Kafka transactions span Kafka only. Pass an idempotency key to the external API or write an outbox record and let a separate worker call it.
Leaving readers on the default isolation level after enabling transactions
Fix: Set isolation.level to read_committed on every consumer of a transactional topic, otherwise aborted records are visible and later disappear.
Processing a batch for longer than transaction.timeout.ms
Fix: Either shorten the batch, raise the timeout to cover the worst case, or move heavy work out of the transaction and into an idempotent follow-up step.
Best Practices
- Keep transactional.id stable and unique per logical instance so restarts fence rather than duplicate
- Set isolation.level to read_committed at the same time you turn on transactional production, not later
- Make the transform inside the transaction pure so a replay produces byte-identical output
- Chart transaction aborts per minute; a rising abort rate is the first sign of timeout or rebalance trouble
Interview Questions
Q1: Difference between an idempotent producer and a transactional producer?
Idempotence prevents duplicate appends from one producer's retries using a producer id and per-partition sequence numbers. Transactions make several sends and an offset commit atomic across topics and restarts, and they imply idempotence.
Q2: What does isolation.level=read_committed change for a consumer?
The consumer only sees records belonging to committed transactions, waits behind open ones, and never sees aborted records. It costs latency because reads stall on the transaction marker.
Q3: A transaction times out mid-processing. What happens?
The coordinator aborts it, committed consumers never saw its records, and the consumer reprocesses the batch on the next poll. If timeouts repeat, throughput collapses into a loop of aborts.
Q4: How do you handle a rebalance while a transaction is open?
The transaction aborts because ownership of the input partitions changes. Use static membership to reduce rebalance frequency, keep batches short, and treat the abort plus replay as normal rather than exceptional.
Q5: What are the limits of exactly-once in Kafka?
It covers reads and writes inside the cluster. Side effects elsewhere, work done by other consumer groups, and readers not set to read_committed all sit outside the guarantee and must be idempotent on their own.
Key Takeaways
- At-most-once loses, at-least-once duplicates, exactly-once does neither but constrains how you write the application
- A producer id plus per-partition sequence numbers let the broker drop duplicates and reject out-of-order appends
- sendOffsetsToTransaction ties progress to output so a crash either replays a whole batch or skips it, never splits it
- isolation.level controls what readers see, and read_uncommitted defeats a transactional producer by itself
- External side effects, rebalances and transaction timeouts are the three places exactly-once quietly stops applying