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.
The first version of this lab didn't call flush() before
abort_transaction(), and read_uncommitted showed only the committed
records, as if aborts deleted data. They don't: librdkafka simply
discarded the still-buffered messages on abort, so they never reached a
broker. Records already sent before an abort stay in the log, marked
aborted. Any consumer that matters must use
isolation.level=read_committed.
How it works
- A transaction coordinator (a broker, chosen by hashing the
transactional.id) tracks each transaction's state in the internal__transaction_statetopic. - On commit or abort, the coordinator writes control records
(markers) into every partition in the transaction.
kafka-dump-log.shshows them asisControl: true. read_committedconsumers 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: 0Each 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 transactionsIf 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: _FENCEDThis is the fencing-token idea from the Redis module's locks lesson, built into the protocol.
What exactly-once doesn't cover
Exactly-once applies to Kafka → Kafka flows. The moment a consumer sends an email, charges a card, or writes to Postgres, Kafka's transaction can't include that side effect. A crash after the charge but before the commit means the batch is reprocessed and the card is charged twice. For external effects you're back to at-least-once plus idempotence (dedup keys, upserts), or storing offsets in the external system's own transaction.
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
- Run
exactly_once.py. - Dump a
transferspartition withkafka-dump-log.shand find the control batches (isControl: true) for the commit and the abort. - 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 confirmledgerstill holds exactly 30 entries forread_committed. - List open transactions:
kafka-transactions.sh --bootstrap-server localhost:19092 list.