Course contents

07. Messaging and Event-Driven Systems Lesson 8 of 10

Delivery Semantics

At-most-once, at-least-once and effectively-once: watch a worker crash lose or redeliver messages, slow work become duplicates, and dedup fix it.

15 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Delivery semantics describe what happens when a consumer fails between receiving and acknowledging a message.
  • At-most-once acks first: no duplicates, but a crash silently loses the messages the consumer held.
  • At-least-once acks last: nothing is lost, but crashes, slow work and lost acks cause duplicates.
  • The visibility timeout is both the false-redelivery threshold and the crash-recovery delay; extend it while working.
  • Effectively-once = at-least-once delivery + an idempotent consumer whose dedup record commits with the side effect.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A delivery guarantee says how many times a message's effect can happen when things go wrong. There are three practical levels:

  • At most once: the effect happens zero or one times. Messages may be lost, never duplicated.
  • At least once: the effect happens one or more times. Messages are never lost while the broker keeps them, but may be duplicated.
  • Effectively once (often marketed as "exactly once"): the effect happens once, built from at-least-once delivery plus deduplication in the consumer.

All three are decided by one detail: when the consumer acknowledges a message relative to doing the work, and what it does when it sees the same message twice.

Why it exists

A broker and a consumer communicate over a network and both can crash. When a consumer goes quiet, the broker cannot tell whether it is slow, dead before doing the work, or dead after doing the work but before its ack arrived. Whatever the broker does next (forget the message or deliver it again) is wrong in one of those cases. Delivery semantics are the explicit choice of which wrong outcome you prefer, and what you do in the consumer to make it harmless.

How it works

At most once. The consumer acks on receipt (or the broker auto-acks on delivery), then processes. If the consumer crashes before finishing, the broker has already deleted the message: lost. Fire-and-forget producers (sending without waiting for a confirmation, no retries) give the same property on the publishing side.

At least once. The consumer processes, then acks. Until the ack, the broker only leases the message: it is invisible to other consumers for a visibility timeout (SQS), ack deadline (Google Pub/Sub) or until the consumer's channel closes (RabbitMQ). If the lease expires without an ack, the message is delivered again. Duplicates follow from three cases:

  1. The consumer is slower than the timeout; the message goes to another consumer while the first is still working, and both finish.
  2. The consumer performs the side effect, then crashes before acking.
  3. The ack is lost or arrives after the lease expired.

Producers have the same choice: retrying a publish whose confirmation was lost can store the message twice.

Timeouts and leases. The timeout is counted from delivery, not from a crash: the broker never sees the crash, only the missing ack. So the timeout is also your crash-recovery delay. Long-running consumers extend the lease while they work (SQS ChangeMessageVisibility, Pub/Sub modifyAckDeadline, handled automatically by most client libraries), which keeps the base timeout short.

Effectively once. The consumer makes processing idempotent: doing it twice has the same effect as once. Common techniques:

  • Dedup table (inbox): insert the message id (or a business key like the order id) into a table with a unique constraint in the same transaction as the effect. A duplicate fails the insert and is acked without repeating the effect.
  • Natural idempotency: upserts and "set state to X" writes instead of "add 1".
  • Idempotency keys passed to external services (payment providers commonly accept one), so the provider deduplicates retries.

What "exactly-once" features cover. Some systems offer exactly-once guarantees within their own boundary: Kafka's idempotent producer (on by default in the Java client since Kafka 3.0) deduplicates producer retries per partition, and Kafka transactions make a read-process-write cycle between topics atomic for read_committed consumers. SQS FIFO queues deduplicate sends with the same deduplication id within a 5-minute window. None of these extend to a side effect in another system, such as charging a card or sending an email.

When to use it

  • At least once + idempotent consumer: the default for business events, payments, orders, anything where losing a message is worse than handling it twice (which idempotency makes harmless).
  • At most once: metrics samples, telemetry, cache invalidation hints, presence updates: high volume, where an occasional loss is acceptable and a duplicate or delay is not worth paying for.
  • Broker-level exactly-once: stream processing that only reads from and writes to the same log system (e.g. Kafka topic to Kafka topic).

When not to

  • Do not use at-most-once for anything a user or auditor will miss: payments, orders, notifications that must arrive.
  • Do not rely on broker "exactly-once" when the consumer calls external systems; it does not cover them.
  • Do not add a dedup store when the operation is naturally idempotent already (an upsert of the latest state); it only adds a write.

Trade-offs

