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.
  • seq matches 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.

Sequence of an idempotent-producer retry. The producer, PID 42, sends batch seq 0 with records A, B, C to partition P0. The broker appends it and records last seq 0 for PID 42 on P0, then crashes before the acknowledgement leaves. The producer times out and resends the identical batch. The broker now leading P0, whether the restarted broker or a follower that took over, finds seq 0 among its cached batches for PID 42, drops the batch, and acknowledges with the original offset, so the log holds A, B, C exactly once.
A retry the broker has already written is acknowledged, not appended The dedup check is a lookup per (PID, partition). In step 3 the broker answering may be the same broker after a restart or, more often with acks=all, a follower that became leader. Either way it has the register, because (PID, seq) sits in every batch header in the replicated log itself.
enable.idempotence=true
# Automatically forces: acks=all, max.in.flight.requests.per.connection≤5, retries=MAX_INT

Layer 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.id is 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"   │
                       └──────────────────────────────────┘
ThingValue
Inputorders-placed; the app is about to read message #42
Outputsorders (partition P0), invoices (partition P2)
Consumer groupg1; its bookmark (offset) lives in __consumer_offsets
Producer nametransactional.id = "billing-0"
Coordinatorhash("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()

  1. The producer asks "who coordinates billing-0?" (FindCoordinator) and gets Broker 3.
  2. It asks Broker 3 for an ID (InitProducerId). Broker 3's records say billing-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.
  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 pending

A 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 #42

The two messages go to two different coordinators, often on different brokers:

CoordinatorPicked byJobMessage it gets
Transaction coordinator (Broker 3)hash("billing-0")Decides commit or abortAddOffsetsToTxn: "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 bookmarksTxnOffsetCommit: 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                           ← done

The 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?

CrashWhat happensResult
A. App dies after ④, before commitThe 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 startsThe 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-writeThe 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 ✅
Sequence diagram of one transactional consume-transform-produce cycle across five participants: the producer, the transaction coordinator, the orders partition, the invoices partition, and __consumer_offsets. Init: the producer sends InitProducerId with its transactional.id; the coordinator bumps the epoch and first aborts any prior open transaction using the old epoch, then returns PID 88, epoch 3. beginTransaction is local only. Write: the producer sends AddPartitionsToTxn for orders-P0 and invoices-P2, sends records to orders and to invoices tagged PID 88 epoch 3, then sends AddOffsetsToTxn for group g1 plus TxnOffsetCommit, and the offsets are written to __consumer_offsets tagged PID 88 epoch 3. Commit: the producer calls commitTransaction, which sends EndTxn commit=true; the coordinator appends PREPARE_COMMIT to __transaction_state, replicated and durable; then in parallel sends WriteTxnMarker to every enlisted partition, each of which appends a COMMIT control record; then appends COMPLETE_COMMIT to __transaction_state and replies committed.
One transaction: enlist every partition, then commit them all with one durable record The transaction is decided the moment PREPARE_COMMIT is durable in __transaction_state; the marker fan-out after it can be resumed by a new coordinator, but never reversed.

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-P2 and g1's offsets partition each receive a marker.

What readers see

A consumer's isolation.level decides whether it waits for the marker:

Recordread_uncommitted (default)read_committed
Data with no marker yetDelivered right awayHeld back until the marker arrives
Data followed by COMMITDeliveredDelivered
Data followed by ABORTDelivered anyway; the app never knows it was abortedSkipped
The marker itselfNever shown to the appNever 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 retried

The 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:

StateIn the example
OngoingSteps ③–⑤: partitions being registered, data being written
PrepareCommit / PrepareAbortStep ⑥a: decided, markers not all delivered yet. Point of no return.
CompleteCommit / CompleteAbortStep ⑥c: every partition has its marker. Done.

Last Stable Offset (LSO)

A partition log with four records. Offset 0, record A, no transaction. Offsets 1 and 2, records B and C, belong to transaction txn-1, which is open. Offset 3, record D, no transaction. While txn-1 is open the last stable offset is 1, blocked by the open transaction, so a read_committed consumer sees only A — not even D, which is not in any transaction. After txn-1 commits the LSO advances to 4 and the consumer sees A, B, C and D.
read_committed stops at the first open transaction — even for records outside it