Kafka transactions in depth: coordinator, fencing and the last stable offset

A Kafka transaction is a small protocol between the producer, a transaction coordinator on one broker, and the leaders of every partition it writes. This page follows that protocol step by step with the Admin API, then runs the cases that matter in production: a zombie instance being fenced, a stuck transaction blocking consumers, an abortable error and the cost of small transactions.

Share

Contents

The pieces of the transaction protocol

A transactional producer does not simply tag its records. It runs a protocol with a broker that acts as its transaction coordinator, and with the leaders of every partition it writes to. Seven pieces take part:

  • Transactional id: the name you configure with transactional.id. It identifies one logical producer across restarts, such as "the invoicing processor for partition 0".
  • Producer id and epoch: a number the coordinator assigns to the transactional id, and a counter that it raises whenever a new producer instance registers. Every batch carries both.
  • Transaction coordinator: the broker that leads the partition of __transaction_state where the transactional id is stored. It decides commit or abort.
  • __transaction_state: an internal, compacted topic with 50 partitions by default, where the coordinator writes each state change before acting on it. A new coordinator rebuilds its state from it after a failover.
  • Partition leaders: they store the transaction's records like any others, and remember which producer ids have a transaction open on them.
  • Control records: when the transaction ends, the coordinator asks each leader to append a commit or abort marker. Markers take up an offset but are never returned to applications.
  • Last stable offset: on each partition, the offset of the first record of the oldest transaction still open. read_committed consumers read only up to it.

The protocol runs in four steps. initTransactions() finds the coordinator, which aborts or completes any earlier transaction of this id and bumps the epoch. During the transaction, each new partition is registered with the coordinator before the first write to it. commitTransaction() flushes the records and sends EndTxn; the coordinator writes PrepareCommit to its log, which is the point of no return. Then it writes the markers to every partition and finally CompleteCommit.

How the transaction protocol has changed
ChangeKafka versionEffect
KIP-98: idempotent and transactional producer0.11The protocol on this page
KIP-447: group metadata in sendOffsetsToTransaction2.5One producer per application instance is enough; before, read-process-write needed one producer per input partition
KIP-890: transactions server-side defense, transaction.version=24.0, enabled on the server by defaultThe epoch is bumped on every commit and abort, and partitions are added to the transaction implicitly by the first write

Every program starts its own single-node Kafka 4.2 broker inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test, and uses the plain Kafka client and Admin APIs. Production clusters have 3 or more brokers; the single broker here needs __transaction_state replication lowered to 1. The basics, including read-process-write, are on the Kafka transactions page.

One transaction through the coordinator