Choice You gain You pay
At most once Simplicity, lowest latency, no duplicates Silent loss on every consumer crash
At least once No loss while the broker holds the message Duplicates; consumers must handle them
Dedup table in the same transaction Duplicate-proof effects An extra write per message; table cleanup (retention window)
Short visibility timeout Fast recovery after crashes Duplicates whenever work runs long
Long visibility timeout Few false redeliveries Slow recovery: a crash delays its messages by the full timeout
Lease extension Short timeout and no false redeliveries Heartbeat logic; a stuck-but-alive consumer can hold a message forever

Alternatives

  • Synchronous calls with idempotency keys: when the caller needs the result, retry a request with a key the server deduplicates.
  • Transactional outbox + idempotent consumer: covers the producer side, so a message is published if and only if the database change commits.
  • Log-based processing with committed offsets: consumers store their position atomically with their output (in the same database), which gives effectively-once without per-message ids.

Failure modes

  • Silent loss with at-most-once: no error, no retry, no DLQ entry. Only reconciliation notices.
  • Double side effects with at-least-once and a non-idempotent consumer: double charges, duplicate emails, inflated counters.
  • Dedup outside the transaction: the id is recorded but the effect fails (message never handled), or the effect commits but the id write fails (duplicate later).
  • Dedup window too short: ids are purged before a late redelivery or a DLQ redrive arrives.
  • Timeout shorter than processing: every slow message is processed twice, which also doubles the load exactly when consumers are already slow.
  • Auto-ack by default: some client libraries ack on delivery unless configured otherwise, turning a consumer into at-most-once without anyone deciding it.

In production

Treat at-least-once as the baseline and make every consumer idempotent; test it by delivering the same message twice in integration tests. Put the dedup insert and the effect in one transaction, keyed by a stable message or business id, and keep ids at least as long as the longest possible redelivery (including DLQ redrives). Set the visibility timeout above normal processing time and let the client library extend leases. Pass idempotency keys to external providers. Monitor redelivery and duplicate rates: a spike usually means consumers got slow.

Common misconceptions

  • "Our broker does exactly-once, so we don't need idempotency." Broker guarantees stop at the broker's boundary.
  • "Duplicates mean the queue is broken." They are the documented price of not losing messages.
  • "Acking early is just an optimisation." It changes the guarantee to at-most-once.
  • "A crashed message is redelivered as soon as the consumer dies." Only when its lease expires.
  • "Retries on the producer are harmless." Without producer idempotence they create duplicate messages too.

Interview angle

When a design has a queue, state the guarantee you assume ("at-least-once, consumers are idempotent by order id") before you are asked. Expect follow-ups: where duplicates come from, how the dedup record stays consistent with the effect, how long ids are kept, what the visibility timeout is and why, what happens to an external payment call, and why "exactly-once delivery" is not possible across a network (the Two Generals problem: the sender can never be sure its last message arrived). Saying "exactly-once effect, not exactly-once delivery" shows you know the difference.

Model assumptions

