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.
Contents
The pieces of the transaction protocol One transaction through the coordinator Zombie fencing A stuck transaction blocks every committed reader Abortable and fatal errors What a transaction costs Kafka Streams and Spring do this for you Settings that matter in production Choosing how to handle each situation
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
. It identifies one logical producer across restarts, such as "the invoicing processor for partition 0".transactional.id - 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
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.__transaction_state- 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.
consumers read only up to it.read_committed
The protocol runs in four steps. initTransactions()commitTransaction()EndTxnPrepareCommitCompleteCommit
| Change | Kafka version | Effect |
|---|---|---|
| KIP-98: idempotent and transactional producer | 0.11 | The protocol on this page |
KIP-447: group metadata in sendOffsetsToTransaction | 2.5 | One producer per application instance is enough; before, read-process-write needed one producer per input partition |
KIP-890: transactions server-side defense, transaction.version=2 | 4.0, enabled on the server by default | The 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 EmbeddedKafkaKraftBrokerspring-kafka-test__transaction_state
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:
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);
}
}
}
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
2, so the KIP-890 protocol is active, as it is on any new Kafka 4 cluster.transaction.version - After
, the coordinator holds producer id 0 at epoch 0, in stateinitTransactions() .Empty 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 becamebeginTransaction() with both partitions listed.Ongoing- 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.
is stored in partition 44 of the 50billing-0 partitions, chosen from the hash of the id. The broker that leads partition 44 is this id's coordinator.__transaction_state
The program waits for CompleteCommitcommitTransaction()PrepareCommit
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
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);
}
}
}
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
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.initTransactions() - A's next send failed with
, and its commit failed with the same error, so its first record never became visible.InvalidProducerEpochException - A then tried to abort and start again, and got
. That error is fatal: the only thing a fenced producer can do is close.ProducerFencedException - B committed at epoch 3. The
consumer sees only B's record at offset 2. Offset 0 is A's aborted record, and offset 1 is the abort marker.read_committed
Fencing only works if two instances that do the same work share a transactional.id
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
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);
}
}
}
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
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.read_committed , run here through its main class, shows the culprit:kafka-transactions.sh list , producer id 1,slow-job-0 . In production this is the first command to run when consumers stop making progress but the log keeps growing.Ongoing- 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
failed withcommitTransaction() instead of committing work that had already been thrown away.InvalidTxnStateException
Consumer lag metrics hide this problem, because a read_committedtransaction.timeout.mstransaction.max.timeout.mskafka-transactions.sh find-hangingabort
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
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);
}
}
}
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
returned normally, and the error arrived through the future assend() . A transactional producer reports send errors this way, so code that ignores futures finds out only at commit.RecordTooLargeException- After the error, the next send,
andcommitTransaction() all failed with "in an error state". The small order sent before the big one cannot be committed either.beginTransaction() was the one call allowed, and it cleared the error. The next transaction committed normally on the same producer.abortTransaction()
Compare this with the fenced producer in the zombie example, which could not even abort. A read-process-write loop therefore needs three branches:
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
What a transaction costs
Each transaction adds fixed work: registering partitions, the EndTxn__transaction_state
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);
}
}
}
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
did not change that in a separate run, because the cost is the commit round trips, not batching.linger.ms=0 - 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()commit.interval.ms
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:
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
Since Kafka 4.0, exactly_once_v2exactly_onceexactly_once_betaspring.kafka.producer.transaction-id-prefixKafkaTemplate
Settings that matter in production
| Setting | Where | Default | Why it matters |
|---|---|---|---|
transaction.timeout.ms | Producer | 60000 | How long a hung transaction can block read_committed |
transaction.max.timeout.ms | Broker | 900000 | The largest timeout a producer may request |
transaction.state.log.replication.factor | Broker | 3 | Transactions fail until __transaction_state |
transaction.state.log.min.isr | Broker | 2 | Replicas that must confirm each coordinator write |
transactional.id.expiration.ms | Broker | 604800000 (7 days) | An id unused for this long is forgotten, and its fencing history with it |
producer.id.expiration.ms | Broker | 86400000 (1 day) | How long a partition leader remembers an idle producer's sequence numbers |
transaction.abort.timed.out.transaction.cleanup.interval.ms | Broker | 10000 | How often the coordinator looks for timed-out transactions |
Choosing how to handle each situation
| Situation | What to do |
|---|---|
| Several instances of one processor | One stable transactional.id |
ProducerFencedExceptionInvalidProducerEpochException | Close the producer and stop this instance: a newer one owns the work |
Any other KafkaException | abortTransaction() |
read_committed | kafka-transactions.sh listtransaction.timeout.ms |
| Throughput too low with transactions | More records per transaction: one per poll batch, or a longer commit interval |
| Kafka in, Kafka out, with state | Kafka Streams with exactly_once_v2 |
For the producer settings underneath, see