Kafka producers: how records get to the broker

KafkaProducer.send() only puts a record in a buffer; a background thread batches, compresses and delivers it. This page explains that pipeline and runs its important settings against a real broker: acks and idempotence, partitioning, batching and compression, errors and transactions.

Share

Contents

How the producer turns send() into a write

A Kafka producer appends records to topics. KafkaProducer.send() looks like a network call, but it is not one. It puts the record in memory and returns at once, and a background thread does the network work later. Understanding that split explains the producer's settings, its failure modes and its speed.

Inside the producer, each record goes through these stages:

  1. Serialize: the key and value serializers turn the objects into byte arrays.
  2. Partition: the partitioner picks a partition. A record with a key goes to the partition given by a hash of the key; a record without one goes to a "sticky" partition that changes from time to time.
  3. Accumulate: the record is appended to the open batch for that partition, inside a buffer of buffer.memory bytes (32 MB by default). send() returns a Future<RecordMetadata> here.
  4. Send: the I/O thread, named kafka-producer-network-thread, sends a batch when it is full (batch.size) or has waited linger.ms. Batches for partitions led by the same broker share one request, and up to 5 requests per broker may be in flight.
  5. Acknowledge: the broker leader writes the batch and replies once enough replicas have it, as acks demands. The futures complete with the partition and offset, and callbacks run.

Failed requests are retried by the I/O thread, not by your code, until delivery.timeout.ms (2 minutes) has passed. Two things can make send() itself block: missing metadata for the topic, and a full buffer. Both wait at most max.block.ms, 60 seconds by default. KafkaProducer is thread-safe, and one shared instance per application is usually faster than several, because it batches the records of all threads together.

Ways to send with KafkaProducer
StyleCodeBest for
Fire and forgetsend(record)Metrics or logs where a lost record is acceptable
Synchronoussend(record).get()Low volume, or a caller that must know the outcome
Asynchronoussend(record, callback)Most applications: fast, and errors are still seen
TransactionalbeginTransaction() ... commitTransaction()Several records that must appear together, or exactly-once pipelines

The examples use kafka-clients 4.2.2. Each program first starts its own single-node Kafka 4.2 broker inside the JVM, with EmbeddedKafkaKraftBroker from spring-kafka-test (the startBroker method at the end). The producer code is the same against a real cluster, which has three or more brokers.

Fire and forget, synchronous and asynchronous sends

Three orders are sent in the three styles, so the difference is visible in one run. The program then prints the defaults that control delivery, read from the client library itself:

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.concurrent.CountDownLatch;
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.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class SendThreeWays {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        broker.addTopics("orders");
        Map<String, Object> props = Map.of(
                ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, broker.getBrokersAsString(),
                ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class,
                ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
            // 1. fire and forget: the returned Future is ignored
            producer.send(new ProducerRecord<>("orders", "o-1", "created"));
            System.out.println("1. fire and forget: send() returned at once");

            // 2. synchronous: block on the Future until the broker answers
            Future<RecordMetadata> future =
                    producer.send(new ProducerRecord<>("orders", "o-2", "created"));
            System.out.println("2. synchronous: done before get()? " + future.isDone());
            RecordMetadata meta = future.get();
            System.out.println("   get() -> partition " + meta.partition()
                    + ", offset " + meta.offset() + ", value bytes "
                    + meta.serializedValueSize());

            // 3. asynchronous: a callback runs on the producer's I/O thread
            CountDownLatch acked = new CountDownLatch(1);
            producer.send(new ProducerRecord<>("orders", "o-3", "created"), (m, error) -> {
                System.out.println("3. callback on thread '" + Thread.currentThread().getName()
                        + "': offset " + m.offset() + ", error " + error);
                acked.countDown();
            });
            acked.await();
        }

        Map<String, Object> defaults = ProducerConfig.configDef().defaultValues();
        System.out.println("producer defaults in kafka-clients 4.2:");
        for (String key : List.of("acks", "enable.idempotence", "retries",
                "max.in.flight.requests.per.connection", "linger.ms", "batch.size",
                "buffer.memory", "compression.type", "max.block.ms", "request.timeout.ms",
                "delivery.timeout.ms")) {
            System.out.printf("  %-38s %s%n", key, defaults.get(key));
        }
        broker.destroy();
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so 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.ERROR);
        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
