Lesson 02 / 10 · Foundation

Kafka Producer Configuration: acks and Batching

Kafka producer configuration tested on Kafka 4.4: acks, linger.ms, batch.size, compression, partitioning, idempotence and transactions, with real metrics.

2-3 hours intermediate Not completed

On this page · 13 sections
  1. What send() really does
  2. Defaults you get today (Java client, Kafka 4.x)
  3. Batching: linger.ms and batch.size
  4. Partitioning: keys, no keys, and hot partitions
  5. acks, and what “written” means
  6. Idempotence: how the broker spots a retry
  7. Transactions: atomic writes across partitions
  8. Worked example 2: two ways to lose data with a “successful” producer
  9. Common mistakes
  10. Configuration starting points
  11. Hands-on exercise: measure batching and compression
  12. Key Takeaways
  13. Quiz

What send() really does

producer.send() (or produce() in the Python and Go clients) does not talk to the broker. It does four things on your thread and returns:

  1. Serializes the key and value to bytes.
  2. Picks a partition (from the key, or the sticky partitioner if there is no key).
  3. Appends the record to an in-memory batch for that partition, in a buffer of buffer.memory bytes (32 MB by default in the Java client).
  4. Returns a future, or registers your delivery callback.

A separate sender thread drains those batches, groups the batches for the same broker into one produce request, compresses each batch, and waits for the broker’s answer. Retries happen there too, without your code knowing.

Two consequences follow, and most producer bugs come from forgetting one of them:

  • A successful send() means “queued in this process”, not “written to Kafka”. The real result arrives later, in the future or the callback.
  • If the process exits with records still in the buffer, they are gone. Nothing is persisted on the client side.

The worked examples below make both visible.

Defaults you get today (Java client, Kafka 4.x)

Many tutorials, including the first version of this lesson, still describe the 2.x defaults. These are the values the Kafka 4.4.0 Java client actually ships with (read from ProducerConfig on 25 Nov 2026):

SettingDefaultWhat it means
acksallLeader waits for the in-sync replicas before acknowledging (since Kafka 3.0)
enable.idempotencetrueBroker drops retried duplicates (since 3.0)
linger.ms5Wait up to 5 ms to fill a batch (was 0 before Kafka 4.0, KIP-1030)
batch.size16384Upper bound on one partition’s batch, in bytes
max.in.flight.requests.per.connection5Up to 5 unacknowledged requests per broker; ordering is still kept with idempotence on
retries2147483647Retry until delivery.timeout.ms runs out
delivery.timeout.ms120000Total time budget for one record, including retries
request.timeout.ms30000How long one produce request may wait for the broker
max.block.ms60000How long send() may block when the buffer is full or metadata is missing
compression.typenoneBatches go uncompressed unless you ask

If you use librdkafka (Python confluent-kafka, Go, .NET, Node clients), check its defaults separately. In librdkafka enable.idempotence is still false by default, so a Python producer with only bootstrap.servers set can write duplicates on retry, while the Java producer next to it can’t.

Batching: linger.ms and batch.size

A batch for a partition is sent when either:

  • it reaches batch.size bytes, or
  • linger.ms has passed since the first record went in,

whichever happens first. A batch can also go out with linger.ms=0 if records pile up while earlier requests are still in flight, which is why you get some batching even at zero.

Fewer, bigger requests mean less CPU on the broker, fewer network round trips and better compression. The price is that each record may wait up to linger.ms before leaving.

Worked example 1: same traffic, five configs

Setup: Kafka 4.4.0, one KRaft node on localhost, a 3-partition topic, and kafka-producer-perf-test.sh sending 100,000 JSON order events (about 160 bytes each, file orders.jsonl) at a fixed 10,000 records/sec. Only linger.ms and compression.type change between runs. Script: course-code/kafka-mastery/producers/linger_batching.sh.

ConfigAvg latencyp99Avg batch on the wireRecords per requestRequests/sec (derived)
linger.ms=0, none0.85 ms10 ms3,178 B18.5~540
linger.ms=5 (default), none3.97 ms11 ms10,857 B64.6~155
linger.ms=20, none5.59 ms12 ms10,664 B104.6~96
linger.ms=20, lz410.80 ms22 ms6,881 B187.6~53
linger.ms=20, zstd10.99 ms22 ms4,442 B197.2~51

The batch and request columns are the producer’s own metrics (batch-size-avg, records-per-request-avg, printed with --print-metrics). Requests/sec is 10,000 divided by records per request. The max latency in every run was 220–300 ms; that is the first send waiting for topic metadata, not batching.

