How Kafka Transactions Work Internally
Kafka transactions let a producer write records to several partitions and topics, and commit consumer offsets, as one atomic unit: either all of it becomes visible to read_committed consumers, or none of it does. They are the foundation of Kafka’s exactly-once processing and of Kafka Streams’ exactly_once_v2 guarantee.
This article explains how Kafka transactions work internally: the transactional ID, producer epoch and zombie fencing, the transaction coordinator and its log, commit markers, the last stable offset, and what read_committed consumers actually do. It finishes with a consume–transform–produce example in Java and the Spring Boot equivalent.
1. What Are Kafka Transactions?
A Kafka transaction groups several operations of one producer:
- writes to any number of partitions, in any number of topics, and
- commits of consumer-group offsets (
sendOffsetsToTransaction()).
The producer commits or aborts them together. Consumers that use isolation.level=read_committed see the records of a committed transaction and never see records of an aborted one. Transactions are a Kafka-internal mechanism: they do not span databases or other systems.
2. Why Transactions Are Needed
Consider a service that reads orders, writes an enriched record to orders-enriched and an audit record to audit, then commits its input offset. Without transactions, a crash between these steps leaves partial results:
- The enriched record is written but the offset is not committed: after restart, it is written again (duplicate).
- The offset is committed but the audit record is not written: the audit entry is lost.
- An old instance that was paused by a long GC wakes up and keeps writing after a new instance took over: a zombie produces duplicates.
Transactions solve all three: the writes and the offset commit are atomic, and zombies are fenced off.
3. Building Blocks
| Component | Role |
|---|---|
transactional.id | A stable name for the logical producer, configured by you. It stays the same across restarts of the same logical instance. |
| Producer ID and epoch | The cluster maps the transactional ID to a producer ID. Each new session with the same transactional ID gets a higher epoch, which is what fences zombies. |
| Transaction coordinator | A broker-side module that manages the state of each transactional ID. Every broker runs one; a transactional ID is assigned to the coordinator that leads its partition of the transaction log. |
__transaction_state | An internal, replicated, compacted topic (50 partitions by default) where coordinators persist transaction state, so a new coordinator can take over after a broker failure. |
| Control records (markers) | Special COMMIT or ABORT records written into every partition the transaction touched. They are not returned to applications; consumers use them to decide what to show. |
| Last stable offset (LSO) | Per partition, the offset before which all transactions are decided. read_committed consumers read only up to the LSO. |
4. How a Transaction Works, Step by Step
- Find the coordinator and initialise. On
initTransactions(), the producer locates the coordinator for its transactional ID and sendsInitProducerId. The coordinator returns the producer ID with an incremented epoch and completes or aborts any transaction the previous instance left open. - Begin.
beginTransaction()is local; nothing is sent to the cluster yet. - Send. Before the first record reaches a partition, that partition is registered with the coordinator, so the coordinator knows where markers must go later. Records are written to the partition logs immediately, but marked as part of an open transaction.
- Add offsets.
sendOffsetsToTransaction()registers the consumer group with the transaction and sends the input offsets to the group coordinator as transactional offset commits. They take effect only if the transaction commits. - Commit (two phases).
commitTransaction()sendsEndTxn. The coordinator first writesPREPARE_COMMITto__transaction_state; from this point the commit is guaranteed. It then writes a COMMIT marker into every registered partition, including the__consumer_offsetspartition, and finally logsCOMPLETE_COMMIT.
An abort follows the same path with ABORT markers. Kafka 4.0 introduced a strengthened transaction protocol (KIP-890, “Transactions Server-Side Defense”), enabled once a cluster upgrade to 4.0 is finalized: with 4.0 producer clients, the epoch is bumped on every transaction, so a late retry from one transaction cannot be written into the next. The overall flow above is unchanged.
5. Zombie Fencing
A zombie is an old producer instance that is still running, for example after a long GC pause or a network partition, while a replacement already started with the same transactional.id. When the replacement calls initTransactions(), the coordinator bumps the epoch. Any later request from the zombie carries the old epoch and is rejected; the zombie’s client throws ProducerFencedException and must close.
Fencing only works if the same logical instance always uses the same transactional ID, and two live instances never share one. Spring for Apache Kafka builds transactional IDs from a configured prefix for this reason.
6. What read_committed Consumers See
Records of open transactions sit in the partition log next to non-transactional records. A consumer’s isolation.level decides what it gets:
read_uncommitted(the default) returns everything, including records of transactions that are still open or were later aborted.read_committedreads only up to the last stable offset, the first offset of the oldest still-open transaction. Records of aborted transactions are filtered out using the broker’s aborted-transaction index, and control records are never returned.
A consequence: one long-running or stuck open transaction holds back the LSO, and read_committed consumers of that partition stop advancing, even for non-transactional records written later. The coordinator aborts transactions that exceed transaction.timeout.ms, which bounds this delay.
7. Java Example: Consume, Transform, Produce
An enrichment service reads orders and writes orders-enriched exactly once. The output records and the input offsets commit in one transaction:
Properties pp = new Properties();
pp.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
pp.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "order-enricher-" + instanceId); // stable per instance
pp.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
pp.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
Properties cp = new Properties();
cp.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
cp.put(ConsumerConfig.GROUP_ID_CONFIG, "order-enricher");
cp.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); // offsets go through the transaction
cp.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed"); // never read aborted input
cp.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
cp.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
KafkaProducer<String, String> producer = new KafkaProducer<>(pp);
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(cp);
consumer.subscribe(List.of("orders"));
producer.initTransactions(); // fences older instances
while (running) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
if (records.isEmpty()) continue;
try {
producer.beginTransaction();
Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
for (ConsumerRecord<String, String> r : records) {
producer.send(new ProducerRecord<>("orders-enriched", r.key(), enrich(r.value())));
offsets.put(new TopicPartition(r.topic(), r.partition()), new OffsetAndMetadata(r.offset() + 1));
}
producer.sendOffsetsToTransaction(offsets, consumer.groupMetadata());
producer.commitTransaction();
} catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {
producer.close(); // cannot recover: another instance owns this transactional.id
throw e;
} catch (KafkaException e) {
producer.abortTransaction(); // output discarded, offsets not committed
rewindToCommitted(consumer); // seek each assigned partition back to its committed offset
}
}
consumer.groupMetadata()passes the group generation, so the coordinator rejects offsets from a consumer that has already lost its partitions in a rebalance.- After an abort, the consumer must seek back to the last committed offsets; otherwise its in-memory position has already moved past the aborted batch.
- No send callbacks are needed: a failed send inside a transaction makes
commitTransaction()throw, as theKafkaProducerJavadoc describes.
8. Transactions in Spring Boot
In Spring Boot, setting a transaction ID prefix is enough to make the producer transactional. Spring Boot then auto-configures a KafkaTransactionManager and wires it into the listener container, which starts a transaction before calling the listener and sends the consumed offsets to it:
spring:
kafka:
bootstrap-servers: localhost:9092
producer:
transaction-id-prefix: order-enricher-
consumer:
group-id: order-enricher
isolation-level: read_committed
@Component
public class OrderEnricherListener {
private final KafkaTemplate<String, String> kafkaTemplate;
public OrderEnricherListener(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@KafkaListener(topics = "orders")
public void onOrder(ConsumerRecord<String, String> record) {
// Runs inside the container's Kafka transaction: this send and the input offset
// commit together, or are both rolled back if the method throws
kafkaTemplate.send("orders-enriched", record.key(), enrich(record.value()));
}
}
Outside a listener, kafkaTemplate.executeInTransaction(t -> ...) or a @Transactional method with the Kafka transaction manager runs a local transaction.
9. Important Configuration
| Property | Where | Default | Meaning |
|---|---|---|---|
transactional.id | Producer | none | Enables transactions; must be stable per logical instance |
transaction.timeout.ms | Producer | 60000 | The coordinator aborts a transaction open longer than this |
isolation.level | Consumer | read_uncommitted | Set read_committed to hide aborted and open transactions |
transaction.max.timeout.ms | Broker | 900000 | Upper limit for a producer’s transaction.timeout.ms |
transaction.state.log.replication.factor / .min.isr | Broker | 3 / 2 | Durability of __transaction_state |
transactional.id.expiration.ms | Broker | 604800000 (7 days) | An unused transactional ID’s state is removed after this time |
10. Limitations and Costs
- Kafka only. Database writes, REST calls and emails are outside the transaction; use an idempotent consumer or the outbox pattern for those.
- Overhead per transaction. Each commit costs coordinator round trips and a marker per partition, so commit batches of records, not single records.
- Higher end-to-end latency for
read_committedconsumers, which see records only after the commit. - One open transaction per producer; a producer instance cannot interleave transactions.
11. Common Mistakes
- Leaving consumers on
read_uncommitted, so aborted records are processed anyway. - Generating a random
transactional.idon every start, which disables zombie fencing. - Committing offsets with the consumer (
commitSync()) instead ofsendOffsetsToTransaction(), which breaks atomicity. - Not seeking back after
abortTransaction(), which skips the aborted input. - Very long transactions, which hold back the LSO and stall every
read_committedreader of those partitions.
12. Summary
A Kafka transaction makes a producer’s writes to several partitions and its consumer-offset commits atomic. The transactional ID maps to a producer ID whose epoch fences zombies; the transaction coordinator tracks each transaction in __transaction_state, writes a two-phase decision, and places COMMIT or ABORT markers in every partition involved. read_committed consumers read up to the last stable offset and skip aborted records. Use transactions for Kafka-to-Kafka exactly-once processing, keep them short, and handle anything outside Kafka with idempotent consumers or an outbox.
13. Related Reading
- Kafka Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once
- Idempotent Producer in Kafka
- Transactional Outbox Pattern with Kafka
14. References
- Apache Kafka 4.4 Javadoc: KafkaProducer (transactions)
- Apache Kafka design: Message delivery semantics
- Apache Kafka: Upgrade notes (KIP-890 transaction protocol in 4.0)
- Apache Kafka 4.4: Broker configs (transaction settings)
- KIP-98: Exactly Once Delivery and Transactional Messaging
- Spring for Apache Kafka: Transactions
Kafka Transactions Interview Questions and Answers
Common interview questions on Kafka Transactions, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What does a Kafka transaction guarantee, and what does it not cover?
Answer: It guarantees that a producer’s writes to several partitions and topics, together with consumer offsets added through sendOffsetsToTransaction(), are committed or aborted as one unit, and that read_committed consumers never see aborted records. It does not cover anything outside Kafka: a database write or an HTTP call made in the same code can still happen when the Kafka transaction aborts, or happen twice when the input is reprocessed.
Q. What are the transaction coordinator and the __transaction_state topic?
Answer: The transaction coordinator is a module on each broker that manages transactions. A transactional ID is hashed to a partition of the internal __transaction_state topic, and the leader of that partition acts as its coordinator. It assigns the producer ID and epoch, records which partitions and groups each transaction touches, persists state changes such as PREPARE_COMMIT to the replicated log, writes the commit or abort markers, and aborts transactions that exceed their timeout. Because the state is in a replicated topic, another broker can take over after a failure.
Intermediate questions
Q. How do Kafka transactions work internally, from initTransactions() to commitTransaction()?
Answer: initTransactions() finds the coordinator and obtains the producer ID with a bumped epoch, closing any transaction the previous instance left open. beginTransaction() is local. Each partition is registered with the coordinator before the first write to it, and records go straight into the partition logs as part of an open transaction. sendOffsetsToTransaction() adds the input offsets as transactional offset commits. commitTransaction() makes the coordinator log PREPARE_COMMIT, write a COMMIT marker into every involved partition, including the offsets partition, and then log COMPLETE_COMMIT.
Q. What are control records and the last stable offset, and how do read_committed consumers use them?
Answer: Control records are COMMIT or ABORT markers that the coordinator writes into each partition a transaction touched; they are never returned to the application. The last stable offset (LSO) is the first offset of the oldest transaction in the partition that is still undecided. A read_committed consumer fetches only up to the LSO, and it drops records of aborted transactions using the abort information the broker returns with each fetch. A read_uncommitted consumer reads up to the high watermark and sees everything.
Q. How does zombie fencing work, and what breaks it?
Answer: When a new instance calls initTransactions() with the same transactional.id, the coordinator increments the producer epoch. Requests from the old instance carry the old epoch and are rejected, and its client throws ProducerFencedException. Fencing breaks if each start uses a new random transactional ID, because the new instance never bumps the old one’s epoch, or if two live instances share an ID and fence each other continuously.
Tricky and scenario questions
Q. A transactional producer crashes in the middle of a transaction. What do read_committed consumers see, and when?
Answer: Nothing from that transaction. Its records are in the logs but stay behind the LSO, so read_committed consumers of those partitions stop at that point. The transaction is aborted either when a new instance with the same transactional ID calls initTransactions(), or when transaction.timeout.ms expires and the coordinator aborts it. After the ABORT markers are written, consumers skip the records and continue. The input offsets were not committed, so the restarted instance processes the same input again.
Q. read_committed consumers on one partition have stopped advancing, while producers keep writing. What would you suspect?
Answer: An open transaction that is holding back the last stable offset: a producer that hung without committing, or a transaction timeout that was set very high. Records written after it, even non-transactional ones, are not readable in read_committed mode until it is decided. Check open transactions with kafka-transactions.sh, fix or restart the producer, and keep transaction.timeout.ms short enough that the coordinator aborts stuck transactions quickly.