1. fire and forget: send() returned at once
2. synchronous: done before get()? false
   get() -> partition 0, offset 1, value bytes 7
3. callback on thread 'kafka-producer-network-thread | producer-1': offset 2, error null
producer defaults in kafka-clients 4.2:
  acks                                   all
  enable.idempotence                     true
  retries                                2147483647
  max.in.flight.requests.per.connection  5
  linger.ms                              5
  batch.size                             16384
  buffer.memory                          33554432
  compression.type                       none
  max.block.ms                           60000
  request.timeout.ms                     30000
  delivery.timeout.ms                    120000
  • The fire-and-forget send returned without any result. Its record was still written, at offset 0, which is why the next record got offset 1. Had it failed, nothing would have said so.
  • The second future was not done straight after send(): the record was only in the buffer. get() blocked until the broker replied with partition 0, offset 1. The value "created" took 7 bytes once serialized.
  • The callback ran on kafka-producer-network-thread | producer-1, not on main. All callbacks of a producer share this one thread, so slow work in a callback delays every other send. Hand it to an executor instead.
  • acks = all, enable.idempotence = true and retries = 2147483647 make the producer retry until delivery.timeout.ms without writing duplicates. These have been the defaults since the 3.0 release.
  • linger.ms = 5 is the Kafka 4.0 default (KIP-1030); it was 0 before. Each batch now waits up to 5 ms to fill.
  • compression.type = none: records are sent uncompressed unless you choose a codec, as a later section measures.

close(), called here by try-with-resources, sends everything still in the buffer and waits for it. A producer that is never closed can lose its last records when the JVM exits.

acks and the idempotent producer

The acks setting decides when the broker replies. With acks=0 the producer does not wait at all. With acks=1 the leader replies once it has written the record, so a leader crash before the followers copy it loses the record. With acks=all (also written -1), the leader waits for every in-sync replica.

Idempotence solves a different problem: duplicates from retries. If a broker writes a batch but its reply is lost, the producer sends the batch again. With idempotence, each producer gets an id and numbers its batches per partition, and the broker drops a batch whose number it has already seen. It needs acks=all, retries and at most 5 requests in flight. This program builds the producer's configuration with several conflicting settings and shows what the client does with each:

Java
import ch.qos.logback.classic.Level;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IdempotenceRules {

    public static void main(String[] args) {
        // the producer logs its whole configuration at INFO; keep only errors.
        // 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.ERROR);
        check("defaults", Map.of());
        check("acks=1", Map.of("acks", "1"));
        check("acks=0", Map.of("acks", "0"));
        check("retries=0", Map.of("retries", "0"));
        check("max.in.flight=10", Map.of("max.in.flight.requests.per.connection", "10"));
        check("acks=1 + idempotence=true",
                Map.of("acks", "1", "enable.idempotence", "true"));
        check("idempotence=false", Map.of("enable.idempotence", "false"));
    }

    // parses and checks the settings exactly as the KafkaProducer constructor does
    static void check(String label, Map<String, String> overrides) {
        Map<String, Object> props = new HashMap<>(overrides);
        props.put("bootstrap.servers", "localhost:9092");
        props.put("key.serializer", StringSerializer.class);
        props.put("value.serializer", StringSerializer.class);
        try {
            ProducerConfig config = new ProducerConfig(props);
            System.out.printf("%-27s -> acks=%s, enable.idempotence=%s%n", label,
                    config.getString("acks"), config.getBoolean("enable.idempotence"));
        } catch (ConfigException e) {
            System.out.printf("%-27s -> ConfigException: %s%n", label, e.getMessage());
        }
    }
}
Output
defaults                    -> acks=-1, enable.idempotence=true
acks=1                      -> acks=1, enable.idempotence=false
acks=0                      -> acks=0, enable.idempotence=false
retries=0                   -> acks=-1, enable.idempotence=false
max.in.flight=10            -> ConfigException: To use the idempotent producer, max.in.flight.requests.per.connection must be set to at most 5. Current value is 10.
acks=1 + idempotence=true   -> ConfigException: Must set acks to all in order to use the idempotent producer. Otherwise we cannot guarantee idempotence.
idempotence=false           -> acks=-1, enable.idempotence=false
  • With the defaults, acks is -1, meaning all, and idempotence is on.
  • Setting only acks=1, acks=0 or retries=0 switched idempotence off without any error. This is a trap: an application that lowers acks for speed also loses duplicate protection, and nothing reports it except a log line.
  • max.in.flight.requests.per.connection=10 was refused with a ConfigException, even though idempotence was not set explicitly. The enable.idempotence documentation says conflicting settings disable it silently, but kafka-clients 4.2.2 rejects this one.
  • Asking for idempotence explicitly together with acks=1 failed with "Must set acks to all in order to use the idempotent producer". Setting enable.idempotence=true explicitly is therefore a cheap safety check.

