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:
- Serializes the key and value to bytes.
- Picks a partition (from the key, or the sticky partitioner if there is no key).
- Appends the record to an in-memory batch for that partition, in a buffer of
buffer.memorybytes (32 MB by default in the Java client). - 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):
| Setting | Default | What it means |
|---|---|---|
acks | all | Leader waits for the in-sync replicas before acknowledging (since Kafka 3.0) |
enable.idempotence | true | Broker drops retried duplicates (since 3.0) |
linger.ms | 5 | Wait up to 5 ms to fill a batch (was 0 before Kafka 4.0, KIP-1030) |
batch.size | 16384 | Upper bound on one partition’s batch, in bytes |
max.in.flight.requests.per.connection | 5 | Up to 5 unacknowledged requests per broker; ordering is still kept with idempotence on |
retries | 2147483647 | Retry until delivery.timeout.ms runs out |
delivery.timeout.ms | 120000 | Total time budget for one record, including retries |
request.timeout.ms | 30000 | How long one produce request may wait for the broker |
max.block.ms | 60000 | How long send() may block when the buffer is full or metadata is missing |
compression.type | none | Batches 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.sizebytes, or linger.mshas 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.
| Config | Avg latency | p99 | Avg batch on the wire | Records per request | Requests/sec (derived) |
|---|---|---|---|---|---|
linger.ms=0, none | 0.85 ms | 10 ms | 3,178 B | 18.5 | ~540 |
linger.ms=5 (default), none | 3.97 ms | 11 ms | 10,857 B | 64.6 | ~155 |
linger.ms=20, none | 5.59 ms | 12 ms | 10,664 B | 104.6 | ~96 |
linger.ms=20, lz4 | 10.80 ms | 22 ms | 6,881 B | 187.6 | ~53 |
linger.ms=20, zstd | 10.99 ms | 22 ms | 4,442 B | 197.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=0to 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=20without 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, sobatch.sizeclosed the batch first. Raisinglinger.mspast the point wherebatch.sizefills does nothing except add risk at low traffic.- Compression changed the picture more than linger did.
compression-rate-avgwas 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. Becausebatch.sizeis 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.sizeearly. If you turn on compression, revisitlinger.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, notcustomer_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 settingmin.insync.replicas=2on 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.idor 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 isread_uncommitted. - Offsets in a transactional topic have gaps. Never compute “number of messages” as end offset minus start offset, and never assume offset
n+1exists. - A
read_committedconsumer can’t read past an open transaction, so a producer that begins a transaction and hangs holds back every consumer of that partition untiltransaction.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
- 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. - No
flush()/close()on shutdown. Example 2 lost 10,000 of 10,000 records. - Assuming librdkafka has the Java defaults. Set
enable.idempotence=trueexplicitly in Python, Go and .NET producers. - Setting
retries=0“to avoid duplicates”. With idempotence on, retries do not create duplicates, and withretries=0a single leader election (a few hundred milliseconds) turns into lost records. - Making
delivery.timeout.msvery short. It must be at leastlinger.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. - 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. - 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):
| Run | Records/sec | Avg latency | p99 |
|---|---|---|---|
| 1. linger 0, 16 KB, none | ~392,000 | 227 ms | 341 ms |
| 2. linger 20, 128 KB, lz4 | ~529,000 | 9 ms | 36 ms |
| 3. as 2 with acks=1 | ~574,000 | 4 ms | 14 ms |
- With
--throughput -1the 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.msthen adds up to its value to every send. acks=1returns as soon as the leader has the write. If the leader dies before followers copy it, that write is lost. Keepacks=all(withmin.insync.replicas=2on a real cluster) for data you cannot lose.
Key Takeaways
send()only queues the record. Success or failure arrives in the callback, and anything still queued at exit is lost unless youflush()orclose().- Kafka 4.x Java producers default to
acks=all, idempotence on andlinger.ms=5; librdkafka clients still default to idempotence off. linger.msstops helping oncebatch.sizefills first. Compression often gives more than linger: 0.29 (lz4) and 0.18 (zstd) of the original size on JSON in example 1.- Keyless records stick to one partition per batch; keyed records keep per-key order. Key by the smallest thing that still needs ordering.
- Idempotence removes duplicates from retries within one producer session; transactions add atomic multi-partition writes, offset gaps, and require
read_committedconsumers.
Quiz
- At 10,000 records/sec, raising
linger.msfrom 5 to 20 barely changed the uncompressed batch size, but adding lz4 nearly doubled records per request. Why? - A Python service using
confluent-kafkawith onlybootstrap.serversset 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? - A transactional topic’s partition has start offset 0 and end offset 7, but a
read_committedconsumer reads 3 records. Give two reasons the counts differ.
Show answers
- At that rate a partition fills
batch.size(16 KB) before 20 ms pass, sobatch.sizecloses the batch and the extra linger is never used.batch.sizeis compared with the estimated compressed size, so with lz4 (about 0.29 of the original) more records fit before the batch is full. - librdkafka defaults to
enable.idempotence=false, the Java client totrue. Without a producer id and sequence numbers, the broker can’t tell the retry from a new batch. Setenable.idempotence=truein the Python producer. - Commit and abort markers take up offsets (each transaction adds one), and records from aborted transactions are in the log but hidden from
read_committedconsumers. In the worked example: 3 committed + 2 aborted + 2 markers = 7 offsets.