Delivery semantics
Where a message can be lost or duplicated, what at-most-once, at-least-once and exactly-once really promise, and how to get an effectively-once result.
The problem
A payments team runs a worker that takes “charge order” messages from a queue and charges cards. During a routine deploy the workers are restarted one at a time. The next morning, support has a dozen customers who were charged twice. Each of them had a message in flight on a worker at the moment it was killed: the charge had gone through, and the acknowledgement had not.
The team’s first fix is to acknowledge first and process second. The double charges stop. Three weeks later a worker runs out of memory part of the way through a batch, and this time a handful of orders are never charged at all. Nothing in any log says so, because the broker had already been told they were done.
Neither version had a bug in the ordinary sense. A network can lose any message, including an acknowledgement, and a process can die between any two lines of code. A sender that hears nothing back cannot tell “my message was lost” from “the reply was lost”. This is the two generals problem, and no protocol removes it. A messaging system can only choose which way to fail.
Step 1 of 8
A checkout service queues a message that says: charge order 42 for 30 pounds. A payment worker will consume it and write the charge to a ledger. The worker acknowledges after it has processed a message, which is the at-least-once setting.
Read the steps as text
- A checkout service queues a message that says: charge order 42 for 30 pounds. A payment worker will consume it and write the charge to a ledger. The worker acknowledges after it has processed a message, which is the at-least-once setting.
- The broker delivers the message to the worker and starts waiting for an acknowledgement. Until one arrives, the broker keeps the message.
- The worker does its job. It inserts a 30 pound charge for order 42 into the ledger, and the database commits.
- The worker sends its acknowledgement, and it never arrives. Perhaps the network dropped it, or the worker was killed a millisecond after the commit. The work is done, but the broker does not know that.
- The broker times out. From where it sits, a lost acknowledgement looks exactly like a worker that died before doing anything. The only safe choice is to deliver the message again.
- The worker has no memory of the first attempt, so it inserts a second charge. The customer has now paid twice. No component had a bug. This is simply what at-least-once delivery means.
- Acknowledging before processing does not fix this. A crash after the acknowledgement and before the insert would then lose the charge completely. That is at-most-once delivery: no duplicates, but silent loss.
- The fix belongs in the consumer. Store the message ID in the same database transaction as the charge, under a unique constraint. A redelivered message hits the constraint, so the worker skips the insert and acknowledges. Delivery was at least once, and the effect was exactly once.
Three guarantees
| Guarantee | How you get it | What a failure causes |
|---|---|---|
| At most once | Never retry; acknowledge before processing | Lost messages |
| At least once | Retry until acknowledged; acknowledge after processing | Duplicates |
| Exactly once | At least once, plus deduplication or an atomic commit | Neither, inside a stated boundary |
At-least-once is the default in practice, because a lost payment or order is usually worse than a repeated one, and repeats can be made harmless. At-most-once is right when a message is cheap and soon superseded: a metrics sample, a “user is typing” indicator, a location ping that will be replaced in two seconds.
Where a message can be lost or duplicated
There are three hops, and each fails in its own way.
Producer to broker
The producer sends, the broker writes, and the acknowledgement is lost. If the producer does not retry, it risks loss, since for all it knows the write never happened. If it retries, the broker may store the record twice. With Kafka’s acks=0 the producer does not wait for any reply, which is at-most-once by construction.
There is an earlier loss point too. If a service commits to its database and crashes before publishing, the event never exists. That is the dual-write problem, which the transactional outbox in idempotency solves.
Inside the broker
A broker that acknowledges before the data is safely replicated can lose it. In Kafka, acks=1 acknowledges after the leader’s own write, so a leader crash before a follower copies the record loses an acknowledged message. acks=all with min.insync.replicas=2 closes this gap, as the Kafka lesson describes. Every broker also discards data that outlives its retention period, whether or not a slow consumer has read it.
Broker to consumer
Most real duplicates come from this hop, and it turns on one decision: when the consumer records its progress.
- Commit, then process. A crash between the two skips the message for good. At most once.
- Process, then commit. A crash between the two repeats the message. At least once.
In a queue, the commit is the acknowledgement or delete. A message is also redelivered if processing runs past the SQS visibility timeout, even though the first worker is still busy with it. In Kafka, the commit is the offset commit, and a rebalance in the middle of a batch hands the uncommitted records to another consumer.
Kafka’s auto-commit is on by default with a 5-second interval. During a call to poll() it commits the offsets that an earlier poll() returned. If you finish each batch before polling again, that is at-least-once. If you hand records to a thread pool and poll again straight away, offsets are committed for work still in flight, and a crash loses it. Committing manually after processing removes the doubt.
What “exactly once” means in Kafka
Kafka has offered “exactly-once semantics” since version 0.11 (2017). It consists of two specific mechanisms, and both stop at Kafka’s edge.
The idempotent producer fixes the first hop. Each producer gets an ID, and each batch carries a sequence number per partition. If a retry arrives with a sequence number the broker has already written, the broker acknowledges it without appending again. It has been on by default since Kafka 3.0. It deduplicates the producer’s internal retries within one producer session. It does not help if your application calls send() twice for the same business event.
Transactions make a group of writes atomic across partitions. Their main use is the consume-transform-produce loop: read from topic A, write results to topic B, and commit the input offsets, all in one transaction. Either the outputs and the offsets advance together, or neither does. Downstream consumers set isolation.level=read_committed so that they skip records from aborted transactions. Kafka Streams packages all of this as processing.guarantee=exactly_once_v2.
The limits are what interviewers probe:
- It covers Kafka-to-Kafka only. If the consumer writes to PostgreSQL, calls a payment API or sends an email, that side effect is outside the transaction. A crash after the side effect and before the commit repeats it.
- The processing still runs more than once. After a failure the records are processed again. What happens exactly once is the visible result in Kafka, because the failed attempt’s output was aborted.
- It costs latency. Read-committed consumers see nothing from a transaction until it commits, so end-to-end delay is at least the commit interval.
Effectively once
The guarantee you can build end to end is at-least-once delivery plus idempotent processing. A message may arrive twice, and the second arrival changes nothing. This is usually called effectively-once.
For a consumer that writes to a database, there are two standard ways:
- Deduplicate. Store the message ID in the same database transaction as the business change. A redelivery finds the ID and is skipped.
- Store the offset with the data. Write the Kafka offset in the same transaction as the result, and on restart seek to the stored offset, not the one Kafka holds. Progress and output can then never disagree.
For a side effect that cannot join a transaction, such as charging a card through a third party, pass an idempotency key so that the other side deduplicates. The idempotency lesson covers each technique.
When to choose each
- At most once when loss is cheap and a duplicate or a delay is worse: telemetry samples, presence, cache-invalidation hints backed by a TTL. Do not choose it for anything a customer or an accountant will notice is missing.
- At least once with idempotent consumers for nearly everything that matters: orders, payments, notifications, search indexing. This is the default answer.
- Kafka transactions when the whole pipeline is Kafka in and Kafka out, as in stream processing, and you want the framework to do the bookkeeping. Do not reach for them to protect a database write, because they do not cover it.
In the interview
When you put a queue or a log in a design, state the guarantee in one sentence: “Delivery is at least once, so this consumer is idempotent, keyed on the event ID.” Most candidates never raise it, and interviewers notice when you do.
If the interviewer says “but Kafka has exactly-once”, agree and then bound it. Idempotent producers remove duplicates from producer retries. Transactions make read-process-write atomic inside Kafka. Anything that leaves Kafka still needs idempotency at the destination. Then show where the duplicate comes from, which is the crash between processing and commit. Being able to point at the exact gap is what convinces.
Key takeaways
- A sender that gets no reply cannot tell a lost message from a lost acknowledgement, so every system must choose between possibly losing and possibly repeating.
- Commit before processing gives at-most-once. Process before committing gives at-least-once. A crash between the two steps decides which failure you see.
- At-least-once with idempotent consumers is the default for anything that matters; at-most-once suits cheap, quickly superseded data.
- Kafka's idempotent producer removes duplicates caused by the producer's own retries, within one producer session.
- Kafka transactions make consume-transform-produce atomic inside Kafka. They do not cover a database write, an API call or an email.
- End to end, the achievable goal is effectively-once: at-least-once delivery plus processing that is safe to repeat.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
Why can no protocol guarantee exactly-once delivery over an unreliable network?
A sender that hears nothing cannot distinguish a lost message from a lost acknowledgement. It must either retry and risk a duplicate, or not retry and risk loss.
Commit-then-process versus process-then-commit?
Commit first: a crash in between loses the message (at most once). Process first: a crash in between repeats it (at least once).
What does Kafka's idempotent producer do?
It tags batches with a producer ID and per-partition sequence numbers so the broker can drop a retried batch it has already written. It covers internal retries within one producer session.
What do Kafka transactions make atomic?
Writes to several partitions together with the consumer offsets of the input, so a consume-transform-produce step either fully happens or leaves no visible output.
What is outside Kafka's exactly-once guarantee?
Any side effect that leaves Kafka: a database write, an HTTP call, an email. Those need idempotency at the destination.
What is effectively-once processing?
At-least-once delivery combined with an idempotent consumer, so that a redelivered message has no additional effect.