Idempotence protects against duplicates from the producer's own retries within one producer session. It does not stop your application from calling send() twice for the same event, for example after a restart; that needs transactions or deduplication by the consumer.

How the partition is chosen

The partition decides ordering and load. The program sends keyed records and compares the partition with a hash computed by hand, then sends records without a key, then uses a custom partitioner that reserves partition 0 for VIP customers:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.Cluster;
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 Partitioning {

    // sends every "vip-" key to partition 0 and spreads the rest over the others
    public static class VipPartitioner implements Partitioner {
        @Override
        public int partition(String topic, Object key, byte[] keyBytes, Object value,
                byte[] valueBytes, Cluster cluster) {
            int count = cluster.partitionCountForTopic(topic);
            if (((String) key).startsWith("vip-")) {
                return 0;
            }
            return 1 + Utils.toPositive(Utils.murmur2(keyBytes)) % (count - 1);
        }

        @Override
        public void configure(Map<String, ?> configs) {
        }

        @Override
        public void close() {
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        broker.addTopics(new NewTopic("events", 4, (short) 1));
        Map<String, Object> props = Map.of(
                "bootstrap.servers", broker.getBrokersAsString(),
                "key.serializer", StringSerializer.class,
                "value.serializer", StringSerializer.class);
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
            System.out.println("keyed records, actual vs computed partition:");
            for (String key : List.of("alice", "bob", "carol", "dave", "alice")) {
                int actual = producer.send(new ProducerRecord<>("events", key, "x"))
                        .get().partition();
                byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
                int computed = Utils.toPositive(Utils.murmur2(bytes)) % 4;
                System.out.printf("  %-6s -> %d (murmur2 %% 4 = %d)%n", key, actual, computed);
            }

            // 120 records without a key, each with a 1,000-byte value
            String value = "x".repeat(1000);
            List<Future<RecordMetadata>> futures = new ArrayList<>();
            for (int i = 0; i < 120; i++) {
                futures.add(producer.send(new ProducerRecord<>("events", value)));
            }
            List<String> runs = new ArrayList<>();
            int current = -1;
            int length = 0;
            for (Future<RecordMetadata> f : futures) {
                int p = f.get().partition();
                if (p != current && length > 0) {
                    runs.add(length + "");
                    length = 0;
                }
                current = p;
                length++;
            }
            runs.add(length + "");
            System.out.println("120 null-key records, consecutive records per partition: "
                    + runs);
        }

        try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                "bootstrap.servers", broker.getBrokersAsString(),
                "key.serializer", StringSerializer.class,
                "value.serializer", StringSerializer.class,
                "partitioner.class", VipPartitioner.class))) {
            System.out.println("custom partitioner:");
            for (String key : List.of("vip-7", "alice", "vip-2", "bob")) {
                int p = producer.send(new ProducerRecord<>("events", key, "x")).get().partition();
                System.out.println("  " + key + " -> " + p);
            }
        }
        broker.destroy();
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so 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.ERROR);
        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
