Skip to content
Silver 7 min read · Kafka 2 practice problems ↓

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

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

With a key, the producer hashes the key and takes it modulo the partition count, so a key always goes to the same partition. Without a key, it sticks to one partition until about one batch has been sent there, then moves on, which spreads load in full batches.

Batch · wait a little

The message joins a batch for that partition. The batch is sent when it reaches 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

The batch goes to the brokerbroker: One server in a Kafka cluster. Each stores some partitions and serves reads and writes for them. Learn more → that leads that partition. With compression.type set, the whole batch is compressed first.

Acknowledge · acks

With 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

No answer, or a temporary error? The producer sends the batch again, for up to delivery.timeout.ms (2 minutes by default). After that, your code gets an error.

acks: which receipt you wait for

SettingThe producer waits forCan a write be lost?Use it for
acks=0NothingYes, silentlyMetrics you can afford to drop
acks=1The leader writing itYes, if the leader dies before followers copy itRarely worth it today
acks=allEvery in-sync replicaNot while one in-sync replica survivesEverything 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 with acks=all and effectively unlimited retries.
  • 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.
Watch out: setting 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:

SettingDefaultRaise it when
linger.ms5Throughput matters more than a few extra milliseconds (10 to 100 is common)
batch.size16384 bytesMessages are large or traffic is heavy (64 KB to 1 MB)
compression.typenoneAlmost 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:

PySpark · Keyed JSON messages with compression
(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?"

acks=all protects against losing a write: the leader acknowledges only after every in-sync replica has it, so a leader crash right after the acknowledgement does not lose it (combined with min.insync.replicas of 2 or more, so in-sync never means just the leader). Idempotence protects against duplicates and reordering from the producer's own retries: each batch has a producer id and sequence number, and the broker drops a batch it already stored. Both are on by default in current clients. Neither covers an application that re-sends after a restart; that needs an event id consumers deduplicate on, or Kafka transactions.

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?"
The broker gives each producer an id, and the producer numbers its batches per partition. The broker remembers the last sequence numbers it stored for each producer and partition, and drops a batch it has already written. That covers retries within one producer session; a restarted application gets a new producer id, so its re-sends look new.
Scenario"A producer sends 50,000 small JSON events a second and the brokers' network is saturated. What do you change?"
Batch and compress before adding hardware: raise linger.ms to 10 to 50 ms and batch.size to 64 KB or more so requests carry many records, and set compression.type to lz4 or zstd, which shrinks JSON several times because compression works on whole batches. Keep acks=all. Then measure; if it is still saturated, add brokers or partitions.
Trap"With the idempotent producer on, Spark writing to Kafka is exactly-once."
No. When Spark retries a micro-batch it sends the messages again as new sends, which the broker cannot recognise as repeats. Spark's Kafka sink is at-least-once. Carry an event id in each message for consumers to deduplicate on, or write to Delta when exactly-once matters.

Check yourself

3 questions

The 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 read
Schemas and Schema Registry
JSON, Avro or Protobuf, compatibility modes and who upgrades first, and decoding registry messages in Spark.

Related lessons

Previous: Incremental file ingestion

Primary sources: Producer configs · Kafka design: the producer · Kafka design: message delivery semantics · Spark: writing data to Kafka