Delivery Semantics - Complete Deep Dive
Prerequisites: Message Queues, Idempotency Used in: Notification System, Message Queue, Payment System
What Are Delivery Semantics?
Delivery semantics describe how many times a message can be handed from a sender to a receiver when the network in between is allowed to fail. There are exactly three answers people talk about — at-most-once, at-least-once, and exactly-once — and the difference between them is not a property of the message or the queue. It is a property of what the sender decides to do when it does not get an acknowledgement back.
Real-world analogy: You mail a signed contract to a client and ask them to post the countersigned copy back. If the return envelope never arrives, you have a choice. You can shrug and move on, in which case the contract might never have been signed — that is at-most-once. Or you can print and mail another copy, in which case the client may end up with two contracts on their desk and might sign both — that is at-least-once. What you cannot do is reach into the postal system and find out whether the first envelope was delivered. The silence is identical in both cases, and no amount of re-reading the silence will tell you which world you are in.
The Two Generals and Why Exactly-Once Delivery Is Impossible
Start with the single fact that every other section on this page follows from: an acknowledgement that does not arrive is indistinguishable from a message that never arrived.
A sender transmits message M and starts a timer. The timer fires with no acknowledgement. Two completely different things could have happened.
sequenceDiagram
participant S as Sender
participant N as Network
participant R as Receiver
S->>N: Send message M
N->>R: Deliver M
R->>R: Process M and update state
R->>N: Ack for M
Note over N: Ack packet is dropped
Note over S: Timer fires with no ack
Note over S: Sender cannot tell these apart<br/>Case A - receiver never got M<br/>Case B - receiver got M and the ack was lost
In Case A the right move is to resend. In Case B resending creates a duplicate. The sender has no way to find out which case it is in, because the only channel it could use to ask is the same unreliable network that just lost the ack. Asking “did you get it?” is itself a message that can be lost, and the answer to it is a message that can be lost.
This is the Two Generals problem, stated in 1975. Two armies on opposite hills must attack at the same dawn or both lose. The only way to communicate is a messenger crossing the valley, who may be captured. General A sends “attack at dawn.” Does A attack? Not unless B confirms — B might never have got the order. So B sends a confirmation. Does B attack? Not unless B knows A received the confirmation, because A will not attack without it. So A confirms the confirmation. The regress never ends. There is no finite exchange of messages over a lossy channel that leaves both sides certain, and this is a proof, not an engineering gap waiting for a better protocol.
So when someone says “I want exactly-once delivery,” they are asking for something the network cannot sell. The practical consequence:
| What the sender does on an unacked send | What you get | What you must now live with |
|---|---|---|
| Nothing. Move on. | At-most-once | Silent message loss. Zero duplicates. |
| Retry until acked | At-least-once | Guaranteed delivery. Duplicates are certain at scale. |
| Retry, and somehow never duplicate | Exactly-once delivery | Not achievable over a lossy channel |
Notice that at-most-once and at-least-once are not sophisticated protocols. They are just the two possible retry policies, and each one trades the failure mode you can tolerate for the one you cannot.
The Three Guarantees, Defined Precisely
At-most-once means the sender transmits and never retries. If the message is lost in flight, it is gone and nobody is told. Fire-and-forget UDP metrics, a browser navigator.sendBeacon analytics ping, and a log line written to a socket with no confirmation are all at-most-once. It is the cheapest option — no retry bookkeeping, no dedup store, no duplicate handling — and it is the correct choice when the data is statistical and a lost sample does not change any decision.
At-least-once means the sender retries until it receives an acknowledgement. Every durable queue you are likely to use — Amazon SQS, RabbitMQ with manual ack, Kafka with a consumer that commits after processing, Google Pub/Sub — is at-least-once by default. Duplicates are not an edge case here. At a million messages a day, redelivery from ack timeouts, consumer rebalances, and broker failovers will happen daily. Design as if every message arrives twice, because eventually one will.
Exactly-once is what people actually want: the effect of the message lands once. That is achievable. What is not achievable is the transmission landing once. Separating those two sentences is the whole trick.
The Resolution the Industry Actually Uses
Nobody solves this by making the network reliable. Everyone solves it by making the receiver not care how many copies it gets:
at-least-once delivery + idempotent processing = effectively-once
The sender keeps retrying — duplicates flow freely on the wire, and that is fine. The receiver recognises a message it has already handled and does nothing the second time. The net observable effect on the world is one state change per logical message. This is called effectively-once, or exactly-once processing — never exactly-once delivery, and the word swap is deliberate.
flowchart LR
P["Producer retries<br/>until acked"] --> Q["Queue delivers<br/>one or more times"]
Q --> D{"Seen this<br/>message id before"}
D -->|"Yes"| SKIP["Skip and ack<br/>no state change"]
D -->|"No"| APPLY["Apply effect and<br/>record the id atomically"]
APPLY --> ACK["Ack the message"]
SKIP --> ACK
The critical word in that diagram is atomically. If the receiver applies the effect and then records the id as a second, separate write, a crash in between leaves the effect applied with no record of it — and the retry will apply it again. The effect and the dedup record must commit together, which in practice means both live in the same database transaction, or the effect is itself a conditional write keyed on the id. This is the same dual-write hazard the outbox pattern solves on the publishing side.
How a Dedup Store Works
A dedup store is a set of keys, one per message already processed, each with a time-to-live after which it is forgotten.
def handle(message):
key = f"dedup:{message.id}"
# SET NX returns False if the key already exists.
# One atomic operation does both the check and the claim.
claimed = redis.set(key, "done", nx=True, ex=7 * 24 * 3600)
if not claimed:
return ACK # already processed, nothing to do
try:
apply_effect(message)
return ACK
except Exception:
redis.delete(key) # release the claim so the retry can work
raise
The code is six lines. Choosing the key is the hard part, and it is where most real bugs live.
| Key choice | What it dedups | Fails when |
|---|---|---|
| Producer-assigned message id | A single transmission and its retries | The producer itself retries and mints a new id for the same business event — now two ids, no dedup |
Natural business key such as order_id:captured |
The business event, no matter who sent it or how many times | The event legitimately happens twice, for example two separate refunds on one order |
| Content hash of the payload | Byte-identical payloads | Two genuinely distinct events have identical bodies, such as two $5 tips one second apart. Also breaks if the payload carries a timestamp, since nothing ever matches |
The guidance that holds up: dedup on a natural business key whenever one exists, because it survives the producer retrying with a fresh id, which is the failure the message-id approach silently misses. Fall back to a producer-assigned id only when the event has no natural identity. Treat a content hash as a last resort.
Where the Dedup Store Lives
| Location | Durability | Atomic with the effect | Cost |
|---|---|---|---|
| Redis with a TTL | Can lose recent keys on failover | No, separate system | Cheapest, sub-millisecond |
| Unique constraint in the business database | Full, same durability as the data | Yes | One extra index write |
| The processor’s own state store, for example a Flink or Kafka Streams state backend | Checkpointed | Yes, within the framework | Operationally heaviest |
The unique constraint deserves more credit than it gets. You do not need a separate dedup table at all if the effect itself can carry the key:
-- The dedup record IS the effect. One statement, atomic by definition.
INSERT INTO ledger_entries (dedup_key, account_id, amount_cents)
VALUES ('order_7781:capture', 42, 2500)
ON CONFLICT (dedup_key) DO NOTHING;
If that statement runs five times, four of them do nothing, and there is no window in which the effect exists without its dedup record. A Redis-based store cannot make that promise, because Redis and your database are two systems that can disagree. The reason people still reach for Redis is throughput: an extra unique index on a hot write table costs real write amplification, and at 50,000 writes per second that matters.
The TTL trade. A dedup key must outlive every retry that could possibly reference it. Too short and a late redelivery — a message that sat in a dead-letter queue for a week and was then replayed — sails straight through as a fresh message. Too long and the store grows without bound. The honest framing: TTL is a correctness parameter disguised as a storage parameter. Set it from your maximum possible redelivery window, including manual DLQ replays, not from your disk budget. A week is a common answer. Stripe keeps idempotency keys for 24 hours and says so explicitly in its API contract, which is the other valid approach — publish the window so callers know when reuse stops being safe.
The Offset Commit Ordering Problem
Here is where at-least-once and at-most-once stop being abstract. A queue consumer does two things: it processes the message, and it records that it is done so the broker stops redelivering. The order of those two steps chooses your semantics, and there is no third option.
flowchart TD
A["Message delivered to consumer"] --> B{"Which happens first"}
B -->|"Process then commit"| C["Crash after processing<br/>before the commit lands"]
C --> D["Broker redelivers<br/>effect applied twice"]
D --> E["At-least-once"]
B -->|"Commit then process"| F["Crash after the commit<br/>before processing finishes"]
F --> G["Broker never redelivers<br/>the work is silently lost"]
G --> H["At-most-once"]
Process-then-commit is the right default for almost everything, because a duplicate is a problem you can engineer away with a dedup store and a lost message is a problem you cannot engineer away at all. Commit-then-process is a legitimate choice only when throughput beats completeness — and when you pick it, say so in writing, because the next engineer will assume the default.
A subtle version of the same bug: a consumer that prefetches a batch of a hundred messages, processes them on a thread pool, and commits the batch offset when the batch finishes. Message 40 can fail while message 90 succeeds, and committing the batch offset marks all hundred as done. Per-message acknowledgement or per-partition offset tracking is the fix.
Kafka Transactions and Where the Guarantee Stops
Kafka advertises exactly-once, and the claim is real — but it is scoped much more narrowly than the marketing implies. Two separate mechanisms:
The idempotent producer (enable.idempotence=true) gives each producer a producer id and attaches a monotonic sequence number to every record in a partition. The broker tracks the highest sequence number it has seen and silently drops a record whose sequence number it has already accepted. This removes duplicates caused by producer retries — the exact Case B ambiguity from the start of this page — within one producer session. It does not remove duplicates caused by your application calling send() twice.
Transactions let a consumer-producer application atomically commit a set of produced records together with its own consumed offsets. That makes a read-process-write cycle atomic: either the output records and the new offsets both land, or neither does, so a crash mid-cycle reprocesses from the old offset and the partial output is never visible to readers using isolation.level=read_committed.
| Scenario | Does Kafka exactly-once cover it |
|---|---|
| Producer retries a record after a lost ack | Yes — idempotent producer dedups by sequence number |
| Read from topic A, transform, write to topic B, commit offsets | Yes — transactions make the whole cycle atomic |
| Consumer writes a row to PostgreSQL | No — Postgres is not in the Kafka transaction |
| Consumer calls the Stripe API | No |
| Consumer sends an email | No |
| Zombie producer resurrects after a rebalance | Yes — the producer epoch fences it, see fencing tokens |
The boundary is crisp: Kafka’s exactly-once holds exactly as far as Kafka’s own storage reaches, and stops dead at the first external side effect. The moment your consumer touches anything that is not a Kafka topic, you are back to at-least-once plus idempotency, and you own the dedup store yourself.
Side Effects You Cannot Undo
Some effects are not stateful rows you can overwrite. They are events in the world.
- An email sent cannot be unsent. The recipient has read it.
- A card charged can be refunded, but the cardholder saw two charges on their statement, and that generates a support ticket whether or not you refund it.
- A webhook delivered to a customer’s endpoint has already triggered whatever their code does.
- A push notification buzzed someone’s phone at 3am. Twice.
Dedup-after-the-fact does not help, because by the time you notice the duplicate the effect has landed. The only working approach is to push the idempotency key out to the external boundary and make the external system responsible for the dedup:
# The key is derived from the business event, not generated per attempt.
# Retry this call a hundred times - Stripe charges once.
stripe.PaymentIntent.create(
amount=2500,
currency="usd",
customer=customer_id,
idempotency_key=f"order-{order_id}-capture", # stable across retries
)
Every serious provider offers this hook — Stripe’s Idempotency-Key header, PayPal’s PayPal-Request-Id, AWS ClientToken parameters, SendGrid and Twilio message-level keys. Use it, and derive the key from your business entity rather than generating a fresh UUID per attempt, which is the mistake that quietly defeats the whole mechanism. If a provider offers no such hook, you are reduced to a local claim: write “I am about to send this” to your own database with a unique constraint, send, then mark it sent. That narrows the duplicate window to a crash in the middle of the send. It does not close it, and no design closes it, so the remaining gap belongs to reconciliation.
Comparison
| At-most-once | At-least-once | Effectively-once | |
|---|---|---|---|
| Sender on no ack | Gives up | Retries | Retries |
| Receiver work | None | None | Dedup check per message |
| Failure mode | Silent loss | Duplicate effects | Dedup store bugs or TTL expiry |
| Infra cost | Lowest | Low, durable queue | Durable queue plus dedup store |
| Latency added | None | None | One store lookup, typically sub-millisecond |
| Good for | Metrics, traces, telemetry | Anything with an idempotent sink | Payments, orders, ledgers, notifications |
Pick at-most-once when the data is statistical. Pick at-least-once when the sink is naturally idempotent — a PUT to object storage, a SET of an absolute value, an upsert keyed on a stable id — because then you get effectively-once for free with no dedup store at all. Build the dedup store only when the effect is a side effect you cannot express as an overwrite.
Common Interview Questions
Q1: Why is exactly-once delivery impossible, and why do vendors advertise it?
A sender cannot distinguish “the receiver never got the message” from “the receiver got it and the acknowledgement was lost,” because the only way to ask is the same channel that just failed. That is the Two Generals problem and it has no finite solution. Vendors advertise exactly-once processing within their own boundary — Kafka transactions genuinely make a read-process-write cycle atomic inside Kafka. The guarantee is real; it just stops at the first external side effect, and that caveat is usually in the footnote rather than the headline.
Q2: Your consumer processes a message, crashes before committing the offset, and gets it again. What now?
Nothing is wrong — that is at-least-once working as designed, and the alternative ordering loses messages instead. The fix is on the processing side. Before applying the effect, atomically claim a dedup key derived from the business event and commit the claim in the same transaction as the effect. On redelivery the claim fails, the consumer skips the work and acks. If the effect is an external call, pass the same key as the provider’s idempotency key.
Q3: What key should the dedup store use — message id, business key, or content hash?
Prefer a natural business key such as
order_7781:capture. A producer-assigned message id only dedups retries of one transmission; if the producer itself retries and mints a new id for the same business event, the message-id check passes both and you process twice. A content hash breaks in both directions: distinct events with identical bodies collide, and any timestamp in the payload means nothing ever matches. Use a message id when the event has no natural identity, and a hash only as a last resort.
Q4: How long should dedup keys live?
Long enough to cover the worst redelivery you could ever see, including a manual replay out of a dead-letter queue days later. That makes TTL a correctness parameter, not a storage one: a key that expires early lets a late duplicate through as a fresh message. A week is a reasonable default for queue dedup. Publishing a shorter window, as Stripe does with 24 hours, is also valid — it tells callers exactly when key reuse stops being safe.
Q5: You must send one confirmation email per order. How do you avoid sending two?
Accept that you cannot fully guarantee it, then shrink the window. Write an
email_sendsrow keyed uniquely onorder_id:confirmationinside the order transaction, so the intent is recorded atomically with the order. A worker claims unsent rows with a conditional update, calls the provider with that same key as its idempotency key, and marks the row sent. Duplicates now require both a crash inside the send and a provider that ignores idempotency keys. The residual risk is real but bounded, and a reconciler that flags rows claimed but never marked sent catches what slips through.
Navigation
| ← Message Queues | WebSocket vs SSE vs Polling → |
| All Concepts | HLD Designs |