keyed records, actual vs computed partition:
  alice  -> 1 (murmur2 % 4 = 1)
  bob    -> 2 (murmur2 % 4 = 2)
  carol  -> 2 (murmur2 % 4 = 2)
  dave   -> 2 (murmur2 % 4 = 2)
  alice  -> 1 (murmur2 % 4 = 1)
120 null-key records, consecutive records per partition: [32, 20, 32, 32, 4]
custom partitioner:
  vip-7 -> 0
  alice -> 1
  vip-2 -> 0
  bob -> 1
  • Each key's partition matched murmur2(key bytes), made positive, modulo the partition count. alice went to partition 1 both times. The hash is computed on the serialized key, so the same key always maps to the same partition, from any Java client.
  • bob, carol and dave all landed in partition 2. A few keys can easily collide; distribution only evens out with many keys.
  • Records without a key went to one partition for a run of records, then to another. The default partitioner changes the sticky partition after at least batch.size bytes (16 KB, about 16 of these 1 KB records) have gone to it, so batches fill up. The next partition is chosen at random, weighted towards less loaded brokers, so the run lengths differ from one run to the next.
  • The custom VipPartitioner sent vip-7 and vip-2 to partition 0 and hashed the other keys over partitions 1 to 3.

Two traps follow from the hashing. Adding partitions to a topic changes hash % count, so existing keys move to other partitions and their order across the change is lost. And a few very busy keys make hot partitions, because all of a key's records must go to one place. partitioner.ignore.keys=true spreads keyed records like unkeyed ones, for when the key is only metadata. RoundRobinPartitioner also exists, but its documentation warns of uneven distribution (KAFKA-9965).

Batching and compression

Batching is where the producer's throughput comes from: one request with a thousand records costs little more than a request with one. Compression works on whole batches, so bigger batches also compress better. The program sends 50,000 JSON click events of about 100 bytes with several settings, and reads the producer's own metrics after each run:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
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 BatchingCompression {

    static final int RECORDS = 50000;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        broker.addTopics(new NewTopic("clicks", 3, (short) 1));
        // JSON-like click events: repetitive text, as most real events are
        Random random = new Random(42);
        String[] values = new String[RECORDS];
        for (int i = 0; i < RECORDS; i++) {
            values[i] = "{\"user\":\"user-" + random.nextInt(1000) + "\",\"page\":\"/product/"
                    + random.nextInt(500) + "\",\"action\":\"click\",\"ts\":"
                    + (1700000000000L + i) + "}";
        }
        System.out.printf("%,d records, rough comparison, best of 3 runs%n", RECORDS);
        System.out.println("settings                         ms   records/req  batch bytes"
                + "  compression");
        run(broker, values, "linger.ms=0", Map.of("linger.ms", 0));
        run(broker, values, "linger.ms=5 (default)", Map.of());
        run(broker, values, "linger.ms=20, batch.size=128K",
                Map.of("linger.ms", 20, "batch.size", 131072));
        for (String codec : List.of("gzip", "snappy", "lz4", "zstd")) {
            run(broker, values, "  same + " + codec, Map.of("linger.ms", 20,
                    "batch.size", 131072, "compression.type", codec));
        }
        broker.destroy();
    }

    static void run(EmbeddedKafkaBroker broker, String[] values, String label,
            Map<String, Object> settings) {
        long best = Long.MAX_VALUE;
        Map<String, Double> stats = null;
        for (int attempt = 0; attempt < 3; attempt++) {
            Map<String, Object> props = new HashMap<>(settings);
            props.put("bootstrap.servers", broker.getBrokersAsString());
            props.put("key.serializer", StringSerializer.class);
            props.put("value.serializer", StringSerializer.class);
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
                producer.partitionsFor("clicks"); // fetch metadata before timing
                long start = System.nanoTime();
                for (int i = 0; i < values.length; i++) {
                    producer.send(new ProducerRecord<>("clicks", "user-" + (i % 1000),
                            values[i]));
                }
                producer.flush();
                long ms = (System.nanoTime() - start) / 1000000;
                if (ms < best) {
                    best = ms;
                    stats = new HashMap<>();
                    for (Map.Entry<MetricName, ? extends Metric> e
                            : producer.metrics().entrySet()) {
                        if (e.getKey().group().equals("producer-metrics")) {
                            Object v = e.getValue().metricValue();
                            if (v instanceof Double d) {
                                stats.put(e.getKey().name(), d);
                            }
                        }
                    }
                }
            }
        }
        System.out.printf("%-30s %5d %10.1f %12.0f %10.2f%n", label, best,
                stats.get("records-per-request-avg"), stats.get("batch-size-avg"),
                stats.get("compression-rate-avg"));
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so 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.ERROR);
        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