The simulation is a simplified model, not a benchmark. The Payments API publishes 12 messages per second (Poisson). Two workers with 4 slots each take about 400 ms per message (lognormal, cv 0.3); the slow worker is three times slower (about 1.2 s). The visibility timeout is 2 s (1 s in the duplicates and idempotency steps, 4 s in the tuning step). At-most-once is modelled as a queue that never redelivers (max deliveries 1, no dead letter queue): messages held by a crashed worker are dropped when their timeout expires (counted as dropped, not dead-lettered, because no dead letter queue is connected), which has the same outcome as acking on receipt. A crashed worker never completes the messages it held; in reality it may have done the side effect first. The engine counts every second completion of the same message as a duplicate; it does not model idempotency, so the dedup step and the ack-order sequences are scripted illustrations, and the Payments DB is scenery. Message accounting: each message ends in one outcome, counted once: delivered (first successful acknowledgement), dead-lettered (moved to a dead letter queue after its last delivery) or dropped (it ran out of deliveries with no dead letter queue connected, or a subscription was full or down when its copy arrived). Redelivered (a delivery that came back after its timeout) and duplicates (a message processed again after it had already been processed) are not outcomes: they count extra deliveries of messages that are counted once above. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Receive, process, acknowledge

    The Payments API puts a capture payment message on a queue for every order. Two workers take messages, charge the card through the Payments DB and then send an acknowledgement (ack). Only the ack removes the message from the queue for good.

    The highlighted message shows the order: delivery, charge, answer, ack. Between taking a message and acking it, the queue only hides it for the visibility timeout (2 s). That gap is where every delivery guarantee is decided: what happens if the worker dies inside it?

    Scene: The Payments API publishes capture messages to the Capture Queue. Workers 1 and 2 take them, charge the card in the Payments DB and acknowledge. A highlighted message travels queue → worker → database → worker → ack. Nothing is redelivered.

    Key idea: A delivery guarantee is a statement about what happens when a consumer fails between receiving a message and acknowledging it.

  2. 2. At most once: ack first, lose on crash

    Suppose the worker acks as soon as it receives a message, then charges the card. The highlighted message is acked after about 0.45 s; Worker 1 crashes at 1 s, before charging.

    The queue already forgot that message, and every other message Worker 1 was holding. Nothing is ever redelivered, so those payments are never captured. No duplicates, but silent loss. The engine models this as "deliver once, never again" (max deliveries = 1, no dead letter queue): when the crashed worker’s messages time out, they are dropped.

    Scene: Workers acknowledge on receipt. Worker 1 crashes one second in; the messages it held are never delivered again and are dropped, so those payments are lost. Worker 2 keeps processing the rest.

    Key idea: At-most-once: each message is handled zero or one times. Cheap and duplicate-free, but a crash loses work silently.

  3. 3. At least once: ack after the work

    Worker 1 is restarted and the code now acks after charging. Max deliveries is back to 5. At 1 s Worker 1 crashes again, holding a few messages it has not acked.

    This time nothing is lost: each unacked message becomes visible again exactly 2 s (the visibility timeout) after Worker 1 took it, and Worker 2 processes it. Recovery is not instant: those payments wait the whole timeout first.

    Scene: Workers acknowledge after charging. Worker 1 crashes one second in; two seconds after it took them, its unacknowledged messages reappear on the queue and Worker 2 processes them. No message is lost.

    Key idea: At-least-once: ack after processing. A crash causes a redelivery after the visibility timeout instead of a loss.

  4. 4. Slow is indistinguishable from dead

    Worker 1 is back but runs on a noisy host: each charge now takes about 1.2 s, three times longer. To recover faster from crashes, the visibility timeout was lowered to 1 s.

    The queue cannot tell slow from dead. When the timeout passes it hands the message to another worker, while Worker 1 is still charging. Both finish: the card is charged twice. The engine counts every second completion of a message as a duplicate. The same happens if a worker charges the card and crashes just before its ack.

    Scene: Worker 1 is degraded and takes longer than the 1 second visibility timeout. Its messages are redelivered to the other worker while it is still working, and both copies are processed: duplicate charges.

    Key idea: At-least-once means duplicates are normal, not a bug: slow consumers, lost acks and crashes after the side effect all cause them.

  5. 5. Effectively once: make the second time harmless

    The broker still delivers some messages twice; the engine keeps counting them. What changes is the consumer: in the same database transaction as the charge, it inserts the message id into a processed_messages table with a unique key.

    The scripted message shows it. Delivery 1 commits *id + charge*. Delivery 2 arrives after the timeout, its insert hits the unique key, so the worker skips the charge and just acks. Duplicate deliveries, one charge: *effectively once*. Deduplication only works if the id check and the side effect commit together.

    Scene: Scripted: one message is delivered to Worker 1, which commits the message id and the charge together. After the timeout it is delivered again to Worker 2, whose insert of the same id is rejected, so it acknowledges without charging. The simulation keeps redelivering slow messages in the background.

    Key idea: Exactly-once delivery is not available over a network; exactly-once effect is: at-least-once delivery plus an idempotent consumer.

  6. 6. Fewer duplicates, slower recovery

    Idempotency makes duplicates harmless; a sensible visibility timeout makes them rare. It is raised to 4 s, well above the slow worker’s 1.2 s. Redeliveries and duplicates stop.

    The price shows at 1 s, when the slow Worker 1 crashes: its messages now wait 4 s before Worker 2 gets them. Real consumers avoid choosing between the two by extending the lease while they work (a heartbeat that pushes the timeout out), so the timeout can stay short for dead workers.

    Scene: With a 4 second visibility timeout the slow worker finishes before its messages are redelivered, so there are no duplicates. When Worker 1 crashes, its messages reappear after 4 seconds and Worker 2 processes them.

    Key idea: Set the visibility timeout above the slowest normal processing time, extend it while working, and accept that it is also your crash-recovery delay.

  7. 7. Choose where duplicates and losses go

    Worker 1 is healthy again. At most once acks first: no duplicates, but crashes lose messages. At least once acks last: nothing is lost, but crashes, slow work and lost acks produce duplicates. Effectively once is at-least-once plus a consumer that records what it already did, atomically with the effect.

    "Exactly-once" features in brokers and stream processors are real but scoped: they cover reads and writes inside that system (for example a transactional read-process-write between topics), not your card provider or email server.

    Scene: The Payments API publishes to the Capture Queue, two healthy workers consume it and acknowledge after charging. Nothing is redelivered or duplicated.

    Key idea: Default to at-least-once with idempotent consumers; use at-most-once only where losing a message is acceptable.