Kafka producers: acks, retries and batching
A producer is the code that writes into Kafka: your application, a change-data-capture tool, or a Spark query with a Kafka sink. A handful of producer settings decide whether a write can be lost, whether it can be repeated, and how much throughput you get. This lesson explains them in the order a message meets them, and shows what Spark sets for you.
Step 4 · Structured Streaming · Silver · Kafka in depth, lesson 1 of 2
On this page
Read first: Consumer groups and offsets (skip if you know it)
In plain words first
Sending a parcel, you make three choices. Which branch it goes to (the address decides). Whether you want a receipt: none, a receipt from the counter clerk, or a receipt only once the parcel is also in the back-room safe. And whether to wait a moment to fill the van, or drive each parcel over on its own.
A KafkaKafka: A system that stores streams of events in topics, in order within each partition, so many readers can read them, and read them again, at their own pace. Learn more → producer makes the same three choices for every message: the partitionpartition: In Kafka, one ordered slice of a topic, read in order. In Spark, one chunk of a DataFrame's rows, processed as one task. Learn more →, the acknowledgement it waits for (acks), and how long to wait to fill a batch (linger.ms). The rest of this lesson is those three, plus what happens when a receipt never comes.
The life of one message
Partition · choose
Batch · wait a little
batch.size (16 KB by default) or when linger.ms has passed (5 ms by default since Kafka 4.0; 0 before).Send · to the leader
compression.type set, the whole batch is compressed first.Acknowledge · acks
acks=all (the default), the leader answers only once every in-sync replicain-sync replicas: The copies of a partition that are fully caught up with the leader. Only they can become leader without losing data. Learn more → has the batch. Only then does the producer count it as written.Retry · no answer
delivery.timeout.ms (2 minutes by default). After that, your code gets an error.acks: which receipt you wait for
| Setting | The producer waits for | Can a write be lost? | Use it for |
|---|---|---|---|
acks=0 | Nothing | Yes, silently | Metrics you can afford to drop |
acks=1 | The leader writing it | Yes, if the leader dies before followers copy it | Rarely worth it today |
acks=all | Every in-sync replica | Not while one in-sync replica survives | Everything else; the default |
acks=all waits for the replicas that are currently in sync, which might be just the leader if the others fell behind. The topictopic: A named stream of events in Kafka or Pub/Sub, such as "orders". Producers write to it; consumers read from it. Learn more → setting min.insync.replicas closes that gap; Kafka in production shows the combination that survives a broker failure.
Retries without duplicates
Retries are how a producer avoids losing data. They also create a risk: if the broker stored the batch but the acknowledgement got lost on the way back, the retry writes it a second time. The idempotentidempotent: Safe to run again: running a step twice gives the same result as running it once. Learn more → producer fixes this. Each producer gets an id, and every batch carries a sequence number per partition. A broker that sees a sequence number it already stored drops the copy.
- It is on by default (
enable.idempotence=true), together withacks=alland effectively unlimitedretries. - It also keeps order: with up to 5 requests in flight per connection (the default), a retried batch cannot overtake a later one.
- It only covers retries inside one producer session. If your application crashes and sends the same event again after restarting, Kafka sees a new message. That repeat needs an event id that consumersconsumer: An application that reads events from a topic and keeps track of how far it has read. Learn more → check: Delivery guarantees.
acks=1, or retries=0, quietly switches idempotence off unless you enabled it explicitly. Changing one producer setting for speed can bring back duplicates and reordering.Batching and compression
Sending one message per request wastes most of the time on round trips. Waiting a few milliseconds to fill a batch, and compressing the batch, multiplies throughput. The trade-off is a little latency:
| Setting | Default | Raise it when |
|---|---|---|
linger.ms | 5 | Throughput matters more than a few extra milliseconds (10 to 100 is common) |
batch.size | 16384 bytes | Messages are large or traffic is heavy (64 KB to 1 MB) |
compression.type | none | Almost always: lz4 or zstd for JSON-like data |
Compression works on whole batches, so better batching also means better compression. JSON compresses very well, often to a fraction of its size, which cuts network and broker disk at the same time.
Writing to Kafka from Spark
The Kafka sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more → turns each row into one message. It expects a value column (string or binary) and optionally key, headers, topic and partition. Producer settings are passed with a kafka. prefix:
(alerts .select(F.col("account_id").cast("string").alias("key"), F.to_json(F.struct("*")).alias("value")) .writeStream.format("kafka") .option("kafka.bootstrap.servers", "broker:9092") .option("topic", "alerts") .option("kafka.compression.type", "zstd") .option("kafka.linger.ms", "20") .option("checkpointLocation", "s3://chk/alerts/") .start())
Spark's checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more → makes the query recover exactly, but the Kafka sink itself is at-least-onceat-least-once: No event is lost, but after a failure some can be processed or written twice. Learn more →: a retried micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → sends all of its messages again, and the idempotent producer cannot tell, because they are new sends. Put an event id in every message so readers can drop repeats.
Common mistakes
- Lowering acks to 1 for speed — It risks losing writes and switches idempotence off. Tune linger.ms and compression instead.
- Believing the idempotent producer gives end-to-end exactly-onceexactly-once: Each event affects the output exactly one time, even when work is retried after a failure. Learn more → — It removes copies from its own retries only. Restarts and Spark batch retries still repeat messages.
- Leaving compression off — JSON sent uncompressed costs network and disk for nothing. lz4 or zstd is nearly free.
- Sending without a key when order matters — Keyless messages spread across partitions and lose their relative order.
Key takeaways
- The key decides the partition; keyless messages are spread across partitions in batches.
- acks=all waits for every in-sync replica and is the default; acks=0 and 1 can lose writes.
- The idempotent producer, on by default, removes duplicates from its own retries only.
- linger.ms, batch.size and compression trade a few milliseconds for much more throughput.
Interview prep
THE QUESTION
"What do acks=all and enable.idempotence=true each protect against?"
Avoid: "set acks=1 for performance" without saying it can lose acknowledged writes and quietly switches off idempotence.
Follow-ups · answer out loud, then open
Follow-up"How does the idempotent producer detect a duplicate?"
Scenario"A producer sends 50,000 small JSON events a second and the brokers' network is saturated. What do you change?"
Trap"With the idempotent producer on, Spark writing to Kafka is exactly-once."
Check yourself
3 questionsThe broker stored a batch but the acknowledgement was lost. The producer retries. With idempotence on, what happens?
Show the answer
The broker recognises the sequence number and drops the copy. Producer id plus a sequence number per partition lets the broker spot the repeat.
Which change can quietly turn idempotence off?
Show the answer
acks=1. Idempotence needs acks=all; a conflicting setting disables it unless it was explicitly enabled.
A Spark query writing to Kafka retries a micro-batch. What do consumers see?
Show the answer
The messages of that batch a second time. The retried batch is sent as new messages; the Kafka sink is at-least-once.
Practise this
Interview problems on streaming, graded on hidden tests
Keep going
Up next · Kafka in depth · lesson 2 of 2 · 7 min readSchemas and Schema Registry
JSON, Avro or Protobuf, compatibility modes and who upgrades first, and decoding registry messages in Spark.
Related lessons
Delivery guarantees end to endStructured Streaming · 7 min read
Ordering and out-of-order events
Previous: Incremental file ingestion
Primary sources: Producer configs · Kafka design: the producer · Kafka design: message delivery semantics · Spark: writing data to Kafka