50,000 records, rough comparison, best of 3 runs
settings                         ms   records/req  batch bytes  compression
linger.ms=0                      352      495.0        16245       1.00
linger.ms=5 (default)            161      495.0        16245       1.00
linger.ms=20, batch.size=128K     81     3846.2       124420       1.00
  same + gzip                    142     5555.6        26531       0.15
  same + snappy                   86     5000.0        39839       0.25
  same + lz4                      50     5000.0        39392       0.25
  same + zstd                     72     5000.0        22870       0.14
  • With linger.ms=0, the run was the slowest. Batches still filled to about 16 KB, because records arrived faster than the I/O thread sent them, but the producer sent more, smaller requests while it waited for nothing.
  • The default linger.ms=5 took about half that time, with the same 16 KB batches and about 495 records per request.
  • Raising batch.size to 128 KB with linger.ms=20 made batches of about 120 KB with nearly 4,000 records per request, and halved the time again.
  • The compression column is compressed size divided by original size, and with a codec the batch column shows the compressed batch. gzip and zstd shrank the data to about 15% of its size, snappy and lz4 to 25%.
  • gzip was the slowest codec, because it costs the most CPU. lz4 was even faster than sending uncompressed, since far fewer bytes had to be copied and written, and zstd matched gzip's ratio in about half of gzip's time.

This is a rough comparison: best of 3 runs on a 2-core Linux container, with the broker in the same JVM, so there is almost no network time. Over a real network, fewer and smaller requests matter even more. lz4 or zstd with a linger.ms of 10 to 50 ms is a common choice for high-volume topics. Each record waits up to linger.ms longer when traffic is light, so latency-sensitive topics keep it low. The broker stores the batch as the producer compressed it (topic setting compression.type=producer), and consumers decompress it.

When a send fails