The Admin API, through the calls added for transaction tooling in KIP-664, can ask the coordinator what it knows about a transactional id. The program runs one committed and one aborted transaction, writing to two topics, and prints the coordinator's view after each step:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.TransactionDescription;
import org.apache.kafka.clients.admin.TransactionState;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class CoordinatorLifecycle {

    static final String TX_ID = "billing-0";

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        p.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, TX_ID);
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers));
             var producer = new KafkaProducer<String, String>(p)) {
            var features = admin.describeFeatures().featureMetadata().get().finalizedFeatures();
            System.out.println("transaction.version = "
                    + features.get("transaction.version").maxVersionLevel());

            producer.initTransactions();
            show(admin, "after initTransactions");

            producer.beginTransaction();
            show(admin, "after beginTransaction");
            producer.send(new ProducerRecord<>("invoices", "c-1", "invoice 1")).get();
            producer.send(new ProducerRecord<>("payments", "c-1", "payment 1")).get();
            show(admin, "after two sends");
            producer.commitTransaction();
            waitUntilComplete(admin);
            show(admin, "after commitTransaction");

            producer.beginTransaction();
            producer.send(new ProducerRecord<>("invoices", "c-2", "invoice 2")).get();
            producer.abortTransaction();
            waitUntilComplete(admin);
            show(admin, "after abortTransaction");

            // the coordinator for an id is the leader of one partition of __transaction_state
            int partitions = admin.describeTopics(List.of("__transaction_state")).allTopicNames()
                    .get().get("__transaction_state").partitions().size();
            System.out.println("__transaction_state partitions: " + partitions
                    + ", '" + TX_ID + "' lives in partition "
                    + (Utils.abs(TX_ID.hashCode()) % partitions));
        } finally {
            broker.destroy();
        }
    }

    static TransactionDescription describe(Admin admin) throws Exception {
        return admin.describeTransactions(List.of(TX_ID)).description(TX_ID).get();
    }

    static void show(Admin admin, String step) throws Exception {
        TransactionDescription d = describe(admin);
        System.out.printf("%-24s state=%-14s producerId=%d epoch=%d partitions=%s%n",
                step, d.state(), d.producerId(), d.producerEpoch(),
                d.topicPartitions().stream().map(Object::toString).sorted().toList());
    }

    // commit and abort return once the coordinator has decided; the markers follow
    static void waitUntilComplete(Admin admin) throws Exception {
        while (true) {
            TransactionState s = describe(admin).state();
            if (s == TransactionState.COMPLETE_COMMIT || s == TransactionState.COMPLETE_ABORT) {
                return;
            }
            Thread.sleep(20);
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup: both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
transaction.version = 2
after initTransactions   state=Empty          producerId=0 epoch=0 partitions=[]
after beginTransaction   state=Empty          producerId=0 epoch=0 partitions=[]
after two sends          state=Ongoing        producerId=0 epoch=0 partitions=[invoices-0, payments-0]
after commitTransaction  state=CompleteCommit producerId=0 epoch=1 partitions=[]
after abortTransaction   state=CompleteAbort  producerId=0 epoch=2 partitions=[]
__transaction_state partitions: 50, 'billing-0' lives in partition 44
  • The broker runs transaction.version 2, so the KIP-890 protocol is active, as it is on any new Kafka 4 cluster.
  • After initTransactions(), the coordinator holds producer id 0 at epoch 0, in state Empty.
  • beginTransaction() changed nothing on the broker: it only changes the producer's local state. The transaction exists on the coordinator from the first write on, when the state became Ongoing with both partitions listed.
  • The commit raised the epoch to 1, and the abort raised it to 2. That is transaction version 2 at work: each transaction gets its own epoch, so a late write from a finished transaction cannot slip into the next one.
  • billing-0 is stored in partition 44 of the 50 __transaction_state partitions, chosen from the hash of the id. The broker that leads partition 44 is this id's coordinator.

The program waits for CompleteCommit before printing, because commitTransaction() can return while the state is still PrepareCommit. At that point the outcome is decided and logged, and only the markers are still being written; a reader that queries immediately can briefly see the intermediate state.

Zombie fencing

A zombie is an instance that someone believes is dead but is still running: after a long garbage collection pause or a network partition, it wakes up and carries on writing. If a replacement has already taken over its work, both would write the same output. Here instance A stalls in the middle of a transaction, and instance B starts with the same transactional.id:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.TransactionDescription;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ZombieFencing {

    // instance A stalls (a long GC pause, a network partition); B replaces it with the same id
    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers));
             var a = new KafkaProducer<String, String>(props(servers));
             var b = new KafkaProducer<String, String>(props(servers))) {
            a.initTransactions();
            a.beginTransaction();
            a.send(new ProducerRecord<>("shipments", "s-1", "from A, first")).get();
            show(admin, "A is in a transaction");

            b.initTransactions(); // same transactional.id: bumps the epoch, aborts A's work
            show(admin, "B called initTransactions");

            try {
                a.send(new ProducerRecord<>("shipments", "s-2", "from A, second")).get();
            } catch (ExecutionException e) {
                System.out.println("A send:   " + e.getCause().getClass().getSimpleName());
            }
            try {
                a.commitTransaction();
            } catch (KafkaException e) {
                System.out.println("A commit: " + e.getClass().getSimpleName()
                        + ": " + e.getMessage());
            }

            try {
                a.abortTransaction();
                a.beginTransaction();
                System.out.println("A started a new transaction");
            } catch (KafkaException e) {
                System.out.println("A abort and retry: " + e.getClass().getSimpleName());
            }

            b.beginTransaction();
            b.send(new ProducerRecord<>("shipments", "s-1", "from B"));
            b.commitTransaction();
            while (!describe(admin).state().toString().equals("CompleteCommit")) {
                Thread.sleep(20); // the coordinator is still writing the commit markers
            }
            show(admin, "B committed");
            System.out.println("read_committed sees: " + readCommitted(servers));
        } finally {
            broker.destroy();
        }
    }

    static Properties props(String servers) {
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        p.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "shipping-0");
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return p;
    }

    static TransactionDescription describe(Admin admin) throws Exception {
        return admin.describeTransactions(List.of("shipping-0")).description("shipping-0").get();
    }

    static void show(Admin admin, String step) throws Exception {
        TransactionDescription d = describe(admin);
        System.out.printf("%-28s state=%s epoch=%d%n", step, d.state(), d.producerEpoch());
    }

    static List<String> readCommitted(String servers) {
        Properties c = new Properties();
        c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        c.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
        c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        List<String> values = new ArrayList<>();
        try (var consumer = new KafkaConsumer<String, String>(c)) {
            TopicPartition tp = new TopicPartition("shipments", 0);
            consumer.assign(List.of(tp));
            consumer.seekToBeginning(List.of(tp));
            for (int empty = 0; empty < 2; ) {
                var records = consumer.poll(Duration.ofMillis(500));
                empty = records.isEmpty() ? empty + 1 : 0;
                records.forEach(r -> values.add(r.offset() + ":" + r.value()));
            }
        }
        return values;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup: both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
A is in a transaction        state=Ongoing epoch=0
B called initTransactions    state=Empty epoch=2
A send:   InvalidProducerEpochException
A commit: InvalidProducerEpochException: Producer with transactionalId 'shipping-0' and (producerId=0, epoch=0) attempted to produce with an old epoch
A abort and retry: ProducerFencedException
B committed                  state=CompleteCommit epoch=3
read_committed sees: [2:from B]
  • B's initTransactions() aborted A's open transaction and raised the epoch from 0 to 2. From then on, the coordinator and the partition leaders reject anything from producer id 0 at a lower epoch.
  • A's next send failed with InvalidProducerEpochException, and its commit failed with the same error, so its first record never became visible.
  • A then tried to abort and start again, and got ProducerFencedException. That error is fatal: the only thing a fenced producer can do is close.
  • B committed at epoch 3. The read_committed consumer sees only B's record at offset 2. Offset 0 is A's aborted record, and offset 1 is the abort marker.

Fencing only works if two instances that do the same work share a transactional.id, and instances that do different work never do. Give each instance a stable id that survives restarts, such as one derived from its pod name in a StatefulSet. A random id per start defeats fencing, and the same id on every instance makes them fence each other in a loop.

A stuck transaction blocks every committed reader

A batch job opens a transaction, writes one record, and then hangs. Other producers keep writing to the same partition without transactions. The job's producer sets transaction.timeout.ms to 4 seconds, and the broker checks for timed-out transactions every second instead of every 10, so that the program finishes quickly:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.TransactionDescription;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Exit;
import org.apache.kafka.tools.TransactionsCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class StuckTransaction {

    static final TopicPartition EVENTS = new TopicPartition("events", 0);

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        Properties tx = props(servers);
        tx.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "slow-job-0");
        tx.put(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, "4000");
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers));
             var stuck = new KafkaProducer<String, String>(tx);
             var plain = new KafkaProducer<String, String>(props(servers));
             var consumer = consumer(servers)) {
            stuck.initTransactions();
            stuck.beginTransaction();
            stuck.send(new ProducerRecord<>("events", "job", "half-done work")).get();
            long opened = System.nanoTime();
            for (int i = 1; i <= 3; i++) { // other producers keep writing, outside transactions
                plain.send(new ProducerRecord<>("events", "e-" + i, "event " + i)).get();
            }

            consumer.assign(List.of(EVENTS));
            consumer.seekToBeginning(List.of(EVENTS));
            long lso = consumer.endOffsets(List.of(EVENTS)).get(EVENTS);
            System.out.println("4 records written, last stable offset " + lso);
            System.out.println("read_committed poll for 2 s: " + poll(consumer, 2000));

            // what bin/kafka-transactions.sh list prints; the tool calls exit when it is done
            Exit.setExitProcedure((code, message) -> { });
            System.out.println("$ kafka-transactions.sh --bootstrap-server ... list");
            TransactionsCommand.main(new String[] {"--bootstrap-server", servers, "list"});

            List<String> seen = poll(consumer, 15000); // waits for the coordinator's timeout
            long waited = (System.nanoTime() - opened) / 1000000;
            System.out.println("then: " + seen);
            System.out.println("records released after the 4 s timeout: " + (waited >= 4000));
            System.out.println("last stable offset now "
                    + consumer.endOffsets(List.of(EVENTS)).get(EVENTS));

            TransactionDescription d = admin.describeTransactions(List.of("slow-job-0"))
                    .description("slow-job-0").get();
            System.out.println("coordinator: state=" + d.state() + " epoch=" + d.producerEpoch());
            try {
                stuck.commitTransaction();
            } catch (KafkaException e) {
                System.out.println("late commit: " + e.getClass().getSimpleName());
            }
        } finally {
            broker.destroy();
        }
    }

    // polls until it gets records or the time runs out
    static List<String> poll(KafkaConsumer<String, String> consumer, long millis) {
        List<String> values = new ArrayList<>();
        long deadline = System.currentTimeMillis() + millis;
        while (values.isEmpty() && System.currentTimeMillis() < deadline) {
            consumer.poll(Duration.ofMillis(200))
                    .forEach(r -> values.add(r.offset() + ":" + r.value()));
        }
        return values;
    }

    static Properties props(String servers) {
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return p;
    }

    static KafkaConsumer<String, String> consumer(String servers) {
        Properties c = new Properties();
        c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        c.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
        c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        return new KafkaConsumer<>(c);
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup: both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log;
            // timed-out transactions are looked for every second instead of every 10
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1",
                            "transaction.abort.timed.out.transaction.cleanup.interval.ms",
                            "1000"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
4 records written, last stable offset 0
read_committed poll for 2 s: []
$ kafka-transactions.sh --bootstrap-server ... list
TransactionalId	Coordinator	ProducerId	TransactionState	
slow-job-0     	0          	1         	Ongoing         	
then: [1:event 1, 2:event 2, 3:event 3]
records released after the 4 s timeout: true
last stable offset now 5
coordinator: state=CompleteAbort epoch=1
late commit: InvalidTxnStateException
  • Four records were in the log, but the last stable offset was 0: the offset of the stuck transaction's first record.
  • For 2 seconds, the read_committed consumer received nothing, not even events 1 to 3, which were never part of any transaction. A consumer must deliver records in offset order, and it cannot know yet whether offset 0 will be committed.
  • kafka-transactions.sh list, run here through its main class, shows the culprit: slow-job-0, producer id 1, Ongoing. In production this is the first command to run when consumers stop making progress but the log keeps growing.
  • Once the timeout passed, the coordinator aborted the transaction itself and wrote the marker at offset 4. The last stable offset jumped to 5 and the consumer received events 1 to 3. The half-done record stayed hidden.
  • The coordinator raised the epoch to 1 when it aborted, so the job's late commitTransaction() failed with InvalidTxnStateException instead of committing work that had already been thrown away.

Consumer lag metrics hide this problem, because a read_committed consumer measures its lag against the last stable offset, which is not moving. Two settings bound the damage: the producer's transaction.timeout.ms (default 60 seconds) and the broker's transaction.max.timeout.ms (default 15 minutes), which caps what a producer may ask for. A transaction that hangs because a partition leader never learned of its end, the problem KIP-890 was written to prevent, can be found with kafka-transactions.sh find-hanging and ended with its abort command.

Abortable and fatal errors

Inside a transaction, a failed send does not just fail its own future. It puts the whole producer into an error state, because the transaction can no longer commit as a whole. The program sends a 2 MB record, over the producer's max.request.size of 1 MB, then tries every next step:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class AbortableErrors {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, broker.getBrokersAsString());
        p.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "orders-0");
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        try (var producer = new KafkaProducer<String, String>(p)) {
            producer.initTransactions();
            producer.beginTransaction();
            producer.send(new ProducerRecord<>("orders", "o-1", "small order"));
            // 2 MB is over the producer's max.request.size of 1 MB
            Future<RecordMetadata> big =
                    producer.send(new ProducerRecord<>("orders", "o-2", "x".repeat(2000000)));
            System.out.println("send() of the 2 MB record returned a future");
            try {
                big.get();
            } catch (ExecutionException e) {
                System.out.println("future failed: " + e.getCause().getClass().getSimpleName());
            }
            attempt("send another record", () ->
                    producer.send(new ProducerRecord<>("orders", "o-3", "after the error")));
            attempt("commitTransaction", producer::commitTransaction);
            attempt("beginTransaction", producer::beginTransaction);
            attempt("abortTransaction", producer::abortTransaction);

            producer.beginTransaction();
            producer.send(new ProducerRecord<>("orders", "o-1", "small order, retried"));
            producer.commitTransaction();
            System.out.println("the next transaction committed normally");
        } finally {
            broker.destroy();
        }
    }

    static void attempt(String what, Runnable call) {
        try {
            call.run();
            System.out.println(what + ": ok");
        } catch (KafkaException e) {
            System.out.println(what + ": " + e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup: both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
send() of the 2 MB record returned a future
future failed: RecordTooLargeException
send another record: KafkaException: Cannot execute transactional method because we are in an error state
commitTransaction: KafkaException: Cannot execute transactional method because we are in an error state
beginTransaction: KafkaException: Cannot execute transactional method because we are in an error state
abortTransaction: ok
the next transaction committed normally
  • send() returned normally, and the error arrived through the future as RecordTooLargeException. A transactional producer reports send errors this way, so code that ignores futures finds out only at commit.
  • After the error, the next send, commitTransaction() and beginTransaction() all failed with "in an error state". The small order sent before the big one cannot be committed either.
  • abortTransaction() was the one call allowed, and it cleared the error. The next transaction committed normally on the same producer.

Compare this with the fenced producer in the zombie example, which could not even abort. A read-process-write loop therefore needs three branches:

Java
try {
    producer.beginTransaction();
    // process the polled records and send the results
    producer.sendOffsetsToTransaction(offsets, consumer.groupMetadata());
    producer.commitTransaction();
} catch (ProducerFencedException | InvalidProducerEpochException e) {
    // another instance owns the id: stop, without committing anything else
    producer.close();
    throw e;
} catch (KafkaException e) {
    producer.abortTransaction();
    // rewind, so the aborted batch is processed again
    for (TopicPartition tp : consumer.assignment()) {
        OffsetAndMetadata committed = consumer.committed(Set.of(tp)).get(tp);
        if (committed != null) {
            consumer.seek(tp, committed.offset());
        } else {
            consumer.seekToBeginning(Set.of(tp)); // what auto.offset.reset=earliest would do
        }
    }
}

The rewind matters: after the abort, the consumer's position is still past the records whose output was just discarded. Without the seek, the next poll continues after them and those records are never processed. Kafka Streams and Spring's listener containers do this rewind for you.

What a transaction costs

Each transaction adds fixed work: registering partitions, the EndTxn round trip, writes to __transaction_state, and a marker on each partition. The program sends the same 1,000 small records with no transaction, then in transactions of 1, 10, 100 and 1,000 records:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class TransactionCost {

    static final int RECORDS = 1000;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        try (var plain = new KafkaProducer<String, String>(props(servers, null));
             var tx = new KafkaProducer<String, String>(props(servers, "cost-0"))) {
            tx.initTransactions();
            System.out.printf("%-28s %8s%n", "records per transaction", "best ms");
            System.out.printf("%-28s %8d%n", "no transaction", best(() -> sendPlain(plain)));
            for (int perTx : new int[] {1, 10, 100, 1000}) {
                System.out.printf("%-28d %8d%n", perTx, best(() -> sendInTransactions(tx, perTx)));
            }
        } finally {
            broker.destroy();
        }
    }

    static void sendPlain(KafkaProducer<String, String> producer) {
        for (int i = 0; i < RECORDS; i++) {
            producer.send(new ProducerRecord<>("cost", "k" + (i % 10), "value " + i));
        }
        producer.flush(); // wait until every record is acknowledged
    }

    static void sendInTransactions(KafkaProducer<String, String> producer, int perTx) {
        for (int i = 0; i < RECORDS; i += perTx) {
            producer.beginTransaction();
            for (int j = i; j < i + perTx; j++) {
                producer.send(new ProducerRecord<>("cost", "k" + (j % 10), "value " + j));
            }
            producer.commitTransaction(); // flushes, then waits for the coordinator
        }
    }

    // best of 3 runs, after one warm-up run
    static long best(Runnable run) {
        run.run();
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 3; i++) {
            long start = System.nanoTime();
            run.run();
            best = Math.min(best, (System.nanoTime() - start) / 1000000);
        }
        return best;
    }

    static Properties props(String servers, String transactionalId) {
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        if (transactionalId != null) {
            p.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, transactionalId);
        }
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        return p;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup: both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
records per transaction       best ms
no transaction                     11
1                                4161
10                                142
100                                28
1000                                2

This is a rough comparison: best of 3 runs after a warm-up, on a 2-core Linux container shared with other work, with the broker in the same JVM, so there is almost no network latency. Look at the ratios, not the milliseconds:

  • One record per transaction was by far the slowest, at several milliseconds per transaction. Setting linger.ms=0 did not change that in a separate run, because the cost is the commit round trips, not batching.
  • Ten records per transaction instead of one cut the total time by more than ten times, and 100 per transaction cut it again, as the fixed cost was shared by more records.
  • With 100 or more records per transaction, the time was in the same range as the producer without transactions, a few milliseconds to a few tens. Differences that small change from run to run on this machine, so do not read an order into the last rows.

Against a real cluster, each round trip takes milliseconds rather than microseconds, so small transactions hurt more. In a read-process-write loop, one transaction per poll() batch is the natural unit. Kafka Streams commits a transaction every commit.interval.ms, 100 ms by default with exactly-once, which trades a little latency for large transactions.

Kafka Streams and Spring do this for you

Kafka Streams runs the whole read-process-write protocol, including fencing and the rewind after an abort, when one property is set:

Java
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);

Since Kafka 4.0, exactly_once_v2 is the only exactly-once value; the older exactly_once and exactly_once_beta settings, deprecated in 3.0, are rejected. It creates one transactional producer per stream thread, which KIP-447 made possible, and its state store changelogs are written in the same transactions as the output. The Kafka Streams page shows it running. In Spring for Apache Kafka, setting spring.kafka.producer.transaction-id-prefix makes KafkaTemplate transactional, and the listener container then sends the consumed offsets in the same transaction; see KafkaTemplate.

Settings that matter in production

Transaction-related settings and their defaults in Kafka 4.2
SettingWhereDefaultWhy it matters
transaction.timeout.msProducer60000How long a hung transaction can block read_committed consumers
transaction.max.timeout.msBroker900000The largest timeout a producer may request
transaction.state.log.replication.factorBroker3Transactions fail until __transaction_state can be created with this many replicas
transaction.state.log.min.isrBroker2Replicas that must confirm each coordinator write
transactional.id.expiration.msBroker604800000 (7 days)An id unused for this long is forgotten, and its fencing history with it
producer.id.expiration.msBroker86400000 (1 day)How long a partition leader remembers an idle producer's sequence numbers
transaction.abort.timed.out.transaction.cleanup.interval.msBroker10000How often the coordinator looks for timed-out transactions

Choosing how to handle each situation

Transaction problems and what to do about them
SituationWhat to do
Several instances of one processorOne stable transactional.id per instance, the same across its restarts
ProducerFencedException or InvalidProducerEpochExceptionClose the producer and stop this instance: a newer one owns the work
Any other KafkaException in a transactionabortTransaction(), seek the consumer back to the committed offsets, retry
read_committed consumers stalled while the log growskafka-transactions.sh list to find the open transaction; lower transaction.timeout.ms
Throughput too low with transactionsMore records per transaction: one per poll batch, or a longer commit interval
Kafka in, Kafka out, with stateKafka Streams with exactly_once_v2 rather than hand-written transactions

For the producer settings underneath, see Kafka producer; for how consumers track their position, Kafka offsets; and for watching lag, which hides a stuck transaction, Kafka lag monitoring.