What to take from it:

  • Going from linger.ms=0 to 5 cut produce requests by about 3.5x and cost about 3 ms of average latency. On a real cluster with hundreds of producers, that request count is what the brokers feel. That trade is why Kafka 4.0 changed the default.
  • linger.ms=20 without compression barely grew the batches (10.7 KB vs 10.9 KB). At this rate a partition collects about 16 KB in well under 20 ms, so batch.size closed the batch first. Raising linger.ms past the point where batch.size fills does nothing except add risk at low traffic.
  • Compression changed the picture more than linger did. compression-rate-avg was 0.289 for lz4 and 0.175 for zstd: the same 1.53 MB/s of JSON went over the network as roughly 0.44 MB/s and 0.27 MB/s. Because batch.size is checked against the estimated compressed size, each batch held more records and the requests per second halved again.
  • Compressed batches waited the full 20 ms (avg latency ~11 ms vs ~5.6 ms), because they no longer hit batch.size early. If you turn on compression, revisit linger.ms; you may be adding latency you did not plan for.

The perf tool’s default --record-size payload is random letters, which compresses far worse than real JSON. Test compression with a sample of your real messages, or you will underestimate it.

A reasonable starting point for most services: linger.ms 5–20, compression.type=lz4 (cheap CPU) or zstd (smaller, a bit more CPU), and leave batch.size at 16–64 KB. Then measure with your payloads.

Partitioning: keys, no keys, and hot partitions

With a key, the Java client hashes the key bytes with murmur2 and takes it modulo the partition count. Same key, same partition, so records for one order or one user stay in order. Add partitions and most keys move to a different partition; the Kafka partitions article measures how many.

Without a key, records do not go round-robin, which is what older tutorials say. Since Kafka 2.4 the producer uses a sticky partitioner: it fills a batch for one partition, then switches. Kafka 3.3 (KIP-794) made the switch happen after about batch.size bytes and skip slow brokers.

You can see it on a 6-partition topic:

# 30 keyless records from kafka-console-producer
keyless:0:30
keyless:1:0
keyless:2:0
keyless:3:0
keyless:4:0
keyless:5:0

# then 60,000 keyless records from the perf tool
keyless:0:7596
keyless:1:11090
keyless:2:10646
keyless:3:10993
keyless:4:9047
keyless:5:10658

All 30 small records landed in partition 0. Over 60,000 records the spread evens out to 7.6k–11.1k per partition, not exactly 10k each. If a consumer test sends 10 keyless messages and sees only one partition get data, nothing is broken.

Hot partitions. A key with a lot more traffic than the rest pins all of it to one partition and therefore to one consumer thread. Typical culprits: a tenant id when one tenant is 40% of traffic, a country field, or a null-ish default like "unknown" that half your events share. Two fixes, both with a cost:

  • Key by something finer that still gives the ordering you need. If you only need per-order ordering, key by order_id, not customer_id.
  • Salt only the hot keys: key = f"{tenant}:{order_id % 8}" spreads one tenant over 8 sub-keys. You lose ordering across those 8, so do it only where the consumer doesn’t need it.

Custom partitioners are rarely the answer. A partitioner that routes by current hour, for example, sends every record of that hour to one partition, which is the hot-partition problem made on purpose.

acks, and what “written” means

acks decides when the broker answers:

  • acks=0: no answer at all. The producer can’t retry what it never hears about. Only for data you could lose without anyone noticing.
  • acks=1: the leader wrote it to its log. If the leader dies before a follower copies the record, the record is lost even though your callback said success. Lesson 1’s worked example shows such a record on disk but never served to consumers.
  • acks=all: every in-sync replica has it. Pair it with the topic setting min.insync.replicas=2 on a 3-replica topic; otherwise “all” can mean “the leader alone” after the followers drop out of the ISR.

acks=all with RF 3 and min.insync.replicas=2 is the normal production setting, and since Kafka 3.0 it’s the default acks. The latency cost is one follower fetch round trip, usually a few milliseconds inside one data centre.

Idempotence: how the broker spots a retry

The duplicate scenario: the broker writes a batch, the acknowledgement is lost on the network, the producer retries, and the batch is written twice.

With enable.idempotence=true the broker gives the producer a producer id, and the producer numbers every record per partition with a sequence number. The broker remembers the last sequences of each producer id for each partition; a retried batch with sequences it has already written is acknowledged and not appended again. A gap in the sequence is rejected as out of order, which is how ordering survives 5 in-flight requests.

You can see the ids in the log segment itself with kafka-dump-log.sh. Three records from the Java console producer (idempotent by default), then one record sent with enable.idempotence=false:

baseOffset: 0 lastOffset: 2 count: 3 baseSequence: 0 lastSequence: 2 producerId: 13 producerEpoch: 0 ... isTransactional: false
| offset: 0 ... sequence: 0 key: ord-1 payload: CREATED
| offset: 1 ... sequence: 1 key: ord-1 payload: PAID
| offset: 2 ... sequence: 2 key: ord-1 payload: SHIPPED
baseOffset: 3 lastOffset: 3 count: 1 baseSequence: -1 lastSequence: -1 producerId: -1 producerEpoch: -1 ...
| offset: 3 ... sequence: -1 key: ord-1 payload: DELIVERED

producerId: -1 and sequence: -1 mean the broker has nothing to compare a retry against. That record could be duplicated.

What idempotence does not cover:

  • It is per producer session. Restart the process and it gets a new producer id, so a record your app re-sends after a crash is a new record. For that you need a transactional.id or an idempotent consumer (dedupe on a business key).
  • It does not stop your code from calling send() twice for the same event.

Transactions: atomic writes across partitions

Transactions let a producer write to several partitions (and commit consumer offsets) so that either all of it becomes visible or none of it does. The usual use is read-process-write: consume from topic A, write to topic B, commit the offset of A, all in one transaction.

Two things surprise people the first time. The aborted records are physically written to the log, and the hiding is done by the consumer’s isolation.level. Worked example (Python confluent-kafka 2.16.2, script producer_pitfalls.py txn): commit a transaction of 3 records, then write 2 more and abort.

p = Producer({"bootstrap.servers": B, "transactional.id": "payments-writer-1"})
p.init_transactions()

p.begin_transaction()
for i in range(3):
    p.produce(topic, value=f"committed-{i}")
p.commit_transaction()

p.begin_transaction()
for i in range(2):
    p.produce(topic, value=f"aborted-{i}")
p.flush()
p.abort_transaction()
read_uncommitted sees: 5
read_committed sees:   3
$ kafka-get-offsets.sh --bootstrap-server localhost:9092 --topic payments-txn-1dd9f6
payments-txn-1dd9f6:0:7

Five records used seven offsets: the broker appended a COMMIT control marker at offset 3 and an ABORT marker at offset 6 (kafka-dump-log.sh shows them as isControl: true with endTxnMarker). So:

  • Consumers that should not see aborted data must set isolation.level=read_committed. The Java consumer’s default is read_uncommitted.
  • Offsets in a transactional topic have gaps. Never compute “number of messages” as end offset minus start offset, and never assume offset n+1 exists.
  • A read_committed consumer can’t read past an open transaction, so a producer that begins a transaction and hangs holds back every consumer of that partition until transaction.timeout.ms (60 s by default) aborts it.

Skip transactions for logs, metrics and anything where an idempotent consumer is simpler. They add a coordinator round trip per commit and the markers above.

Worked example 2: two ways to lose data with a “successful” producer

Both from producer_pitfalls.py against the same local broker.

Exit without flush. Produce 10,000 records, then let the producer go out of scope as a short script would:

produce() returned for 10000 records
records in topic: 0

Every produce() call returned without error and nothing reached Kafka. The fix is one line: call producer.flush() (Python, Go) or producer.close() (Java) before exit, including in your SIGTERM handler. A Kubernetes rollout sends SIGTERM to every pod, so this bites on every deploy.

Broker down, error only in the callback. Point the producer at a port with no broker and set message.timeout.ms=10000 (librdkafka’s name for the delivery timeout):

produce() returned after 0.05 ms, no error
callback after 10.0s: KafkaError{code=_MSG_TIMED_OUT,val=-192,str="Local: Message timed out"}

The call that “sent” the payment returned in 50 microseconds. The failure showed up 10 seconds later, only in the delivery callback. With the Java default delivery.timeout.ms=120000, that is two minutes. Code that never checks the future or the callback logs nothing and loses the record.

Common mistakes

  1. Treating send() returning as success. Check the callback or future, and count failures in a metric. Calling .get() on every Java future makes it synchronous and caps you at one record per round trip; use callbacks instead.
  2. No flush()/close() on shutdown. Example 2 lost 10,000 of 10,000 records.
  3. Assuming librdkafka has the Java defaults. Set enable.idempotence=true explicitly in Python, Go and .NET producers.
  4. Setting retries=0 “to avoid duplicates”. With idempotence on, retries do not create duplicates, and with retries=0 a single leader election (a few hundred milliseconds) turns into lost records.
  5. Making delivery.timeout.ms very short. It must be at least linger.ms + request.timeout.ms; the client refuses to start otherwise. Below about 30 s, a routine broker restart fails records that would have succeeded a few seconds later.
  6. Logging every record synchronously from the callback. The callback runs on the producer’s I/O thread (Java) or inside poll()/flush() (librdkafka). Slow callbacks stall the sender.
  7. Benchmarking compression on random bytes. Random payloads hardly compress; JSON in example 1 compressed to 17–29% of its size.

Configuration starting points

