Exactly-Once Semantics: The Two-Layer Mechanism
Layer 1 — Idempotent Producer
The problem: producer sends a batch, broker writes it, broker crashes before ack. Producer retries — broker receives the same batch again and writes a duplicate.
The mechanism: Each producer gets a PID (plus a producer epoch) at session start. Every batch carries a monotonically increasing sequence number (per partition), written into the batch header in the log. Every replica of the partition — leader and followers alike — keeps a register of (PID, partition) → metadata of the last 5 batches. It is held in memory for O(1) lookups, but it is derived from the log, not stored only in memory: it survives a restart (rebuilt from a snapshot plus log replay) and a failover (followers build it as they replicate).
On each produce request the leader compares the batch's sequence number against that register:
seq == last_seq + 1→ the next batch in order: append it.seqmatches one of the 5 cached batches → a retry of something already written: don't append, ack with the original offset.- Any other gap →
OutOfOrderSequenceException.
The window is 5 batches because max.in.flight.requests.per.connection ≤ 5: at most 5 unacked batches can be retried, so the broker never needs to remember more.
enable.idempotence=true
# Automatically forces: acks=all, max.in.flight.requests.per.connection≤5, retries=MAX_INTLayer 2 — Transactional API
The problem: consume-transform-produce atomically across multiple partitions — the output writes to orders and invoices and the input offset commit to __consumer_offsets must all become visible together, or none of them do.
In plain terms: for one input message ("order #42 placed") the app makes three separate writes: (1) "order confirmed" to orders, (2) an invoice to invoices, (3) a bookmark ("I've finished #42") to __consumer_offsets. Without a transaction, a crash between any two of them leaves things half-done:
| Crash after… | Result |
|---|---|
| (1), before (2) | Order with no invoice |
| (1) and (2), before (3) | Bookmark not moved → #42 reprocessed → duplicate order and invoice |
| (3), before (1) and (2) | Bookmark says done, nothing written → order lost |
A transaction puts all three writes in one box. On commit they all appear together. On a crash or abort none of them count: anything already written is marked aborted, and read_committed consumers skip it. The bookmark didn't move, so #42 is redone cleanly. The key point is that the bookmark is itself a Kafka write, so "I did the work" and "I recorded that I did it" can never get out of sync. That is what turns at-least-once into exactly-once.
The Transaction Coordinator
How a producer finds its coordinator:
- Kafka has an internal topic,
__transaction_state(50 partitions, replication factor 3 by default), used only for transaction bookkeeping. - The producer's
transactional.idis hashed to pick one of those 50 partitions. - The broker that leads that partition is the coordinator for all of this producer's transactions.
- Different
transactional.ids hash to different partitions, so the coordinator work is spread across the cluster. There is no single global coordinator to become a bottleneck.
One Message, End to End
The whole mechanism, start to finish, using one running example.
The setup
┌──────── billing-service ─────────┐
orders-placed ──────►│ CONSUMER → logic → PRODUCER │──────► orders
(input topic) │ group: g1 transactional.id│──────► invoices
│ = "billing-0" │
└──────────────────────────────────┘| Thing | Value |
|---|---|
| Input | orders-placed; the app is about to read message #42 |
| Outputs | orders (partition P0), invoices (partition P2) |
| Consumer group | g1; its bookmark (offset) lives in __consumer_offsets |
| Producer name | transactional.id = "billing-0" |
| Coordinator | hash("billing-0") → __transaction_state partition 7 → its leader, say Broker 3 |
One app plays both roles. The bookmark belongs to the consumer half ("where am I in the input"). A producer has no bookmark of its own. But only the producer can run a transaction, so the consumer hands its bookmark to the producer to carry inside the transaction. A producer-only app, such as a web server emitting click events, has no bookmark at all.
Part 1 — The app starts: initTransactions()
- The producer asks "who coordinates
billing-0?" (FindCoordinator) and gets Broker 3. - It asks Broker 3 for an ID (
InitProducerId). Broker 3's records saybilling-0 → PID 88, last epoch 2. It bumps the epoch to 3. If the previous run left a transaction open, it aborts that first. It returns PID 88, epoch 3. - Any older instance still running with epoch 2 is now locked out: every broker rejects its writes and commits with
ProducerFencedException.
Part 2 — Processing message #42 (happy path)
① consumer.poll() → gets #42 "Order #42 placed, ₹500"
② producer.beginTransaction() → local only, nothing sent yet③ Register the output partitions (AddPartitionsToTxn). Data writes go straight to each partition's leader, so the coordinator never sees them. It needs this list to know where to put COMMIT/ABORT markers later. The producer registers before the first write, so a crash can never leave a partition holding data the coordinator doesn't know about.
Producer → Broker 3: "billing-0 will write to orders-P0 and invoices-P2"
Broker 3 saves: {PID 88, epoch 3, partitions: [orders-P0, invoices-P2], state: Ongoing}④ Write the outputs, directly to each partition's leader:
orders-P0: [ "order #42 confirmed" ] (PID 88, epoch 3) ← in the log, but pending
invoices-P2: [ "invoice #42, ₹500" ] (PID 88, epoch 3) ← in the log, but pendingA read_committed consumer of orders can't see these yet. It waits at this point (see Last Stable Offset below).
⑤ Put the bookmark in the same transaction (sendOffsetsToTransaction). Normally the consumer saves its bookmark itself (commitSync()), as a separate write that takes effect immediately. Whichever order you choose, a crash between "save output" and "save bookmark" breaks something. Bookmark first, then crash: #42 is skipped and lost. Output first, then crash: #42 is redone and duplicated. So the bookmark goes in the transaction instead:
Producer → Broker 3 (txn coordinator): "this txn also touches g1's offsets" (AddOffsetsToTxn)
Producer → g1's group coordinator: "g1: next read is #43" (TxnOffsetCommit)
__consumer_offsets: [ g1 → #43 ] ← written, but pending; g1's official bookmark is still #42The two messages go to two different coordinators, often on different brokers:
| Coordinator | Picked by | Job | Message it gets |
|---|---|---|---|
| Transaction coordinator (Broker 3) | hash("billing-0") | Decides commit or abort | AddOffsetsToTxn: "the bookmark is part of this transaction". This is step ③ again: g1's offsets partition joins the list, so it gets a marker too. |
| Group coordinator (say Broker 5) | hash("g1") | Stores g1's bookmarks | TxnOffsetCommit: the bookmark itself, "next read #43". It's the same kind of write as commitSync(), but sent by the producer and tagged with PID 88, epoch 3. |
Because of that tag, Broker 5 writes the record but holds it as pending. On the COMMIT marker the bookmark becomes #43. On ABORT the record is discarded and the bookmark stays at #42.
⑥ Commit (commitTransaction()):
a) Broker 3 writes PREPARE_COMMIT to __transaction_state ← point of no return
b) Broker 3 writes a COMMIT marker into orders-P0, invoices-P2,
and g1's __consumer_offsets partition
c) Broker 3 writes COMPLETE_COMMIT ← doneThe moment the markers land, all three become real together: the order is visible, the invoice is visible, and g1's bookmark moves to #43. Then the loop polls #43.
Part 3 — What if it crashes?
| Crash | What happens | Result |
|---|---|---|
| A. App dies after ④, before commit | The restarted app calls initTransactions(). Broker 3 sees epoch 3's transaction is still open, writes ABORT markers to all three partitions, and hands out epoch 4. read_committed consumers skip the aborted order and invoice. The bookmark is still #42, so #42 is processed again and committed. (The abort is forced rather than a commit because the app never asked to commit. Left open, the transaction would block read_committed readers until transaction.timeout.ms, 1 minute by default.) | One order, one invoice ✅ |
| B. Coordinator (Broker 3) dies after PREPARE_COMMIT | __transaction_state partition 7 is replicated, so another broker becomes leader and therefore coordinator. It replays the log, sees PREPARE_COMMIT, and finishes writing the markers. | Once prepared, a commit always completes ✅ |
| C. Zombie: the app freezes in a GC pause and a replacement starts | The replacement gets epoch 4 and the frozen instance's open transaction is aborted. When the old instance wakes up and commits as epoch 3, it gets ProducerFencedException. | Only the replacement's work counts; charged once ✅ |
| D. A data partition's leader dies mid-write | The producer retries to the new leader, which already has the PID 88 / sequence-number register (Layer 1), so the batch isn't written twice. | No duplicate ✅ |
What a commit marker actually is
In one line: a commit marker is a tiny "this transaction is done" note that the coordinator writes into each partition's log, right after the transaction's data.
What it looks like in the log
Continuing the example, here is orders-P0 before and after step ⑥:
Before commit:
offset 100: "order #42 confirmed" (PID 88) ← pending, readers wait here
After commit:
offset 100: "order #42 confirmed" (PID 88)
offset 101: [COMMIT · PID 88] ← the marker
→ offset 100 is now visible- It's a real record: it's appended to the log and takes up an offset (101 here), like any message.
- But it's not your data: a flag in the batch header marks it as a control record. Kafka uses it internally and never hands it to your app.
- It's tiny: just which producer (PID + epoch), which coordinator (coordinator epoch), and the verdict (COMMIT or ABORT).
- Each partition gets its own:
orders-P0,invoices-P2andg1's offsets partition each receive a marker.
What readers see
A consumer's isolation.level decides whether it waits for the marker:
| Record | read_uncommitted (default) | read_committed |
|---|---|---|
| Data with no marker yet | Delivered right away | Held back until the marker arrives |
| Data followed by COMMIT | Delivered | Delivered |
| Data followed by ABORT | Delivered anyway; the app never knows it was aborted | Skipped |
| The marker itself | Never shown to the app | Never shown to the app |
So exactly-once only holds end to end if the downstream consumers use read_committed. How far a read_committed reader may go is tracked by the Last Stable Offset (next section).
Why commit in two phases?
The problem: the coordinator has to write markers into 3 different partitions, on 3 different brokers. It can't do that in one atomic step. Suppose it crashed after marking orders-P0 but before invoices-P2: the order would be committed, the invoice undecided, and nobody would know which way the transaction was meant to go.
The fix: it decides first, then delivers.
Phase 1 — decide: write PREPARE_COMMIT to __transaction_state (replicated)
→ the decision is now saved and can never change
Phase 2 — deliver: write a COMMIT marker into each partition
→ if this is interrupted, it is simply retriedThe decision is saved before any marker goes out, so a crash during delivery can only delay the commit. It can never leave the transaction half-done.
The transaction's states
The coordinator records each transaction's progress in __transaction_state:
| State | In the example |
|---|---|
| Ongoing | Steps ③–⑤: partitions being registered, data being written |
| PrepareCommit / PrepareAbort | Step ⑥a: decided, markers not all delivered yet. Point of no return. |
| CompleteCommit / CompleteAbort | Step ⑥c: every partition has its marker. Done. |