Errors reach the application through the future and the callback, and with plain KafkaProducer rarely as an exception from send() itself. Three records are chosen to fail in three different places: in the producer, at the broker, and waiting for metadata. The producer's max.block.ms is lowered to 2 seconds:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.errors.RetriableException;
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 SendErrors {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        broker.addTopics(new NewTopic("small", 1, (short) 1)
                .configs(Map.of("max.message.bytes", "1024")));
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                "bootstrap.servers", broker.getBrokersAsString(),
                "key.serializer", StringSerializer.class,
                "value.serializer", StringSerializer.class,
                "max.block.ms", 2000))) {
            attempt("2 MB value, over the producer's max.request.size", producer,
                    new ProducerRecord<>("small", "x".repeat(2000000)));
            attempt("5 KB value, over the topic's max.message.bytes", producer,
                    new ProducerRecord<>("small", "x".repeat(5000)));
            attempt("partition 3 of a 1-partition topic", producer,
                    new ProducerRecord<>("small", 3, null, "hello"));
            attempt("a normal record", producer, new ProducerRecord<>("small", "hello"));
        }
        broker.destroy();
    }

    static void attempt(String label, KafkaProducer<String, String> producer,
            ProducerRecord<String, String> record) {
        System.out.println(label + ":");
        long start = System.nanoTime();
        Future<RecordMetadata> future;
        try {
            future = producer.send(record, (meta, error) -> {
                if (error != null) {
                    System.out.println("   callback got " + error.getClass().getSimpleName());
                }
            });
        } catch (RuntimeException e) {
            System.out.println("   send() threw " + e.getClass().getSimpleName());
            return;
        }
        System.out.printf("   send() returned after %s%n", elapsed(start));
        try {
            RecordMetadata meta = future.get();
            System.out.println("   ok: offset " + meta.offset());
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            System.out.println("   get() threw, cause " + cause.getClass().getSimpleName()
                    + ", retriable: " + (cause instanceof RetriableException));
            System.out.println("   " + cause.getMessage());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    static String elapsed(long start) {
        long ms = (System.nanoTime() - start) / 1000000;
        return ms < 1000 ? "under 1 s" : "about " + Math.round(ms / 1000.0) + " s";
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so 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.ERROR);
        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
2 MB value, over the producer's max.request.size:
   callback got RecordTooLargeException
   send() returned after under 1 s
   get() threw, cause RecordTooLargeException, retriable: false
   The message is 2000088 bytes when serialized which is larger than 1048576, which is the value of the max.request.size configuration.
5 KB value, over the topic's max.message.bytes:
   send() returned after under 1 s
   callback got RecordTooLargeException
   get() threw, cause RecordTooLargeException, retriable: false
   The request included a message larger than the max message size the server will accept.
partition 3 of a 1-partition topic:
   callback got TimeoutException
   send() returned after about 2 s
   get() threw, cause TimeoutException, retriable: true
   Partition 3 of topic small with partition count 1 is not present in metadata after 2000 ms.
a normal record:
   send() returned after under 1 s
   ok: offset 0
  • The 2 MB record exceeded the producer's max.request.size of 1 MB. The producer refused it before buffering: the callback ran before send() even returned, and the future failed with RecordTooLargeException.
  • The 5 KB record passed the producer but not the topic's 1 KB max.message.bytes. send() returned quickly, and the broker's rejection arrived later in the callback.
  • Partition 3 does not exist. send() blocked for about 2 seconds, the max.block.ms, waiting for metadata that would show it. With the default of 60 seconds, the calling thread would stall for a minute.
  • The timeout was marked retriable (it extends RetriableException), the size errors were not. The producer has already retried retriable errors until delivery.timeout.ms before it reports them, so retrying again in application code rarely helps.

Spring's KafkaTemplate turns some of these into exceptions thrown by send(); see KafkaTemplate for that behaviour. For records that must not be lost, check every future or callback, keep acks=all, and give topics a replication factor of 3 with min.insync.replicas=2, so that one broker failure does not stop writes.

Transactions: atomic writes across records

A money transfer writes a debit and a credit, and no reader may see one without the other. A transactional producer makes a group of records, possibly across topics and partitions, visible together or not at all. It needs a transactional.id, which identifies the producer across restarts:

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 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.ProducerRecord;
import org.apache.kafka.common.KafkaException;
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 Transactions {

    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        broker.addTopics("ledger");
        try (KafkaProducer<String, String> producer = producer("ledger-writer")) {
            producer.initTransactions(); // registers the id and fences older instances

            producer.beginTransaction();
            producer.send(new ProducerRecord<>("ledger", "acct-1", "debit 50"));
            producer.send(new ProducerRecord<>("ledger", "acct-2", "credit 50"));
            producer.commitTransaction();
            System.out.println("transfer 1 committed");

            producer.beginTransaction();
            producer.send(new ProducerRecord<>("ledger", "acct-1", "debit 70"));
            producer.flush(); // the record is now on the broker, but not committed
            producer.abortTransaction();
            System.out.println("transfer 2 aborted after its debit reached the broker");

            // a second instance with the same transactional.id, e.g. after a restart
            try (KafkaProducer<String, String> replacement = producer("ledger-writer")) {
                replacement.initTransactions();
                System.out.println("a new instance called initTransactions()");
                String step = "beginTransaction";
                try {
                    producer.beginTransaction();
                    step = "send";
                    producer.send(new ProducerRecord<>("ledger", "acct-1", "debit 99"));
                    step = "commitTransaction";
                    producer.commitTransaction();
                    System.out.println("old instance committed");
                } catch (KafkaException e) {
                    System.out.println("old instance, " + step + "() threw "
                            + e.getClass().getSimpleName());
                }
            }
        }
        System.out.println("read_uncommitted sees: " + read("read_uncommitted"));
        System.out.println("read_committed sees  : " + read("read_committed"));
        broker.destroy();
    }

    static KafkaProducer<String, String> producer(String transactionalId) {
        return new KafkaProducer<>(Map.of(
                "bootstrap.servers", servers,
                "transactional.id", transactionalId,
                "key.serializer", StringSerializer.class,
                "value.serializer", StringSerializer.class));
    }

    static List<String> read(String isolation) {
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", servers);
        props.put("group.id", "reader-" + isolation);
        props.put("auto.offset.reset", "earliest");
        props.put("isolation.level", isolation);
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        List<String> seen = new ArrayList<>();
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
            consumer.subscribe(List.of("ledger"));
            long quietSince = System.currentTimeMillis();
            // stop after 2 quiet seconds, counted from when the group assigned partitions
            while (System.currentTimeMillis() - quietSince < 2000) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(200))) {
                    seen.add(r.offset() + ":" + r.value());
                    quietSince = System.currentTimeMillis();
                }
                if (consumer.assignment().isEmpty()) {
                    quietSince = System.currentTimeMillis();
                }
            }
        }
        return seen;
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so 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.ERROR);
        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
