00:00

How Kafka Transactions Work Internally

Last updated:

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

ComponentRole
transactional.idA stable name for the logical producer, configured by you. It stays the same across restarts of the same logical instance.
Producer ID and epochThe 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 coordinatorA 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_stateAn 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

Kafka transaction flowThe producer sends InitProducerId to the transaction coordinator, which returns a producer ID and a bumped epoch and fences older instances. After beginTransaction, the producer sends records to the output partitions, which are registered in the transaction. sendOffsetsToTransaction adds the consumer offsets to the transaction through the group coordinator. commitTransaction sends EndTxn: the coordinator writes PREPARE_COMMIT to the __transaction_state log, then writes COMMIT markers to each output partition and to the consumer offsets partition, and finally logs COMPLETE_COMMIT. read_committed consumers can now read the records. Producertransactional.id Txn coordinator__transaction_state Output partitionsorders-enriched, audit Group coord.__consumer_offsets ① InitProducerIdPID + bumped epoch, old instance fenced ② send recordspartitions join the transaction ③ sendOffsetsToTransactioninput offsets (pending) ④ commitTransaction log PREPARE_COMMIT ⑤ COMMIT marker ⑤ COMMIT marker ⑥ log COMPLETE_COMMIT: read_committed consumers can read the records
The coordinator records the decision in its own log before writing markers, so a commit that has started always completes, even if the coordinator fails half-way.
  1. Find the coordinator and initialise. On initTransactions(), the producer locates the coordinator for its transactional ID and sends InitProducerId. The coordinator returns the producer ID with an incremented epoch and completes or aborts any transaction the previous instance left open.
  2. Begin. beginTransaction() is local; nothing is sent to the cluster yet.
  3. 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.
  4. 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.
  5. Commit (two phases). commitTransaction() sends EndTxn. The coordinator first writes PREPARE_COMMIT to __transaction_state; from this point the commit is guaranteed. It then writes a COMMIT marker into every registered partition, including the __consumer_offsets partition, and finally logs COMPLETE_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_committed reads 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:

OrderEnricher.java
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 the KafkaProducer Javadoc 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:

application.yml
spring:
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      transaction-id-prefix: order-enricher-
    consumer:
      group-id: order-enricher
      isolation-level: read_committed
OrderEnricherListener.java
@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

PropertyWhereDefaultMeaning
transactional.idProducernoneEnables transactions; must be stable per logical instance
transaction.timeout.msProducer60000The coordinator aborts a transaction open longer than this
isolation.levelConsumerread_uncommittedSet read_committed to hide aborted and open transactions
transaction.max.timeout.msBroker900000Upper limit for a producer’s transaction.timeout.ms
transaction.state.log.replication.factor / .min.isrBroker3 / 2Durability of __transaction_state
transactional.id.expiration.msBroker604800000 (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_committed consumers, 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.id on every start, which disables zombie fencing.
  • Committing offsets with the consumer (commitSync()) instead of sendOffsetsToTransaction(), 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_committed reader 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.

14. References