Throughput-heavy event stream (clicks, logs, CDC):

acks=all
enable.idempotence=true
linger.ms=20
batch.size=65536
compression.type=zstd

Latency-sensitive request path (payment events, notifications):

acks=all
enable.idempotence=true
linger.ms=1
compression.type=lz4
delivery.timeout.ms=30000

In both cases set min.insync.replicas=2 on the topic, and watch record-error-rate, record-retry-rate and buffer-available-bytes in the producer metrics. A shrinking buffer means the producer is producing faster than the brokers accept, and send() will start blocking for up to max.block.ms.

Hands-on exercise: measure batching and compression

Goal: prove to yourself how much linger.ms, batch.size and compression change producer throughput. Use the local cluster from Lesson 1. These runs flood the producer (--throughput -1), unlike worked example 1, which used a fixed rate.

bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic perf --partitions 3 --replication-factor 1

# 1. No batching delay, small batches, no compression
bin/kafka-producer-perf-test.sh --topic perf --num-records 500000 --record-size 200 --throughput -1 \
  --producer-props bootstrap.servers=localhost:9092 acks=all linger.ms=0 batch.size=16384 compression.type=none

# 2. Wait up to 20 ms to fill bigger batches, compress them
bin/kafka-producer-perf-test.sh --topic perf --num-records 500000 --record-size 200 --throughput -1 \
  --producer-props bootstrap.servers=localhost:9092 acks=all linger.ms=20 batch.size=131072 compression.type=lz4

# 3. Same as 2 but acks=1
bin/kafka-producer-perf-test.sh --topic perf --num-records 500000 --record-size 200 --throughput -1 \
  --producer-props bootstrap.servers=localhost:9092 acks=1 linger.ms=20 batch.size=131072 compression.type=lz4

Write down records/sec, average latency and p99 for each run, then answer: why can a longer linger.ms give lower latency here? What does run 3 trade away for its extra speed?

What you should see, and why

One run on a laptop (your numbers will differ; the ratios are what matter):

RunRecords/secAvg latencyp99
1. linger 0, 16 KB, none~392,000227 ms341 ms
2. linger 20, 128 KB, lz4~529,0009 ms36 ms
3. as 2 with acks=1~574,0004 ms14 ms
  • With --throughput -1 the producer is flooded. Tiny batches mean many small requests, so records queue up in the producer’s buffer and wait; that queueing is the latency you see in run 1. Bigger, compressed batches move more data per request, so the queue drains faster and latency falls even though each batch may wait up to 20 ms. At low traffic the trade-off flips: linger.ms then adds up to its value to every send.
  • acks=1 returns as soon as the leader has the write. If the leader dies before followers copy it, that write is lost. Keep acks=all (with min.insync.replicas=2 on a real cluster) for data you cannot lose.

Key Takeaways

  1. send() only queues the record. Success or failure arrives in the callback, and anything still queued at exit is lost unless you flush() or close().
  2. Kafka 4.x Java producers default to acks=all, idempotence on and linger.ms=5; librdkafka clients still default to idempotence off.
  3. linger.ms stops helping once batch.size fills first. Compression often gives more than linger: 0.29 (lz4) and 0.18 (zstd) of the original size on JSON in example 1.
  4. Keyless records stick to one partition per batch; keyed records keep per-key order. Key by the smallest thing that still needs ordering.
  5. Idempotence removes duplicates from retries within one producer session; transactions add atomic multi-partition writes, offset gaps, and require read_committed consumers.

Quiz

  1. At 10,000 records/sec, raising linger.ms from 5 to 20 barely changed the uncompressed batch size, but adding lz4 nearly doubled records per request. Why?
  2. A Python service using confluent-kafka with only bootstrap.servers set retries after a timeout and you see duplicate events. The Java service next to it, with the same settings, doesn’t. Why, and what is the fix?
  3. A transactional topic’s partition has start offset 0 and end offset 7, but a read_committed consumer reads 3 records. Give two reasons the counts differ.
Show answers
  1. At that rate a partition fills batch.size (16 KB) before 20 ms pass, so batch.size closes the batch and the extra linger is never used. batch.size is compared with the estimated compressed size, so with lz4 (about 0.29 of the original) more records fit before the batch is full.
  2. librdkafka defaults to enable.idempotence=false, the Java client to true. Without a producer id and sequence numbers, the broker can’t tell the retry from a new batch. Set enable.idempotence=true in the Python producer.
  3. Commit and abort markers take up offsets (each transaction adds one), and records from aborted transactions are in the log but hidden from read_committed consumers. In the worked example: 3 committed + 2 aborted + 2 markers = 7 offsets.

Done with this lesson?

Marking it complete updates the sidebar, the course page and the Continue button.