Kafka transactions and exactly-once processing
Kafka can retry, crash and restart without writing a record twice, but only when three features work together: the idempotent producer, transactions and read_committed consumers. This page explains what each one guarantees and what it does not, then runs them against a real Kafka 4.2 broker, starting with the duplicates that appear without them.
Contents
Delivery guarantees and where duplicates come from The idempotent producer Duplicates after a restart: the at-least-once processor A first transaction: commit, abort and read_committed Read-process-write in one transaction Handling errors in a transactional producer What transactions cost Choosing a delivery guarantee
Delivery guarantees and where duplicates come from
A message system can promise one of three things about each record: it may be lost but never repeated (at most once), it is never lost but may be repeated (at least once), or it takes effect exactly once. Kafka's default settings give at least once. Duplicates come from two different places, and Kafka has a separate feature for each:
- Producer retries: the producer sends a batch, the broker writes it, but the acknowledgement is lost. The producer cannot tell this from a failed write, so it sends the batch again. The idempotent producer lets the broker recognise and drop the second copy.
- Processor restarts: an application reads a record, writes a result, and crashes before it commits its consumer offset. After the restart it reads the same record again and writes the result a second time. Transactions fix this by committing the results and the consumer offset together, as one unit.
A transaction also needs cooperation from whoever reads the output. A consumer with isolation.level=read_committedread_uncommitted
| Feature | Setting | Since | What it prevents |
|---|---|---|---|
| Idempotent producer | enable.idempotence=true | 0.11; on by default since 3.0 | Duplicates from the producer's own retries, per partition |
| Transactional producer | transactional.id | 0.11 | Partly written groups of records, and output written twice after a restart |
| Offsets in the transaction | sendOffsetsToTransaction | 0.11; group metadata form since 2.5 | Input read twice after a crash |
| Committed reads | isolation.level=read_committed | 0.11 | Consumers seeing aborted or unfinished transactions |
| Kafka Streams exactly-once | processing.guarantee=exactly_once_v2 | 3.0; the only exactly-once value since 4.0 | All of the above, configured in one property |
"Exactly once" in Kafka has a precise scope: records read from Kafka, processed, and written back to Kafka. A side effect outside Kafka, such as an email, an HTTP call or a database row, is not part of the transaction and can still happen twice. Each program on this page starts its own single-node Kafka 4.2 broker inside the JVM with EmbeddedKafkaKraftBrokerspring-kafka-teststartBroker
The idempotent producer
When idempotence is on, the producer gets a producer id from the broker and numbers every batch it sends to a partition with a sequence number. The partition leader remembers the last sequence numbers for each producer id. A retried batch carries the same numbers, so the leader acknowledges it without writing it again. The program sends five records with the default settings, then checks what the broker is tracking with Admin.describeProducers
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.ProducerState;
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.TopicPartition;
import org.apache.kafka.common.config.ConfigException;
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 IdempotentProducer {
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))) {
// 1. the default producer: idempotent since Kafka 3.0
try (var producer = new KafkaProducer<String, String>(props(servers))) {
for (int i = 1; i <= 5; i++) {
producer.send(new ProducerRecord<>("payments", "p-" + i, "pay " + i)).get();
}
printProducers(admin, "default producer", "payments");
}
// 2. idempotence switched off: the broker tracks nothing
Properties plain = props(servers);
plain.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "false");
try (var producer = new KafkaProducer<String, String>(plain)) {
producer.send(new ProducerRecord<>("audit", "a-1", "login")).get();
printProducers(admin, "enable.idempotence=false", "audit");
}
// 3. acks=1 without asking for idempotence: it is turned off silently
Properties acks1 = props(servers);
acks1.put(ProducerConfig.ACKS_CONFIG, "1");
try (var producer = new KafkaProducer<String, String>(acks1)) {
producer.send(new ProducerRecord<>("metrics", "m-1", "cpu 40")).get();
printProducers(admin, "acks=1 only", "metrics");
}
// 4. acks=1 with idempotence asked for explicitly: refused
acks1.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
try (var producer = new KafkaProducer<String, String>(acks1)) {
System.out.println("unexpected: producer created " + producer);
} catch (ConfigException e) {
System.out.println("acks=1 + enable.idempotence=true: " + e.getMessage());
}
} finally {
broker.destroy();
}
}
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;
}
// asks the partition leader which producer ids it is tracking, and their sequence numbers
static void printProducers(Admin admin, String label, String topic) throws Exception {
TopicPartition tp = new TopicPartition(topic, 0);
List<ProducerState> states = admin.describeProducers(List.of(tp)).partitionResult(tp)
.get().activeProducers();
System.out.println(label + " -> " + topic + "-0 tracks " + states.size() + " producer(s)");
for (ProducerState s : states) {
System.out.println(" producerId=" + s.producerId() + " epoch=" + s.producerEpoch()
+ " lastSequence=" + s.lastSequence());
}
}
// 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);
}
}
}
default producer -> payments-0 tracks 1 producer(s)
producerId=0 epoch=0 lastSequence=4
enable.idempotence=false -> audit-0 tracks 0 producer(s)
acks=1 only -> metrics-0 tracks 0 producer(s)
acks=1 + enable.idempotence=true: Must set acks to all in order to use the idempotent producer. Otherwise we cannot guarantee idempotence.
- With no settings at all, the producer was idempotent. The leader of
tracks producer id 0 at epoch 0, and its last sequence is 4: the five records were numbered 0 to 4.payments-0 - With
, the leader ofenable.idempotence=false tracks no producer, so a retried batch would be written twice.audit-0 - Setting only
turned idempotence off without any error, because idempotence needsacks=1 . Theacks=all partition tracks no producer either. This is the easiest way to lose the guarantee by accident.metrics-0 - Asking for both explicitly made the constructor throw
. SettingConfigException in your configuration turns silent downgrades into start-up errors.enable.idempotence=true
Idempotence also needs retriesmax.in.flight.requests.per.connectionsend
Duplicates after a restart: the at-least-once processor
A typical processor reads orders, writes one invoice for each, and commits its consumer offset after each batch. The program puts six orders in a topic, reads them three at a time, and simulates a crash after writing invoice 5, before that batch's offset is committed. Then it starts the processor again in the same consumer group:
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.Set;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
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.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 AtLeastOnceDuplicates {
// a processor that reads orders, writes invoices, then commits its consumer offsets
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try (var producer = new KafkaProducer<String, String>(producerProps(servers))) {
for (int i = 1; i <= 6; i++) {
producer.send(new ProducerRecord<>("orders", "o-" + i, "order " + i));
}
producer.flush();
System.out.println("first run:");
runProcessor(servers, producer, 5); // crashes after writing invoice 5
System.out.println("second run, after the restart:");
runProcessor(servers, producer, -1);
}
System.out.println("invoices topic: " + readValues(servers, "invoices"));
broker.destroy();
}
static void runProcessor(String servers, KafkaProducer<String, String> producer,
int crashAfter) throws Exception {
try (var consumer = new KafkaConsumer<String, String>(consumerProps(servers))) {
consumer.subscribe(List.of("orders"));
long processedUpTo = 0;
while (processedUpTo < 6) { // the topic holds offsets 0 to 5
var records = consumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> r : records) {
String invoice = r.value().replace("order", "invoice");
producer.send(new ProducerRecord<>("invoices", r.key(), invoice)).get();
System.out.println(" offset " + r.offset() + " -> wrote " + invoice);
if (r.offset() + 1 == crashAfter) {
System.out.println(" crash before committing offsets");
return; // the consumer closes without committing this batch
}
}
if (!records.isEmpty()) {
consumer.commitSync(); // offsets are saved only after the whole batch
processedUpTo = committed(consumer);
System.out.println(" committed offset " + processedUpTo);
}
}
}
}
static long committed(KafkaConsumer<String, String> consumer) {
TopicPartition tp = new TopicPartition("orders", 0);
return consumer.committed(Set.of(tp)).get(tp).offset();
}
static Properties producerProps(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 Properties consumerProps(String servers) {
Properties c = new Properties();
c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
c.put(ConsumerConfig.GROUP_ID_CONFIG, "invoicing");
c.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
c.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
c.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "3");
c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
return c;
}
static List<String> readValues(String servers, String topic) {
Properties c = consumerProps(servers);
c.remove(ConsumerConfig.GROUP_ID_CONFIG);
c.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500");
List<String> values = new ArrayList<>();
try (var consumer = new KafkaConsumer<String, String>(c)) {
TopicPartition tp = new TopicPartition(topic, 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.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);
}
}
}
first run:
offset 0 -> wrote invoice 1
offset 1 -> wrote invoice 2
offset 2 -> wrote invoice 3
committed offset 3
offset 3 -> wrote invoice 4
offset 4 -> wrote invoice 5
crash before committing offsets
second run, after the restart:
offset 3 -> wrote invoice 4
offset 4 -> wrote invoice 5
offset 5 -> wrote invoice 6
committed offset 6
invoices topic: [invoice 1, invoice 2, invoice 3, invoice 4, invoice 5, invoice 4, invoice 5, invoice 6]
- The first batch, offsets 0 to 2, was processed and its offset committed as 3: the position of the next record to read.
- The second batch wrote invoices 4 and 5, then the processor stopped before
. The committed offset stayed at 3.commitSync - The restarted processor resumed from offset 3 and wrote invoices 4 and 5 again. The topic now holds eight invoices for six orders.
The producer was idempotent the whole time. Idempotence did not help, because the broker received two different sends, not one send retried. Committing the offset before writing the invoices would swap the problem for a worse one: after a crash, the orders in that batch would get no invoice at all. The
A first transaction: commit, abort and read_committed
A transfer writes a debit and a credit, and a reader must never see one without the other. The program commits one transfer, aborts a second after its debit has reached the broker, and leaves a third open while two consumers read the topic, one with each isolation level:
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.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
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.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 FirstTransaction {
static final TopicPartition LEDGER = new TopicPartition("ledger", 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, "ledger-writer-1");
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<>("ledger", "acc-1", "debit 50"));
producer.send(new ProducerRecord<>("ledger", "acc-2", "credit 50"));
producer.commitTransaction();
System.out.println("transfer 1 committed");
producer.beginTransaction();
producer.send(new ProducerRecord<>("ledger", "acc-1", "debit 70"));
producer.flush(); // the record is now in the log on the broker
producer.abortTransaction();
System.out.println("transfer 2 aborted after its debit reached the broker");
producer.beginTransaction();
producer.send(new ProducerRecord<>("ledger", "acc-3", "debit 20"));
producer.flush();
System.out.println("transfer 3 open:");
report(servers);
producer.commitTransaction();
System.out.println("transfer 3 committed:");
report(servers);
} finally {
broker.destroy();
}
}
static void report(String servers) {
for (String isolation : List.of("read_uncommitted", "read_committed")) {
try (var consumer = consumer(servers, isolation)) {
long end = consumer.endOffsets(List.of(LEDGER)).get(LEDGER);
System.out.printf(" %-16s end offset %d, sees %s%n",
isolation, end, readAll(consumer));
}
}
}
static KafkaConsumer<String, String> consumer(String servers, String isolation) {
Properties c = new Properties();
c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
c.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, isolation);
c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
return new KafkaConsumer<>(c);
}
// reads the partition from the start until a poll comes back empty
static List<String> readAll(KafkaConsumer<String, String> consumer) {
consumer.assign(List.of(LEDGER));
consumer.seekToBeginning(List.of(LEDGER));
List<String> seen = new ArrayList<>();
for (int empty = 0; empty < 2; ) {
var records = consumer.poll(Duration.ofMillis(500));
empty = records.isEmpty() ? empty + 1 : 0;
for (ConsumerRecord<String, String> r : records) {
seen.add(r.offset() + ":" + r.value());
}
}
return seen;
}
// 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);
}
}
}
transfer 1 committed
transfer 2 aborted after its debit reached the broker
transfer 3 open:
read_uncommitted end offset 6, sees [0:debit 50, 1:credit 50, 3:debit 70, 5:debit 20]
read_committed end offset 5, sees [0:debit 50, 1:credit 50]
transfer 3 committed:
read_uncommitted end offset 7, sees [0:debit 50, 1:credit 50, 3:debit 70, 5:debit 20]
read_committed end offset 7, sees [0:debit 50, 1:credit 50, 5:debit 20]
registers theinitTransactions() with the broker's transaction coordinator. It is called once per producer, before the first transaction.transactional.id- Transfer 1's two records are at offsets 0 and 1. Offset 2 holds the commit marker, a control record that the broker writes into the partition when the transaction ends. Consumers never return markers, which is why offsets 2, 4 and 6 are missing from every list.
- The aborted
is at offset 3. An abort does not delete anything: the record stays in the log, and thedebit 70 consumer returned it.read_uncommitted - While transfer 3 was open, the
consumer's end offset was 5, not 6. That is the last stable offset: the position of the first record of the oldest open transaction. Aread_committed consumer cannot read past it, so it saw only transfer 1.read_committed - After the commit, the last stable offset moved to 7, the end of the log, and
became visible. The aborted record stayed hidden.debit 20
The last stable offset has a consequence that surprises people: a long transaction holds back every read_committedtransaction.timeout.mstransaction.max.timeout.ms
Read-process-write in one transaction
This is the same invoicing processor and the same crash, with three changes. The producer has a transactional.idsendOffsetsToTransaction
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
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.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 ExactlyOnceProcessor {
// the same processor as before, but output and offsets go in one transaction
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String servers = broker.getBrokersAsString();
try (var setup = new KafkaProducer<String, String>(producerProps(servers, null))) {
for (int i = 1; i <= 6; i++) {
setup.send(new ProducerRecord<>("orders", "o-" + i, "order " + i));
}
}
System.out.println("first run:");
KafkaProducer<String, String> crashed = runProcessor(servers, 5);
System.out.println("second run, after the restart:");
runProcessor(servers, -1).close();
crashed.close(Duration.ZERO); // only to free its threads; it is already fenced
System.out.println("invoices, read_uncommitted: "
+ readValues(servers, "read_uncommitted"));
System.out.println("invoices, read_committed: "
+ readValues(servers, "read_committed"));
broker.destroy();
}
// returns the producer so that a "crashed" instance can be left open, as a dead process would
static KafkaProducer<String, String> runProcessor(String servers, int crashAfter)
throws Exception {
var producer = new KafkaProducer<String, String>(producerProps(servers, "invoicing-0"));
producer.initTransactions(); // fences and aborts any older instance with this id
try (var consumer = new KafkaConsumer<String, String>(consumerProps(servers))) {
consumer.subscribe(List.of("orders"));
long processedUpTo = 0;
while (processedUpTo < 6) { // the topic holds offsets 0 to 5
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
if (records.isEmpty()) {
continue;
}
producer.beginTransaction();
Map<TopicPartition, OffsetAndMetadata> next = new HashMap<>();
for (ConsumerRecord<String, String> r : records) {
String invoice = r.value().replace("order", "invoice");
producer.send(new ProducerRecord<>("invoices", r.key(), invoice));
System.out.println(" offset " + r.offset() + " -> wrote " + invoice);
next.put(new TopicPartition(r.topic(), r.partition()),
new OffsetAndMetadata(r.offset() + 1));
if (r.offset() + 1 == crashAfter) {
producer.flush(); // the invoices reach the broker, uncommitted
System.out.println(" crash before committing the transaction");
return producer;
}
}
// the consumer offsets become part of the same transaction
producer.sendOffsetsToTransaction(next, consumer.groupMetadata());
producer.commitTransaction();
processedUpTo = committed(consumer);
System.out.println(" committed invoices and offset " + processedUpTo);
}
}
return producer;
}
static long committed(KafkaConsumer<String, String> consumer) {
TopicPartition tp = new TopicPartition("orders", 0);
return consumer.committed(Set.of(tp)).get(tp).offset();
}
static Properties producerProps(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;
}
static Properties consumerProps(String servers) {
Properties c = new Properties();
c.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
c.put(ConsumerConfig.GROUP_ID_CONFIG, "invoicing");
c.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
c.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); // the transaction commits them
c.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
c.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "3");
c.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
c.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
return c;
}
static List<String> readValues(String servers, String isolation) {
Properties c = consumerProps(servers);
c.remove(ConsumerConfig.GROUP_ID_CONFIG);
c.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, isolation);
c.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500");
List<String> values = new ArrayList<>();
try (var consumer = new KafkaConsumer<String, String>(c)) {
TopicPartition tp = new TopicPartition("invoices", 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.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);
}
}
}
first run:
offset 0 -> wrote invoice 1
offset 1 -> wrote invoice 2
offset 2 -> wrote invoice 3
committed invoices and offset 3
offset 3 -> wrote invoice 4
offset 4 -> wrote invoice 5
crash before committing the transaction
second run, after the restart:
offset 3 -> wrote invoice 4
offset 4 -> wrote invoice 5
offset 5 -> wrote invoice 6
committed invoices and offset 6
invoices, read_uncommitted: [invoice 1, invoice 2, invoice 3, invoice 4, invoice 5, invoice 4, invoice 5, invoice 6]
invoices, read_committed: [invoice 1, invoice 2, invoice 3, invoice 4, invoice 5, invoice 6]
- The first batch committed its three invoices and the offset 3 in one step. Either both are saved or neither is.
- The crash left invoices 4 and 5 in the log, inside an open transaction, and the offset at 3.
- The restarted processor called
with the sameinitTransactions() . The coordinator aborted the crashed instance's open transaction and fenced the old producer, so it could never commit it later. Then the new instance processed offsets 3 to 5 and committed offset 6.transactional.id - The
reader still sees invoices 4 and 5 twice, because the aborted copies are in the log. Theread_uncommitted reader sees each invoice exactly once.read_committed - The lines "wrote invoice 4" and "wrote invoice 5" were printed twice. Printing is a side effect outside Kafka, and the transaction could not undo it. An email or a REST call in the same place would also have happened twice.
Four details make this work. enable.auto.commitread_committedconsumer.groupMetadata()transactional.id
Handling errors in a transactional producer
Transactional code needs an error handler that tells two kinds of failure apart. The pattern from the KafkaProducer
try {
producer.beginTransaction();
// send records, then sendOffsetsToTransaction(...)
producer.commitTransaction();
} catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {
// fatal: another instance owns this transactional.id, or the producer is broken
producer.close();
} catch (KafkaException e) {
// abortable: undo this transaction and try again
producer.abortTransaction();
}
- Fatal errors:
means a newer producer with the sameProducerFencedException has started, so this instance must stop. The producer cannot be used again; close it and exit or rebuild.transactional.id - Abortable errors: any other
, such as a failed send inside the transaction, leaves the producer in an error state where every call exceptKafkaException fails. After the abort, the next transaction can start normally.abortTransaction() - Timeouts: a
fromTimeoutException does not say whether the commit happened. Retry the same call; the producer then finishes the commit or reports the real error.commitTransaction()
After an abort in a read-process-write loop, also move the consumer back to the last committed offsets with seek
What transactions cost
- Extra requests: every transaction adds requests to the coordinator at begin and commit, and a marker written to each partition it touched. A transaction per record is far slower than a transaction per batch. The deep-dive page measures the difference.
- Latency for readers: a
consumer sees records only after their transaction commits, so end-to-end latency includes the time until the commit. In Kafka Streams that is the commit interval, 100 ms by default with exactly-once.read_committed - Blocked partitions: as shown above, one open transaction stops
consumers at the last stable offset until it finishes or times out.read_committed - A replicated transaction log: the coordinator keeps its state in the internal
topic, which needs a replication factor of 3 and__transaction_state of 2 by default, so transactions need at least three brokers unless you lower those settings.min.insync.replicas
Choosing a delivery guarantee
| Situation | Approach |
|---|---|
| Any producer | Keep the defaults: acks=allenable.idempotence=true |
| A consumer whose writes go to a database | At least once, with an idempotent write, such as an upsert keyed by the record's id |
| Several records that must appear together | A transactional producer, and read_committed |
| Kafka in, Kafka out, without duplicates | Read-process-write with sendOffsetsToTransactionexactly_once_v2 |
| Kafka in, side effect out (email, HTTP call) | At least once with deduplication on the receiving side; transactions cannot cover it |
| Spring applications | spring.kafka.producer.transaction-id-prefix |
The producer and consumer settings behind these guarantees are explained on the