What you'll learn: By the end of this lesson you will be able to define at-most-once, at-least-once and exactly-once delivery precisely, show that the first two differ only in the order of two steps in a consumer, name the three places a message can be lost or duplicated, state what Kafka's idempotent producer and transactions do and where their scope ends, build an idempotent consumer whose deduplication is atomic with its effect, and read the output of a lab that runs seven crash scenarios against a real in-process Kafka broker.
A courier has a list of parcels and a pen. For each parcel there are two steps: knock on the door, and tick the box. If the courier ticks first and is then called away, the parcel is never delivered, and nobody will ever look for it, because the list says it is done. If the courier knocks first and is called away before ticking, the next courier sees an unticked box and knocks again: the customer gets two parcels. Nothing about the courier's diligence changed; only the order of two steps did, and so did the way things go wrong.
That is the whole difference between at-most-once and at-least-once delivery. The overview lessons message queues and event streaming give the working definitions and the ShopStream order pipeline applies them in a paragraph and a table. This lesson is the dedicated treatment: where each failure comes from, what Kafka's own features cover, the idempotent-consumer pattern with its one hard requirement, and a lab that makes every case visible.
Verified with Apache Kafka 4.2 documentation (a newer 4.4 exists; its pages say so), Kafka clients 4.2.2, Spring Boot 4.1.2 and Java 25 as the compile target, on 2026-12-01.
The core idea
A delivery guarantee says what a consumer's effect looks like after failures: at-most-once means zero or one effect per message, at-least-once means one or more, and exactly-once means one. For independent systems the achievable version of the last is exactly-once effect: at-least-once delivery combined with a consumer that makes a repeated message harmless.
The Apache Kafka design documentation defines the three levels in one line each: at most once, "Messages may be lost but are never redelivered"; at least once, "Messages are never lost but may be redelivered"; exactly once, "Each message is processed once and only once". Everything below is about which mechanism gives you which line, and what each costs.
Three illustrations run through the lesson, each labelled:
- Minimal example: three orders, a consumer that dies at the second one, and the Java lab in "Build it".
- Realistic example: ShopStream's payment-capture worker, in "In practice".
- Failure example: a deduplicating consumer whose "seen" mark is written in a separate step, so it still duplicates.
Where a message can be lost or duplicated
A message passes through three steps, and each can fail between the work and the record of the work.
Figure 1. The send, the poll and the two-step consumer. How to read this: step 1 is the producer's send and the broker's acknowledgement. If the acknowledgement is lost the producer cannot tell whether the write happened, so it sends again. Step 2 is the consumer reading. Step 3 is two actions, the commit of the offset and the effect on the outside world, and the consumer can die between them.
The consumer's step 3 has no atomic "do both". Whichever of the two comes first is safe against one failure and unsafe against the other:
Figure 2. One crash, two outcomes. How to read this: the same crash point sits between the two actions in both halves. After a commit-first crash the restart resumes after the message, so the effect is lost; after an effect-first crash the restart resumes at the message, so the effect repeats. The Kafka design documentation describes exactly these two orders: save the position and then process gives at-most-once on a crash in between, and process and then save the position gives at-least-once.
The producer side
Before the consumer sees anything, the producer must get the message into the log. Five settings decide what a producer retry can do, with their documented values in Kafka 4.2:
| Setting | Documented default | What it does |
|---|---|---|
acks |
all |
How many acknowledgements the producer requires the leader to have received before a request counts as complete |
retries |
2147483647 | How many times to retry a request that fails with a transient error |
delivery.timeout.ms |
120000 (2 minutes) | An upper bound on the time to report success or failure after send() returns |
enable.idempotence |
true |
The producer ensures exactly one copy of each message is written in the stream |
max.in.flight.requests.per.connection |
5 | The maximum number of unacknowledged requests on one connection |
With retries on and idempotence off, a retry after a lost acknowledgement can write the message twice. The idempotent producer closes that: the Kafka documentation says the broker assigns each producer an ID and deduplicates messages using a sequence number sent with every message, so a resend of the same batch does not create a duplicate entry. The KafkaProducer documentation states the default (enable.idempotence has defaulted to true since Kafka 3.0) and, in the same place, the limit:
- "it is imperative to avoid application level re-sends since these cannot be de-duplicated."
- "the producer can only guarantee idempotence for messages sent within a single session."
So the idempotent producer protects against the client library's own retries inside one running producer. It does not protect against your code calling send() twice for the same business event (a retry loop around a timeout, an outbox relay that republishes after a restart): that is two sends, each gets its own sequence number, and the log holds two records. The lab shows this at offsets 1 and 2 of run 5.
At-most-once is the opposite choice: the Kafka documentation says to get it by "disabling retries on the producer and committing offsets in the consumer prior to processing a batch of messages", for data where a gap is cheaper than a duplicate.
The consumer side: commit order is the guarantee
A consumer's committed offset is the position it resumes from after a restart (the KafkaConsumer documentation: "the last offset that has been stored securely"). The two orders in Figure 2 follow directly, and the Kafka documentation says that, without special measures, "Kafka guarantees at-least-once delivery by default".
Auto-commit blurs the order. With enable.auto.commit=true (the documented default) offsets are committed in the background every auto.commit.interval.ms (5000 ms by default). The KafkaConsumer documentation warns that if you fail to process everything a poll returned, auto-commit lets the committed offset get ahead of the consumed position, "which results in missing records". Treat auto-commit as an accidental at-most-once with a time window, and check what your framework's acknowledgement mode does rather than assuming.
Manual commit after processing is the documented way to get at-least-once: the KafkaConsumer example "manually commit the offsets only after the corresponding records have been inserted into the database".
| Guarantee | Mechanism | A crash between the two steps | Cost | Fits |
|---|---|---|---|---|
| At-most-once | Commit the offset, then process (or producer retries off) | The message is skipped: a gap | None extra, but data is lost | Disposable data: samples, previews |
| At-least-once | Process, then commit the offset (the default behaviour) | The message is read again: a duplicate | The consumer must tolerate repeats | Almost everything else |
| Exactly-once effect | At-least-once plus an idempotent consumer | The repeat is recognised and skipped | A dedupe record, atomic with the effect | Payments, stock, anything a customer sees twice |
Exactly-once: what it can honestly mean
Over an unreliable network a sender cannot tell a lost message from a lost acknowledgement, which is why exactly-once delivery between independent systems cannot be assumed; message queues gives that argument. Kafka's documentation does not promise it either. It promises a narrower, precisely scoped feature.
Transactions. Since Kafka 0.11.0.0 a producer can send messages atomically to multiple partitions and topics: all or none become visible. The KafkaProducer documentation requires the transactional.id property, and for consumers to "read only committed messages" via isolation.level=read_committed (the default is read_uncommitted, which also returns messages from aborted transactions). In a consume-transform-produce loop, "we can write the offset to Kafka in the same transaction as the output topics receiving the processed data", and the design documentation concludes that this combination "can be used generally to provide exactly-once delivery" for reading, processing and writing within Kafka. It adds that the consumer must run with enable.auto.commit=false.
Figure 3. The scope of Kafka's exactly-once. How to read this: the zone is the part a Kafka transaction can make atomic. The two red dashed arrows are side effects outside Kafka. A transaction cannot roll back an email or a card charge.
Outside Kafka the limit is coordination. For an external output the design documentation says "the limitation is in the need to coordinate the consumer's position with what is actually stored as output". Its classic answer is two-phase commit between the offset store and the output; its preferred answer is "letting the consumer store its offset in the same place as its output", because many output systems do not support two-phase commit. The KafkaConsumer documentation describes the same idea: storing offsets outside Kafka, "not always possible, but when it is it will make the consumption fully atomic", restoring the position with seek at start-up.
So writing to PostgreSQL, calling a payment gateway or sending an email is outside the transaction, and a pipeline that does so is not exactly-once merely because it runs on a Kafka that has transactions. The rest of this lesson is the portable answer: at-least-once delivery and an idempotent consumer.
The idempotent consumer
An operation is idempotent when doing it twice has the same effect as doing it once (idempotent and commutative operations has the laws). Some effects are naturally so ("set order o-2 to PAID"); a charge is not, so the consumer adds bookkeeping: a record of which messages it has already applied.
The pattern has three parts, and the third is the one that gets skipped:
- A stable key. The id must identify the business event, not the delivery. It is not the partition and offset, because a resent message gets a new offset (run 5 in the lab:
o-2@1ando-2@2). Use an id the producer assigned once per logical event, such as the order id plus event type. - A durable record of keys already applied. An in-memory set does not survive the restart that caused the redelivery.
- Atomic with the effect. Writing the key and applying the effect must succeed or fail together, normally one database transaction in which the key's insert hits a unique constraint:
Figure 4. Deduplication in the same transaction as the effect. How to read this: the database transaction makes "remember the key" and "do the work" one step. The offset commit afterwards is still a separate step, which is fine, because losing it only causes a redelivery that the key check absorbs.
If the key and the effect are written separately, a crash between them produces exactly the duplicate the key was meant to stop. Run 7 in the lab does that on purpose.
Build it: seven crash scenarios on a real broker
This is the minimal example, a lab you can run. The broker is a real Kafka broker started in the test JVM by @EmbeddedKafka from spring-boot-starter-kafka-test, with no Docker. The "outside world" and the "seen" store are in-memory Java objects, because the lab is about the consumer's ordering; a real consumer would use a database transaction as in Figure 4.
Goal. See at-most-once lose a message, at-least-once repeat one, an idempotent consumer absorb both a crash redelivery and an application resend, and a non-atomic deduplication fail.
Setup. From the repository's examples/spring-labs folder:
cd examples/spring-labs && ./gradlew :labs:kafka-delivery-guarantees:test
The command runs 8 tests: seven behaviour tests plus a golden test that compares the scenario report with examples/spring-labs/golden/kafka-delivery-guarantees.txt. The code is under examples/spring-labs/labs/kafka-delivery-guarantees/src/main/java/buildingai/labs/delivery/.
How the model works. Each scenario creates its own one-partition topic, sends order ids as record keys with an idempotent producer (acks=all, enable.idempotence=true), then runs a worker. The worker assigns the partition itself with assign, so no group rebalance can interfere (the KafkaConsumer documentation notes that manual assignment disables group coordination), and starts from the group's committed offset. Offsets are still committed to the broker under a group id, which is what a restart reads. For every record the worker does the two steps of Figure 2, and a Crash object kills the "process" between them once. A restart is a second call of the worker with the same group. The whole difference between the two policies is this method:
private static void step(KafkaConsumer<String, String> consumer, TopicPartition tp, ConsumerRecord<String, String> record,
Policy policy, Handler handler, Crash crash, List<String> handled) {
var next = Map.of(tp, new OffsetAndMetadata(record.offset() + 1));
if (policy == Policy.COMMIT_BEFORE_PROCESSING) {
consumer.commitSync(next);
crash.check(Crash.Point.WORKER_MIDPOINT, record.key());
handler.handle(record.key());
handled.add(record.key());
} else {
handler.handle(record.key());
handled.add(record.key());
crash.check(Crash.Point.WORKER_MIDPOINT, record.key());
consumer.commitSync(next);
}
}
The idempotent handler is five lines. Its synchronized block stands in for the single database transaction of Figure 4:
@Override
public synchronized void handle(String orderId) {
if (!seen.add(orderId)) {
skipped++;
return;
}
effects.apply(orderId);
}
Steps. Run the command above and read the seven runs against the table below it.
Expected output, captured from a real run (Java 25.0.3, Kafka clients 4.2.2, Spring Boot 4.1.2, 2026-12-01):
Delivery guarantees on a real Kafka broker (in-process, one partition per topic).
Every run: producer acks=all and enable.idempotence=true; consumer enable.auto.commit=false.
The effects line is what the outside world received, in order, from the handler.
Run 1. At-least-once, nothing fails (the baseline).
topic : o-1@0 o-2@1 o-3@2
process 1 : starts at offset 0, handled [o-1, o-2, o-3], reaches the end of the topic, committed offset 3
effects : [o-1, o-2, o-3]
result : o-1 x1, o-2 x1, o-3 x1
Run 2. At-most-once (commit, then handle). The process dies between the two steps while handling o-2.
topic : o-1@0 o-2@1 o-3@2
process 1 : starts at offset 0, handled [o-1], DIES (process died at WORKER_MIDPOINT while handling o-2), committed offset 2
process 2 : starts at offset 2, handled [o-3], reaches the end of the topic, committed offset 3
effects : [o-1, o-3]
result : o-1 x1, o-2 x0 (LOST), o-3 x1
Run 3. At-least-once (handle, then commit). The process dies between the two steps while handling o-2.
topic : o-1@0 o-2@1 o-3@2
process 1 : starts at offset 0, handled [o-1, o-2], DIES (process died at WORKER_MIDPOINT while handling o-2), committed offset 1
process 2 : starts at offset 1, handled [o-2, o-3], reaches the end of the topic, committed offset 3
effects : [o-1, o-2, o-2, o-3]
result : o-1 x1, o-2 x2 (DUPLICATE), o-3 x1
Run 4. At-least-once with an idempotent consumer (effect and seen-mark are one atomic step). Same crash as run 3.
topic : o-1@0 o-2@1 o-3@2
process 1 : starts at offset 0, handled [o-1, o-2], DIES (process died at WORKER_MIDPOINT while handling o-2), committed offset 1
process 2 : starts at offset 1, handled [o-2, o-3], reaches the end of the topic, committed offset 3
effects : [o-1, o-2, o-3]
result : o-1 x1, o-2 x1, o-3 x1
skipped : 1 duplicate(s) recognised by the handler
Run 5. No crash, but the producer sent o-2 twice (a retry after an acknowledgement it never saw). Plain handler.
topic : o-1@0 o-2@1 o-2@2 o-3@3
process 1 : starts at offset 0, handled [o-1, o-2, o-2, o-3], reaches the end of the topic, committed offset 4
effects : [o-1, o-2, o-2, o-3]
result : o-1 x1, o-2 x2 (DUPLICATE), o-3 x1
Run 6. The same two sends of o-2, with the idempotent consumer.
topic : o-1@0 o-2@1 o-2@2 o-3@3
process 1 : starts at offset 0, handled [o-1, o-2, o-2, o-3], reaches the end of the topic, committed offset 4
effects : [o-1, o-2, o-3]
result : o-1 x1, o-2 x1, o-3 x1
skipped : 1 duplicate(s) recognised by the handler
Run 7. Anti-pattern: effect and seen-mark are two steps, and the process dies between them while handling o-2.
topic : o-1@0 o-2@1 o-3@2
process 1 : starts at offset 0, handled [o-1], DIES (process died at HANDLER_MIDPOINT while handling o-2), committed offset 1
process 2 : starts at offset 1, handled [o-2, o-3], reaches the end of the topic, committed offset 3
effects : [o-1, o-2, o-2, o-3]
result : o-1 x1, o-2 x2 (DUPLICATE), o-3 x1
skipped : 0 duplicate(s) recognised by the handler
| Run | What it shows |
|---|---|
| 2 | Commit-first: the committed offset is already 2 when the process dies, so the restart starts at offset 2 and o-2 is never applied. |
| 3 | Effect-first: the committed offset is still 1, so the restart starts at offset 1 and applies o-2 again. |
| 4 | The same crash as run 3, but the second o-2 is recognised and skipped. |
| 5 | No crash at all. The topic holds o-2 at offsets 1 and 2 although the producer is idempotent: two send() calls are two records. |
| 6 | The consumer's business key (o-2) catches what the idempotent producer cannot. Offsets differ, keys do not. |
| 7 | The key is remembered after the effect, in a second step. The crash falls between them and the duplicate returns. |
Break it. In the else branch of Worker.step, move consumer.commitSync(next) above handler.handle(record.key()). That turns the at-least-once policy into at-most-once, so commitAfterProcessingRedeliversTheRecordTheProcessDiedOn and the golden test should fail, with o-2 lost instead of repeated. Restore the file afterwards and re-run the tests.
Stretch. Dedupe on partition and offset instead of the order id and watch run 6 fail. Make the seen set a table in H2 and wrap the effect in one real transaction.
What the lab leaves out. Several partitions and rebalances, a real database, the producer's own retries (the lab shows an application resend, not a library retry), transactions, and real timings. The crash is an exception at a named point, which models a killed process but not a network partition.
Choosing a guarantee: the trade-offs
Figure 5. A decision path. How to read this: loss tolerance first, scope second. Most business systems end at the bottom branch, because their effects live in a database or an external service.
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| At-most-once | Simplest, never repeats | Silent loss | Anything someone would notice missing |
| At-least-once, plain consumer | Never loses, simple code | Duplicate effects | The effect is a charge, an email or a counter |
| At-least-once plus idempotent consumer | Never loses, harmless repeats | A durable key store and the discipline to keep it atomic | The effect cannot be recorded with a key |
| Kafka transactions | Atomic consume-process-produce inside Kafka | Throughput and complexity, scope ends at Kafka | The output is a database or an API |
| Store the offset with the output | No separate dedupe store | The output must hold the offset and the consumer must seek on start |
The output system is not yours |
In practice: ShopStream's payment-capture worker
This is the realistic example, an educational scenario on the course's running example, ShopStream; nothing in it describes a real company. Numbers other than the shared ShopStream figures are illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream's checkout publishes an order-placed event, and a payment-capture worker consumes it and asks the payment provider to capture the money. The peak target is about 58 checkouts per second (a shared illustrative number from the order pipeline stage). A capture that happens twice charges a shopper twice; one that never happens ships groceries for free. The team wants to know which guarantee the worker needs and where each failure is absorbed.
Starting architecture
Figure 6. The capture path. How to read this: the relay may publish an order twice, the worker may read a record twice, and the provider call can time out and be retried. Each hop is at-least-once, so the worker and the provider call both carry a key.
Options considered
| Option | What it gives | Problem |
|---|---|---|
| A. Commit first, then capture | No duplicate capture from a redelivery | A crash between the two steps loses a capture permanently |
| B. Capture, then commit, no key | No lost capture | A crash, a rebalance or an outbox republish charges twice |
| C. Capture, then commit, with a key stored in the same transaction as the ledger row, and the same key sent to the provider | Redeliveries and resends are absorbed | A key store to keep, and a key rule to honour |
| D. Kafka transactions | Atomic inside Kafka | The capture is a provider call and a database write, outside the transaction |
The decision
Option C. The business key is the order id plus the event name, assigned once by the orders service, never by the relay or the worker. The worker inserts the key and the ledger row in one database transaction and passes the same key to the provider as its idempotency key, as in the payments and ledger stage. The Kafka offset is committed last, so a crash anywhere before it ends in a redelivery that the key absorbs.
Rollout and verification
Before launch the team replays the lab's crash points against a staging copy: a kill between the capture and the offset commit, a kill between the key insert and the ledger row (which must roll back both), and a duplicate published on purpose with a new offset. In production the checks are captures per order (never above one), duplicates skipped per hour (expected during restarts, worth an alert if it stays high) and a daily comparison of ledger captures with the provider's report. Verification is zero orders with two captures and zero paid orders with none.
The 2 a.m. failure
The page reads: a shopper was charged twice for one order. The dedupe table is healthy and the worker skipped thousands of redeliveries that night. The cause is the key. The outbox relay timed out waiting for an acknowledgement, published the order-placed event again, and a developer had made the key a fresh event id generated when the relay published. The two records had different ids, so the consumer saw two orders (the lab's run 5 with the key made unique per send; the Kafka documentation's warning that application-level re-sends cannot be de-duplicated is about exactly this).
The checks: find the two Kafka records for the order, compare their keys and offsets, and read the relay's logs for the republish. The mitigation is refunding the duplicate and, as a stop-gap, a unique constraint on order id and charge type in the ledger. The lasting fix is to take the key from the order, not from the delivery, and to test that publishing the same order twice with different event ids captures once.
Architect's notes
- Say the guarantee for each hop: idempotent producer, at-least-once broker to consumer, idempotent by key at the effect. That beats "we have exactly-once".
- Name the scope before you use the word. Exactly-once inside Kafka is real and documented; exactly-once to a database or an API is something you build with keys.
- Keys come from the business, not the transport. An id minted per send attempt, or an offset, identifies a delivery, and deliveries are the thing that repeats.
- Dedupe must be durable and atomic. An in-memory set loses the one thing it was for at the restart; a separate write leaves a gap.
- Treat redelivery as normal. Restarts and rebalances cause it without any bug.
- Check the version. Defaults such as
enable.idempotenceandisolation.levelare documented per release.
Common mistakes
- Calling a pipeline exactly-once because Kafka has transactions. The transaction ends at Kafka.
- Believing the idempotent producer covers application retries. It covers the client's own retries inside one session.
- Auto-commit with slow processing. The offset can run ahead of the work, which is silent at-most-once.
- A dedupe key that changes per send. A fresh UUID per attempt makes every duplicate look new.
- Dedupe in memory, or in a second step. Both fail at the restart that matters.
- Never pruning the key store. Decide how long a duplicate can plausibly arrive and expire keys after that.
- Retrying a permanent failure forever. Delivery guarantees say nothing about poison messages; the next lesson, on dead-letter queues and retries, is where that goes.
Key takeaways
- At-most-once and at-least-once differ only in the order of two consumer steps, commit and effect; a crash between them loses the message in one order and repeats it in the other.
- Kafka's idempotent producer removes duplicates caused by the client's own retries within one producer session, and nothing else.
- Kafka transactions make a read, process and write inside Kafka atomic, with consumers on
read_committed; side effects outside Kafka are not covered. - For effects outside Kafka, build exactly-once effect: at-least-once delivery plus an idempotent consumer, or store the offset with the output.
- A deduplication key must be stable per business event, durable, and written atomically with the effect.
Practice exercises
Exercise 1 (20 min). For a page-view counter, a welcome email, a stock decrement, a courier location sample and a refund, say which guarantee you would accept and why.
Exercise 2 (45 min). Run the lab. For run 3, write the committed offset after each step of the first process and explain why the second process starts at offset 1. Then do the same for run 2.
Exercise 3 (1 hour). Change the lab's deduplication key from the order id to partition and offset and re-run run 6. Explain what you see and why a resend changes the offset but not the business key.
Exercise 4 (2 hours). Write the schema for ShopStream's processed-keys table, the unique constraint, the transaction around the capture and the retention rule for old keys. State how long a duplicate can plausibly arrive and why you chose that window.
Related reading
- Message Queues: acknowledgements, visibility, retries and the first definition of the three guarantees.
- Event Streaming: logs, offsets, partitions and consumer groups.
- Idempotent and Commutative Operations: the laws behind the idempotent consumer.
- Timeouts, Retries, Exponential Backoff and Jitter: the retries that create duplicates in the first place.
- Synchronous vs Asynchronous Communication: why work moves behind a queue.
- ShopStream Stage 5: The Order Pipeline and Stage 6: Payments and Ledger: the running example.
- Distributed Transactions: the alternative when an effect spans systems.
The other side of this topic
The front-end view of this topic is real-time clients: a browser that reconnects after a dropped connection must decide whether the server will resend what it missed and whether it can tell a repeat from a new message. It is the same two-step problem seen from the receiving end, treated in the frontend lesson on heartbeats, backpressure and delivery guarantees.
Official documentation
- Apache Kafka 4.2 documentation, Design: Message Delivery Semantics: the three guarantees, the idempotent producer, transactions and the scope of exactly-once.
- Apache Kafka 4.2, Producer configs:
acks,retries,delivery.timeout.ms,enable.idempotence,transactional.id. - Apache Kafka 4.2, Consumer configs:
enable.auto.commit,isolation.level,auto.offset.reset. - Apache Kafka 4.2 Javadoc, KafkaProducer: the idempotent and transactional producers and their scope.
- Apache Kafka 4.2 Javadoc, KafkaConsumer: offsets, manual commit and storing offsets outside Kafka.