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.

Share

Contents

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_committed skips records from aborted transactions and waits for open ones to finish. A consumer with the default, read_uncommitted, sees everything that was written, including the aborted records.

The features behind Kafka exactly-once
FeatureSettingSinceWhat it prevents
Idempotent producerenable.idempotence=true0.11; on by default since 3.0Duplicates from the producer's own retries, per partition
Transactional producertransactional.id0.11Partly written groups of records, and output written twice after a restart
Offsets in the transactionsendOffsetsToTransaction0.11; group metadata form since 2.5Input read twice after a crash
Committed readsisolation.level=read_committed0.11Consumers seeing aborted or unfinished transactions
Kafka Streams exactly-onceprocessing.guarantee=exactly_once_v23.0; the only exactly-once value since 4.0All 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 EmbeddedKafkaKraftBroker from spring-kafka-test, then uses only the plain Kafka client API. A real cluster has 3 or more brokers; the single broker here needs its transaction log replication lowered to 1, which startBroker does.

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, and tries two settings that conflict with idempotence:

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.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);
        }
    }
}
Output
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 payments-0 tracks producer id 0 at epoch 0, and its last sequence is 4: the five records were numbered 0 to 4.
  • With enable.idempotence=false, the leader of audit-0 tracks no producer, so a retried batch would be written twice.
  • Setting only acks=1 turned idempotence off without any error, because idempotence needs acks=all. The metrics-0 partition tracks no producer either. This is the easiest way to lose the guarantee by accident.
  • Asking for both explicitly made the constructor throw ConfigException. Setting enable.idempotence=true in your configuration turns silent downgrades into start-up errors.

Idempotence also needs retries above 0 and max.in.flight.requests.per.connection of 5 or less; with those, the broker keeps the order of batches even when they are retried. The guarantee has two limits. It covers one producer session: a restarted producer gets a new producer id, and the broker cannot connect its batches to the old ones. And it only covers the producer's own retries, not an application that calls send twice for the same data.

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:

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.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);
        }
    }
}
Output
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 commitSync. The committed offset stayed at 3.
  • 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 Kafka offsets page covers commit strategies in detail. The cure is to make the invoices and the offset commit succeed or fail together.

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:

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.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);
        }
    }
}
Output
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]
  • initTransactions() registers the transactional.id with the broker's transaction coordinator. It is called once per producer, before the first transaction.
  • 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 debit 70 is at offset 3. An abort does not delete anything: the record stays in the log, and the read_uncommitted consumer returned it.
  • While transfer 3 was open, the read_committed 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. A read_committed consumer cannot read past it, so it saw only transfer 1.
  • After the commit, the last stable offset moved to 7, the end of the log, and debit 20 became visible. The aborted record stayed hidden.

The last stable offset has a consequence that surprises people: a long transaction holds back every read_committed consumer of that partition, including records written after it by other producers. Keep transactions short. The coordinator aborts a transaction that stays open longer than the producer's transaction.timeout.ms, which defaults to 60 seconds and may not exceed the broker's transaction.max.timeout.ms of 15 minutes.

Read-process-write in one transaction

This is the same invoicing processor and the same crash, with three changes. The producer has a transactional.id, each batch's invoices are written inside a transaction, and the consumer offsets are added to that transaction with sendOffsetsToTransaction instead of being committed by the consumer:

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.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);
        }
    }
}
Output
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 initTransactions() with the same transactional.id. 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.
  • The read_uncommitted reader still sees invoices 4 and 5 twice, because the aborted copies are in the log. The read_committed reader sees each invoice exactly once.
  • 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.commit must be off, because the transaction commits the offsets. The consumer itself uses read_committed, so that it never processes another processor's aborted output. consumer.groupMetadata() passes the consumer group's generation to the coordinator, which rejects offsets from a consumer that has been removed from the group in a rebalance. And the transactional.id must stay the same across restarts of one instance, and differ between instances that run at the same time; otherwise they fence each other. The Kafka transactions deep dive shows that fencing and the coordinator's state running.

Handling errors in a transactional producer

Transactional code needs an error handler that tells two kinds of failure apart. The pattern from the KafkaProducer Javadoc looks like this:

Java
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: ProducerFencedException means a newer producer with the same transactional.id has started, so this instance must stop. The producer cannot be used again; close it and exit or rebuild.
  • Abortable errors: any other KafkaException, such as a failed send inside the transaction, leaves the producer in an error state where every call except abortTransaction() fails. After the abort, the next transaction can start normally.
  • Timeouts: a TimeoutException from commitTransaction() does not say whether the commit happened. Retry the same call; the producer then finishes the commit or reports the real error.

After an abort in a read-process-write loop, also move the consumer back to the last committed offsets with seek, because its in-memory position is already past the records whose output was just thrown away.

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 read_committed 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.
  • Blocked partitions: as shown above, one open transaction stops read_committed consumers at the last stable offset until it finishes or times out.
  • A replicated transaction log: the coordinator keeps its state in the internal __transaction_state topic, which needs a replication factor of 3 and min.insync.replicas of 2 by default, so transactions need at least three brokers unless you lower those settings.

Choosing a delivery guarantee

Situations and the approach that fits
SituationApproach
Any producerKeep the defaults: acks=all and idempotence; set enable.idempotence=true so a conflicting setting fails loudly
A consumer whose writes go to a databaseAt least once, with an idempotent write, such as an upsert keyed by the record's id
Several records that must appear togetherA transactional producer, and read_committed on every consumer
Kafka in, Kafka out, without duplicatesRead-process-write with sendOffsetsToTransaction, or Kafka Streams with exactly_once_v2
Kafka in, side effect out (email, HTTP call)At least once with deduplication on the receiving side; transactions cannot cover it
Spring applicationsspring.kafka.producer.transaction-id-prefix, as on the KafkaTemplate page

The producer and consumer settings behind these guarantees are explained on the Kafka producer and Kafka consumer pages. For the coordinator, fencing, the last stable offset and the cost of transactions measured, continue with the transactions deep dive; for exactly-once in a stream processing application, see Kafka Streams.