Inside the Kafka producer: send(), batching, the partitioner and transactions
How a record travels from send() to the broker (RecordAccumulator, sender thread, buffer.memory, max.block.ms), measured effects of linger.ms and compression on Kafka 4.3, the uniform sticky partitioner, retrying the right way, and transactions from the inside: coordinator, control markers, LSO, fencing.
On this page
1. The problem
An ordering service calls kafkaTemplate.send() in its controller. Kafka goes into maintenance for 2 minutes, and the whole ordering API times out, including endpoints that don't use Kafka: all 200 Tomcat threads are stuck in send(), each for up to 60 seconds.
2. Key idea
On your thread, send() does four things: waits for the topic's metadata, serialises, picks a partition, and appends to a batch in the accumulator. The sender thread groups batches by broker and sends when a batch is full (batch.size, 16 KB) or linger.ms has elapsed. Missing metadata or a full buffer makes send() block for up to max.block.ms.
linger.ms (5,000 msg/s, 179 B) |
Requests | Records per request | Extra delay |
|---|---|---|---|
| 0 | 14,333 | 1.0 | 0.3 ms |
| 5 (default since Kafka 4.0) | 554 | 27.3 | ~3 ms |
| 20 | 147 | 104.9 | ~11 ms |
Compression works on whole batches: zstd and gzip shrink JSON to about 1/10, lz4 and snappy to about 1/5. Without a key, the producer sticks to one partition for about batch.size bytes before moving on (uniform sticky, Kafka 3.3), favouring less busy brokers.
2.1 Which settings?
| Choice | Use when | Don't use when |
|---|---|---|
max.block.ms 1–2 s |
send() on a path with an SLA (an HTTP request) |
background jobs that can wait |
linger.ms 5–20 + lz4 |
high throughput, a few ms of delay is fine | you need the lowest per-record latency |
zstd |
large topics: logs, CDC, analytics | latency comes first |
Large delivery.timeout.ms |
riding out long leader outages | callers need an early failure |
Outbox instead of send() in the request |
events must survive a Kafka outage | losing an event is fine |
Producer callbacks run on the sender thread: writing a DB or calling HTTP there makes every other batch wait. Don't set partitioner.class (the deprecated classes disable slow-broker avoidance).
3. In Java
A producer for a path with an SLA: no hung HTTP threads.
Properties p = new Properties();
p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
p.put(ProducerConfig.ACKS_CONFIG, "all");
p.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
p.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 1_500); // don't hold a thread for 60 s
p.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 30_000); // instead of retries=30
p.put(ProducerConfig.LINGER_MS_CONFIG, 10);
p.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4");
producer.send(record, (meta, ex) -> {
if (ex != null) metrics.increment("kafka.send.failed"); // only light work on the sender thread
});
// Kafka maintenance: send() throws TimeoutException after 1.5 s, the controller returns 503 instead of hangingTimeoutException: Expiring N record(s) means records sat longer than delivery.timeout.ms: raising retries is pointless. Other languages: librdkafka (Go, Python, Node.js) has similar linger.ms and queue.buffering.max.messages.
Transactions from the inside
- The coordinator is the broker leading partition
hash(transactional.id) % 50of__transaction_state.initTransactions()issues a PID and a new epoch; an older instance with the sametransactional.idthat keeps sending getsInvalidProducerEpochException: it's been fenced. EndTxn(COMMIT)writes a control marker into every participating partition; markers take an offset, so offsets have "gaps".- The LSO (last stable offset) is the first offset of a still-open transaction.
read_committedconsumers stop there, even for other producers' records committed later. Lag grows with no error. - Keep transactions under 1 s;
transaction.timeout.msdefaults to 60 s; watchLastStableOffsetLag; clear hung transactions withkafka-transactions.sh find-hangingandabort. - A role-based fixed
transactional.id(a StatefulSet pod) fences zombies and completes unfinished transactions; a random one loses fencing. - Kafka 4.0 (KIP-890) bumps the epoch after every transaction, so slow retries from an old transaction can't leak into the next.
4. Working with AI
Hand to AI: producer configs for a stated goal, kafka-producer-perf-test.sh runs with real payloads, tests simulating a dead broker.
Check in AI-written code:
- Short
max.block.mson SLA paths; never the 60 s default inside a controller. - No
retries=30; bounded bydelivery.timeout.ms. - Callbacks don't write to a DB or call HTTP.
- No deprecated
partitioner.class. - Transactions are short;
transactional.idis stable per instance.
5. Exercises
Exercise 1: Review a "fault tolerant" config
The AI configured a producer, saying "30 retries, so no messages lost": retries=30, default max.block.ms, send() called in the controller, a callback that writes send status to the DB. Find the problems and fix them.
Solution to Exercise 1
retries=30isn't the real limit: retries are bounded bydelivery.timeout.ms(120 s by default). A lowretriescan even run out before a new leader comes up.- The default
max.block.msof 60 s: when brokers struggle, HTTP threads are held, and once the pool is exhausted the whole API hangs. - A callback writing to the DB runs on the sender thread: a slow DB makes every batch wait.
Fix: drop retries, set delivery.timeout.ms to your SLA; max.block.ms 1–2 s with a 503; the callback only bumps a metric, DB writes go to a separate executor. If events must not be lost, use an outbox instead of send() in the request.
Exercise 2: Read a stalled-consumer incident
A read_committed consumer on payments hasn't moved since 10:05; lag grows steadily, no exceptions. A read_uncommitted consumer on the same topic keeps going. At 10:05 a relay pod froze in a long GC while holding an open transaction. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: the open transaction pins the LSO.
read_committedwon't read past it, not even other producers' records committed afterwards. - 15 minutes:
kafka-transactions.sh find-hangingto find it, thenabort; or start a new instance with the sametransactional.idto fence it and abort the unfinished transaction. - Root fix: a short
transaction.timeout.ms(tens of seconds), transactions under 1 s, no slow DB or HTTP calls inside a transaction; alert onLastStableOffsetLag.
Summary
send()goes into the accumulator; the sender thread sends batches.send()blocks up tomax.block.ms; keep it short on SLA paths.- A few ms of
linger.mscuts requests by tens of times. - Retries are bounded by
delivery.timeout.ms, notretries. - A long-open transaction pins the LSO and stalls every
read_committedconsumer.
Read more: Part 2: Consumer groups, rebalancing and liveness.
Practice interview questions on this topic
- How does Kafka choose a record's partition, and what goes wrong when you change a live topic's partition count?
- How does KafkaProducer.send() work internally: async sends, batching, linger.ms, compression and timeouts?
- How do Kafka transactions and exactly-once work under the hood, and why must a consumer writing to a DB still be idempotent?
Comments
Community rules