Apache Kafka — Event Streaming from Basics to a Platform Service›06 · Producers in depth

Lesson 06 of 17 · How Kafka works

Producers in depth

What happens between producer.send() and a record landing on disk: choosing the partition, batching and compression for throughput, the three acks levels and what each risks, retries and timeouts, idempotence (on by default) to avoid duplicates and reordering, and how to tune a producer for throughput, latency or safety.

Practitioner
Key wordsproducerpartitionersticky partitionerkey hashingbatchingbatch.sizelinger.mscompression.typelz4zstdacksacks=allretriesdelivery.timeout.msenable.idempotencemax.in.flight.requests.per.connectionbuffer.memoryorderinghot partition

The path of one record

producer.send(record)
   │ 1. serialize key and value to bytes
   │ 2. choose a partition (key hash, or sticky for keyless)
   │ 3. add to that partition's batch in memory (buffer.memory)
   │ 4. a sender thread sends full or "lingered" batches to each partition leader
   ▼
leader broker ── writes to its log ── followers copy ── replies when "acks" is satisfied
   │
   ▼ callback: success (with partition and offset) or error

send() is asynchronous: it returns quickly and the result arrives later in a callback or future. Production code must always check that result.

Choosing the partition

Record Partition chosen by
Has a key Hash of the key, modulo the partition count. Same key, same partition
No key The sticky partitioner: fill a batch for one partition, then move to another. Good batching, even spread over time
Explicit partition The partition you set (rarely needed)

Hot partitions: if one key is very busy (one huge customer), its partition gets far more traffic than the others, and only one consumer can process it. Fixes: a finer key (customer + order), or salting the key when strict per-customer order is not needed.

Batching and compression

Sending each record alone wastes network round trips. The producer groups records per partition into batches:

  • batch.size: maximum bytes per batch (default 16 KB; 64–256 KB is common for high throughput).
  • linger.ms: how long to wait for more records before sending a not-yet-full batch (the default is 5 ms in recent versions).
  • compression.type: lz4 or zstd compress whole batches; brokers store them compressed and consumers decompress. Text and JSON often shrink 3 to 5 times.

Bigger batches mean higher throughput and better compression, for a few milliseconds of extra latency.

acks: when is a write "done"?

acks Producer gets success when… Risk
0 It has sent the request Lost if anything fails; no error is ever seen
1 The leader has written it Lost if the leader dies before a follower copied it
all (-1) All in-sync replicas have it Safe as long as min.insync.replicas ≥ 2 (lesson 8)

acks=all is the default since Kafka 3.0. Combined with replication factor 3 and min.insync.replicas=2, a successful write survives the loss of any one broker.

You send a parcel. acks=0: you drop it in a postbox and walk away. acks=1: the post office counter says "got it", but it hasn't left the building yet. acks=all: you wait until the parcel is safely in two different warehouses before you leave. Slower, but a fire in one warehouse can't lose it.

Retries, timeouts and idempotence

Networks fail, leaders move. The producer retries automatically. Retrying creates two dangers:

  1. Duplicates: the first attempt actually succeeded, but the reply was lost, so the record is written twice.
  2. Reordering: batch 1 fails, batch 2 succeeds, batch 1 is retried and lands after batch 2.

The idempotent producer (enable.idempotence=true, the default since Kafka 3.0) solves both within a partition: the broker gives the producer an ID and checks a sequence number on every batch, dropping duplicates and rejecting gaps. It works with up to 5 in-flight requests per connection, so it costs almost nothing.

Time limits:

  • delivery.timeout.ms (default 2 minutes): the total time a record may take, including retries. After it, the callback gets an error.
  • request.timeout.ms: how long to wait for one broker reply.
  • When buffer.memory is full (brokers too slow), send() blocks for up to max.block.ms, then throws.

Idempotence is not end-to-end exactly-once

It stops duplicates caused by the producer's own retries. If your application crashes and sends the same business event again after a restart, that is a new record. Lesson 10 covers transactions and idempotent consumers.

Tuning profiles

Goal Settings
Safety (payments, audit) acks=all, idempotence on, RF 3, min.insync.replicas=2, generous delivery.timeout.ms
Throughput (logs, clicks) linger.ms=10–50, batch.size=128–256 KB, compression.type=zstd or lz4
Low latency linger.ms=0–5, smaller batches, lz4, keep acks=all unless you can lose data

Measure, don't guess

Kafka ships a load generator. A run on a laptop against a 3-broker Docker cluster with acks=all:

$ kafka-producer-perf-test.sh --topic payments --num-records 200000 --record-size 200 --throughput -1 \
    --producer-props bootstrap.servers=kafka-1:9092 acks=all linger.ms=5 compression.type=lz4
200000 records sent, 17111.6 records/sec (3.26 MB/sec), 4296.53 ms avg latency, 7118.00 ms max latency, 4279 ms 50th, 6629 ms 95th, 7035 ms 99th, 7109 ms 99.9th.

Three containers sharing one laptop are far slower than real servers; what matters is comparing settings on the same setup. The high latency here shows the producer's buffer filling faster than the cluster could absorb it: --throughput -1 means "as fast as possible".

Try it: feel the trade-offs

  1. On the lab cluster, run the perf test with acks=1, then acks=all, and compare records/sec and p99 latency.
  2. Repeat with linger.ms=0 and linger.ms=50, and with compression.type=none versus zstd.
  3. Use --throughput 2000 to cap the rate and compare latency with the uncapped run.
  4. Write down which settings you would choose for an audit log and for click tracking, and why.

Going deeper

  • Producers send one request per broker containing batches for many partitions; very many tiny partitions per producer hurt batching.
  • Monitor producer metrics: record-error-rate, request-latency-avg, batch-size-avg, compression-rate-avg, buffer-available-bytes.
  • A record too large error means the record exceeds max.request.size (producer) or message.max.bytes (broker). For large payloads, store them in object storage and send a reference.

Recap

  • The key picks the partition; keyless records use the sticky partitioner; beware hot keys.
  • Batching (linger.ms, batch.size) and compression drive throughput.
  • acks=all with RF 3 and min.insync.replicas=2 makes writes survive a broker loss.
  • Idempotence (default on) removes duplicates and reordering from retries, but not application re-sends.
  • Measure with kafka-producer-perf-test.

This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.