A customer places one order. Two days later, an angry email: “You charged my card twice.”
You check the logs. The payment service received the OrderPlaced message, charged the card, and was about to tell the message broker “done” when it crashed. The broker never heard “done”, so it did the sensible thing: it delivered the message again. A fresh copy of the service picked it up and charged the card a second time.
Now flip it. Another team, tired of duplicates, turned retries off. Their problem is the opposite: once in a while, an order confirmation simply never arrives. The message vanished in a network hiccup and nobody tried again.
Both teams ran into the same hard fact: over a network, you can’t guarantee a message arrives exactly once. You can only choose which mistake to risk, and then design around it. That choice is called message delivery semantics, and it’s the last piece of the communication puzzle.
Why messages get lost or repeated
When a service sends a message, it waits for an acknowledgement (an “ack”): “I got it.” As we saw in distributed systems basics, a network call can end in three ways: success, failure, or “I don’t know.”
If no ack comes back, the sender has only two choices:
- Don’t retry. If the message was lost, it’s gone for good.
- Retry. If the message had arrived and only the ack was lost, the receiver now gets it twice.
There is no third button. That’s why delivery semantics exist: they are the rules a system promises to follow about how many times a message will be delivered.
The three delivery guarantees at a glance
| At-most-once | At-least-once | Exactly-once (processing) | |
|---|---|---|---|
| Delivered | 0 or 1 times | 1 or more times | 1 or more times, but acted on once |
| Can lose messages? | Yes | No | No |
| Can duplicate? | No | Yes | Not in effect |
| Speed and cost | Fastest, simplest | A little slower | Slowest, most work |
| Good for | Metrics, live positions, sensor readings | Emails, notifications, most events | Payments, stock counts, money transfers |
At-most-once: fire and forget
With at-most-once delivery, a message is sent once, with no retries. It arrives zero times or one time, never twice.
Think of dropping a postcard in a postbox. It almost always arrives. If it doesn’t, nobody will ever know, and nobody sends it again.
There are two common ways to get it:
- The producer sends without waiting for an ack and never retries.
- The consumer marks the message as done before it processes it. If it crashes halfway, the message is skipped, not repeated.
// Java · at-most-once consumer: mark as done FIRST, then process
@KafkaListener(topics = "page-views")
public void record(PageView view, Acknowledgment ack) {
ack.acknowledge(); // tell Kafka "done" straight away
analytics.track(view); // if this crashes, the view is simply lost
}
Use it when losing a message is cheaper than handling a duplicate: page-view counts, metrics, logs, game player positions, sensor readings that arrive every second anyway. If one is lost, the next one is coming.
At-least-once: retry until someone says “got it”
With at-least-once delivery, the sender keeps retrying until it gets an ack. A message is never lost, but it can arrive more than once.
Think of a courier who needs a signature. If nobody signs, they come back tomorrow. But if you did take the parcel and the signature got lost, you’ll get a second knock and a second parcel.
The recipe is the opposite of at-most-once:
- The producer waits for the broker to confirm the message is safely stored, and retries if not.
- The consumer marks a message as done only after it has finished processing it.
// Java · at-least-once consumer: process FIRST, then mark as done
@KafkaListener(topics = "order-events")
public void sendConfirmation(OrderPlaced event, Acknowledgment ack) {
emails.sendOrderConfirmation(event); // do the work
ack.acknowledge(); // only then say "done"
// crash between these two lines → the message comes again → a second email
}
On the producer side, Kafka’s safe settings look like this (and they’re the default since Kafka 3.0):
acks=all # wait until all in-sync copies have stored the message
enable.idempotence=true # the broker throws away the producer's own retry duplicates
retries=2147483647 # keep retrying (within delivery.timeout.ms)
At-least-once is the most common choice in real systems. Most of the time, a duplicate is a small annoyance (a second “your order is confirmed” email) while a lost message is a real problem (no email at all). But for some actions, like charging a card, a duplicate is a disaster. That’s where the next idea comes in.
Exactly-once: what it really means
Everyone wants exactly-once: every message delivered once, never lost, never repeated. Here’s the honest truth:
Exactly-once delivery over a network is impossible. The sender can never be sure the receiver got the message, because the confirmation itself can be lost, and so can the confirmation of the confirmation, forever. (Computer scientists call this the Two Generals problem.)
But exactly-once processing is very achievable. The message may arrive twice, but its effect happens only once. The recipe is simple to say:
“Exactly-once = at-least-once delivery + a receiver that safely ignores repeats.”
A receiver that can handle the same message many times with the same result is called idempotent. Making your consumers idempotent is the single most useful skill in message-driven systems.
Four ways to make a consumer idempotent
1. Use operations that are naturally safe to repeat. “Set order 123’s status to PAID” gives the same result however many times you run it. “Add 1 to the like count” does not. Prefer setting values over adding to them.
2. Remember which messages you’ve already handled. Give every message a unique ID, and record it in a processed_messages table in the same database transaction as the real work. A unique constraint does the duplicate check for you:
// Java · idempotent consumer: the ID record and the work commit together
@KafkaListener(topics = "order-events")
@Transactional
public void reduceStock(OrderPlaced event) {
// INSERT INTO processed_messages (event_id) VALUES (?) ON CONFLICT DO NOTHING
int inserted = processed.insertIfAbsent(event.eventId());
if (inserted == 0) {
return; // seen it before: do nothing
}
inventory.decrement(event.items()); // same transaction as the insert
}
Either both the ID record and the stock change are saved, or neither is. A repeat delivery finds its ID already there (the unique key guarantees it, even if two copies arrive at once) and quietly does nothing.
3. Pass an idempotency key to outside systems. You can’t put a payment provider inside your database transaction. Instead, send a key that is the same on every retry, such as "payment-" + orderId. Providers like Stripe use it to make sure a repeated request never charges twice.
4. Use the broker’s transactions for broker-to-broker work. If a service reads from one Kafka topic and writes to another, Kafka transactions can commit the output messages and the input position together. But this only covers what happens inside Kafka. The moment you send an email or call a payment API, you’re back to options 1–3.
A Kafka detail that causes most of the trouble: offsets
In Kafka, a consumer doesn’t delete messages. It keeps a bookmark, called an offset, that says “I’ve finished everything up to here.” When you move that bookmark decides your delivery guarantee:
| You commit the offset… | If the consumer crashes mid-message… | Result |
|---|---|---|
| Before processing | the message is skipped | At-most-once |
| After processing | the message is processed again | At-least-once |
| After processing, with an idempotent consumer | the repeat is ignored | Exactly-once in effect |
Two more offset surprises catch teams out:
- Changing the consumer group name gives you a fresh bookmark. Depending on
auto.offset.reset, the “new” consumer either replays everything from the start or skips everything that was waiting. - Committed offsets expire. If a consumer group is gone longer than the retention period (7 days by default), Kafka forgets its bookmark.
The order of messages matters too
Delivery semantics answer “how many times?” There’s a second question: in what order?
Imagine three updates for order 123: CREATED, then PAID, then SHIPPED. If they arrive as CREATED, SHIPPED, PAID, the order ends up marked PAID even though it has shipped.
Two fixes, often used together:
- Send related messages with the same key. Kafka keeps messages in order within a partition, and the same key always goes to the same partition. Use the order ID as the key, and order 123’s updates stay in sequence.
- Add a version number. Each update carries
version: 1, 2, 3.... The consumer ignores any update older than what it already has. This also protects you when retries shuffle things.
Choosing per action, not per system
One event can need different guarantees for each thing that reacts to it. When an order is placed:
| Action | Lose it? | Do it twice? | Choose |
|---|---|---|---|
| Reduce stock | Overselling | Wrong count | Exactly-once processing |
| Charge the card | Lost revenue | Angry customer, refund | Exactly-once processing (idempotency key) |
| Confirmation email | Customer worries | Mild annoyance | At-least-once |
| Analytics event | One missing data point | Slightly wrong count | At-most-once |
What breaks, and how to fix it
| What breaks | Why | The fix |
|---|---|---|
| Double charge | Crash after charging, before committing the offset | Idempotency key with the payment provider, plus a processed-messages check |
| Stock reduced twice | The message was redelivered and the consumer just did it again | Record the message ID in the same transaction as the work |
| Lost order event | Producer had retries off, or didn’t wait for acks | acks=all, retries on, and the outbox pattern when saving and publishing together |
| Wrong final status | Updates arrived out of order | Same key per entity, plus version checks |
| One bad message blocks everything | It fails every time, so it’s retried forever | After a few tries, move it to a dead-letter queue to inspect later |
Puzzle 1: the double charge mystery
The consumer charged the card, then crashed before the offset was committed (or the save failed). Kafka redelivered the message, and a new consumer charged again. Nothing in the code checks for repeats.
The fix has two parts. Send the gateway an idempotency key that’s the same for every retry, like "payment-" + e.orderId(), so the provider itself refuses a second charge. And record the payment against that key with a unique constraint, so your own database can’t hold two payments for one order. At-least-once always needs an idempotent consumer.
Puzzle 2: “but we turned on exactly-once”
Those settings stop the producer from writing duplicates into Kafka, and let it write several messages atomically. They say nothing about what the consumer does afterwards. If the email consumer sends an email and crashes before committing its offset, it will read the message again and send another email. Kafka can’t un-send an email.
Exactly-once is an end-to-end property. Every step that touches the outside world needs its own protection: idempotent processing, offsets committed after the work, and isolation.level=read_committed so consumers don’t read half-finished transactions.
Puzzle 3: which guarantee would you pick?
- (a) Welcome email: at-least-once. Losing it is worse than sending it twice.
- (b) Bank transfer: exactly-once processing. Losing it or repeating it both lose real money. Use transactions and idempotency keys.
- (c) Page views: at-most-once. One missing view changes nothing.
- (d) Live prices: at-most-once, which surprises people. A lost price doesn’t matter because a newer one arrives in a moment, and an old price delivered late is worse than useless. (Actually placing a trade is a different story: that’s exactly-once.)
Key takeaways
- Networks lose and repeat messages. When an ack goes missing, you must choose: risk losing the message, or risk a duplicate.
- At-most-once never repeats but may lose. Use it for data where the next value is coming anyway.
- At-least-once never loses but may repeat. It’s the default for most real systems.
- Exactly-once delivery is impossible; exactly-once processing is not. Get it with at-least-once plus an idempotent consumer.
- In Kafka, when you commit the offset decides your guarantee. Order is only kept within a partition, so key related messages together.
- Choose per action. Ask: which hurts more here, losing it or doing it twice?
So far in the Communication & integration thread: how services wait for each other, which protocol they speak, and how many times each message arrives. One more piece completes it: the network terms underneath all of this, multiplexing, full duplex, bidirectional streaming and QUIC.
Comments