Learn Labs
Exactly-Once

Transactions & Exactly-Once

Atomic multi-partition writes, read_committed, consume-transform-produce, and fencing

The idempotent producer removes duplicates from retries. Transactions go further: a producer can write to several partitions and commit consumer offsets atomically: all of it becomes visible, or none of it. Combined, that gives exactly-once processing for pipelines that read from Kafka and write to Kafka. The book's Exactly-Once Semantics chapter is the deep dive.

Commit and abort

labs/exactly_once.py writes two records in a committed transaction and two in an aborted one, then reads with both isolation levels:

p = Producer({"bootstrap.servers": BOOTSTRAP, "transactional.id": "transfer-service-1"})
p.init_transactions()

p.begin_transaction()
p.produce("transfers", key="acct-1", value="debit acct-1 100")
p.produce("transfers", key="acct-2", value="credit acct-2 100")
p.commit_transaction()

p.begin_transaction()
p.produce("transfers", key="acct-1", value="debit acct-1 999")
p.produce("transfers", key="acct-3", value="credit acct-3 999")
p.flush()
p.abort_transaction()
read_uncommitted sees: ['credit acct-2 100', 'credit acct-3 999', 'debit acct-1 100', 'debit acct-1 999']
read_committed sees:   ['credit acct-2 100', 'debit acct-1 100']

The aborted records are in the log; a read_uncommitted consumer (the default) sees them. A read_committed consumer skips them, and never reads past an open transaction until it commits or aborts.

How it works

transactional.idstable identity across restarts, e.g. "ledger-writer-<partition-set>"init_transactions()registers with the transaction coordinator; bumps the epoch; fences older instancesbegin_transaction()produce(...)partitions are added to the transaction as they're written tocommit_transaction()coordinator writes COMMIT markers into every partition touched
producertxn coordinatorpartition Apartition Bread_committedinit_transactions()epoch bumpeddebit acct-1credit acct-2commit_transaction()COMMIT markerCOMMIT markerboth records, now visible
  • A transaction coordinator (a broker, chosen by hashing the transactional.id) tracks each transaction's state in the internal __transaction_state topic.
  • On commit or abort, the coordinator writes control records (markers) into every partition in the transaction. kafka-dump-log.sh shows them as isControl: true.
  • read_committed consumers buffer until they see the marker, then deliver or skip.
kafka-dump-log.sh --files .../transfers-0/00000000000000000000.log --print-data-log
baseOffset: 1 ... producerId: 1 producerEpoch: 1 isTransactional: true isControl: true
| offset: 1 ... endTxnMarker: COMMIT coordinatorEpoch: 0

Each marker occupies an offset of its own. That's why offsets in transactional topics have gaps, and why "lag" on them never quite reaches zero in some tools.

Consume-transform-produce

The real use case: read from one topic, write results to another, and commit the input offsets in the same transaction, so the output and the progress can never disagree:

while msgs := consumer.consume(num_messages=10, timeout=5):
  producer.begin_transaction()
  for m in msgs:
      producer.produce("ledger", key=m.key(), value=transform(m.value()))
  producer.send_offsets_to_transaction(consumer.position(consumer.assignment()),
                                       consumer.consumer_group_metadata())
  producer.commit_transaction()

# consume-transform-produce: 30 ledger entries written in 3 transactions

If the process crashes mid-batch, the transaction aborts: the output records are discarded and the offsets weren't committed, so the batch is reprocessed from scratch. Downstream read_committed consumers see each result exactly once.

Zombie fencing

A process that froze (GC pause, network partition) may wake up after a replacement took over. Without protection, both would write. The producer epoch prevents it: init_transactions() on the new instance bumps the epoch for that transactional.id, and the old one's next transactional request is rejected:

old = Producer({..., "transactional.id": "fence-demo"}); old.init_transactions()
new = Producer({..., "transactional.id": "fence-demo"}); new.init_transactions()
old.begin_transaction(); old.produce(...); old.commit_transaction()

zombie producer fenced: _FENCED

This is the fencing-token idea from the Redis module's locks lesson, built into the protocol.

What exactly-once doesn't cover

Other costs: transactions add latency (markers, coordinator round trips), so batch several records per transaction; and read_committed consumers stall behind long-open transactions, so keep transactions short (transaction.timeout.ms, 60 s by default, aborts stuck ones).

Lab

  1. Run exactly_once.py.
  2. Dump a transfers partition with kafka-dump-log.sh and find the control batches (isControl: true) for the commit and the abort.
  3. Change the consume-transform-produce loop to raise an exception after the second produce() in the second batch (without committing). Run it, rerun it without the fault, and confirm ledger still holds exactly 30 entries for read_committed.
  4. List open transactions: kafka-transactions.sh --bootstrap-server localhost:19092 list.

On this page