a new instance called initTransactions()
old instance, commitTransaction() threw InvalidProducerEpochException
read_uncommitted sees: [0:debit 50, 1:credit 50, 3:debit 70]
read_committed sees  : [0:debit 50, 1:credit 50]
  • Transfer 1 committed both records, at offsets 0 and 1.
  • Transfer 2's debit reached the broker, at offset 3, before the abort. An abort does not remove records: it writes an abort marker.
  • A second producer with the same transactional.id called initTransactions(), as a restarted instance would. The old instance's next commit then failed with InvalidProducerEpochException, and its "debit 99" never became visible. Older documentation names ProducerFencedException for this case. Either way, another instance has taken over, and the old one can only be closed.
  • A read_uncommitted consumer, the default isolation level, saw the aborted debit. Only read_committed consumers hide it.
  • Offsets 2 and 4 appear in neither list: they hold the commit and abort markers.

This fencing is what makes "zombie" instances harmless: a stalled process that wakes up after its replacement started cannot write. Every consumer of a transactional topic must set isolation.level=read_committed, or the guarantee is lost. Transactions add a round trip per commit, so commit groups of records rather than single ones. Read-process-write pipelines also add the consumer's offsets to the transaction with sendOffsetsToTransaction; the Kafka transactions page covers that.

Choosing producer settings

Goals and the settings that serve them
GoalSettings
No lost and no duplicated recordsDefaults (acks=all, idempotence on), with enable.idempotence=true set explicitly, and every future checked
Per-entity orderingThe entity id as the key; idempotence keeps order across retries
High throughputlinger.ms 10 to 50, batch.size 64 to 256 KB, compression.type=lz4 or zstd
Lowest latency on a quiet topiclinger.ms=0, no compression
Fail fast when the cluster is downLower max.block.ms and delivery.timeout.ms
Atomic multi-record writestransactional.id, with read_committed consumers
Loss is acceptable, speed matters mostacks=1 or 0, knowing that idempotence is then off

Related pages: Kafka consumers, producer and consumer configuration, serialization and topics and partitions. Spring applications usually send through KafkaTemplate, which wraps this producer.