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.
Contents
How the producer turns send() into a write
A Kafka producer appends records to topics. KafkaProducer.send()
Inside the producer, each record goes through these stages:
- Serialize: the key and value serializers turn the objects into byte arrays.
- 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.
- Accumulate: the record is appended to the open batch for that partition, inside a buffer of
bytes (32 MB by default).buffer.memory returns asend() here.Future<RecordMetadata> - Send: the I/O thread, named
, sends a batch when it is full (kafka-producer-network-thread ) or has waitedbatch.size . Batches for partitions led by the same broker share one request, and up to 5 requests per broker may be in flight.linger.ms - Acknowledge: the broker leader writes the batch and replies once enough replicas have it, as
demands. The futures complete with the partition and offset, and callbacks run.acks
Failed requests are retried by the I/O thread, not by your code, until delivery.timeout.mssend()max.block.msKafkaProducer
| Style | Code | Best for |
|---|---|---|
| Fire and forget | send(record) | Metrics or logs where a lost record is acceptable |
| Synchronous | send(record).get() | Low volume, or a caller that must know the outcome |
| Asynchronous | send(record, callback) | Most applications: fast, and errors are still seen |
| Transactional | beginTransaction()commitTransaction() | Several records that must appear together, or exactly-once pipelines |
The examples use kafka-clientsEmbeddedKafkaKraftBrokerspring-kafka-teststartBroker
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:
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);
}
}
}
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
: the record was only in the buffer.send() blocked until the broker replied with partition 0, offset 1. The value "created" took 7 bytes once serialized.get() - The callback ran on
, not onkafka-producer-network-thread | producer-1 . 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.main ,acks = all andenable.idempotence = true make the producer retry untilretries = 2147483647 without writing duplicates. These have been the defaults since the 3.0 release.delivery.timeout.ms is the Kafka 4.0 default (KIP-1030); it was 0 before. Each batch now waits up to 5 ms to fill.linger.ms = 5 : records are sent uncompressed unless you choose a codec, as a later section measures.compression.type = none
close()
acks and the idempotent producer
The acksacks=0acks=1acks=all-1
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
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());
}
}
}
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,
is -1, meaning all, and idempotence is on.acks - Setting only
,acks=1 oracks=0 switched idempotence off without any error. This is a trap: an application that lowersretries=0 for speed also loses duplicate protection, and nothing reports it except a log line.acks was refused with amax.in.flight.requests.per.connection=10 , even though idempotence was not set explicitly. TheConfigException documentation says conflicting settings disable it silently, but kafka-clients 4.2.2 rejects this one.enable.idempotence- Asking for idempotence explicitly together with
failed with "Must set acks to all in order to use the idempotent producer". Settingacks=1 explicitly is therefore a cheap safety check.enable.idempotence=true
Idempotence protects against duplicates from the producer's own retries within one producer session. It does not stop your application from calling send()
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:
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);
}
}
}
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
, 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.murmur2(key bytes) - 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
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.batch.size - The custom
sent vip-7 and vip-2 to partition 0 and hashed the other keys over partitions 1 to 3.VipPartitioner
Two traps follow from the hashing. Adding partitions to a topic changes hash % countpartitioner.ignore.keys=trueRoundRobinPartitioner
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:
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);
}
}
}
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
, 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.linger.ms=0 - The default
took about half that time, with the same 16 KB batches and about 495 records per request.linger.ms=5 - Raising
to 128 KB withbatch.size made batches of about 120 KB with nearly 4,000 records per request, and halved the time again.linger.ms=20 - 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.mslinger.mscompression.type=producer
When a send fails
Errors reach the application through the future and the callback, and with plain KafkaProducersend()max.block.ms
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);
}
}
}
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
of 1 MB. The producer refused it before buffering: the callback ran beforemax.request.size even returned, and the future failed withsend() .RecordTooLargeException - The 5 KB record passed the producer but not the topic's 1 KB
.max.message.bytes returned quickly, and the broker's rejection arrived later in the callback.send() - Partition 3 does not exist.
blocked for about 2 seconds, thesend() , waiting for metadata that would show it. With the default of 60 seconds, the calling thread would stall for a minute.max.block.ms - The timeout was marked retriable (it extends
), the size errors were not. The producer has already retried retriable errors untilRetriableException before it reports them, so retrying again in application code rarely helps.delivery.timeout.ms
Spring's KafkaTemplatesend()acks=allmin.insync.replicas=2
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
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);
}
}
}
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
calledtransactional.id , as a restarted instance would. The old instance's next commit then failed withinitTransactions() , and its "debit 99" never became visible. Older documentation namesInvalidProducerEpochException for this case. Either way, another instance has taken over, and the old one can only be closed.ProducerFencedException - A
consumer, the default isolation level, saw the aborted debit. Onlyread_uncommitted consumers hide it.read_committed - 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_committedsendOffsetsToTransaction
Choosing producer settings
| Goal | Settings |
|---|---|
| No lost and no duplicated records | Defaults (acks=allenable.idempotence=true |
| Per-entity ordering | The entity id as the key; idempotence keeps order across retries |
| High throughput | linger.msbatch.sizecompression.type=lz4zstd |
| Lowest latency on a quiet topic | linger.ms=0 |
| Fail fast when the cluster is down | Lower max.block.msdelivery.timeout.ms |
| Atomic multi-record writes | transactional.idread_committed |
| Loss is acceptable, speed matters most | acks=10 |
Related pages: