Skip to content

Delivery guarantees and idempotency

Phase 6 · Distributed systems · 16 min read · 2 Atlas cases linked

What you'll be able to do

  • Explain why a timeout cannot tell you whether a remote operation happened, and choose a safe retry policy.
  • Make a side effect safe to retry with an idempotency key, and say what durable, atomic state that needs across restarts.
  • Use an outbox and consumer deduplication to recover from failures between database work and event delivery.

The answer can get lost

Suppose a client asks a payment service to charge $20. The service commits the charge, then sends 200 OK. The network drops the response. From the client's point of view, this looks exactly like a request that never reached the service. A timeout reports uncertainty, not failure. A missing response leaves the client unable to tell whether the charge committed; the two generals problem has the same root, because a missing message proves nothing. Retrying with the same key makes acting under that uncertainty safe; it does not remove the uncertainty.

The response is lost after the charge commits; a blind retry charges a second time.

If the client gives up, it may never learn that it paid. If it retries blindly, it might charge twice. The same ambiguity appears when a queue worker finishes work but crashes before acknowledging its message. Timeouts and retries covers retry policy; here we make the work safe to retry.

What delivery guarantees actually promise

Policy What the sender does Consequence
At most once Sends or processes once, with no retry after uncertainty Work may be lost; no duplicate attempt from this mechanism
At least once Retries until acknowledgement Work is eventually attempted if the system recovers, but may run more than once
Exactly once Depends on the stated boundary Often means one committed effect inside a particular system, not one execution everywhere

An acknowledgement is another network message and can disappear. No queue can make an arbitrary external side effect and its own acknowledgement indivisible. A system may provide exactly-once effects within a transaction, or by combining at-least-once delivery with deduplicated handling. A feature labelled “exactly once” has a scope: ask whether it covers a queue's internal state, a database transaction, or the payment provider.

For a broker with a visibility timeout, polling hides a message temporarily. If the worker does not acknowledge before the timeout, another poll can return it. Ack after durable processing: a crash before ack causes a duplicate, which your handler must tolerate. Ack before processing risks permanent loss when the worker crashes. Committing a stream offset before or after work has the same trade-off. Repeatedly failing poison messages need a retry limit and dead-letter handling; see queues and streams.

Make the operation idempotent

An operation is idempotent when applying it twice has the same intended effect as applying it once. set balance = 20, put this object at this key, and delete this key are often naturally idempotent; increment balance, append a row, and charge $20 are not. A delete that also sends a new email each time is not.

For a non-idempotent operation, the caller supplies an idempotency key that identifies one logical request. The server stores the key, a representation of the request, and the result. On a retry with the same key and payload, it returns the stored result without repeating the effect. With the same key and a different payload, it rejects the request. A key is scoped to a caller and operation: two callers may both use order-7, but one caller reusing it for a different payment is an error.

key = "checkout-42-charge"
charge(key=key, amount_cents=2000)  # commits; reply is lost
charge(key=key, amount_cents=2000)  # returns prior result
charge(key=key, amount_cents=3000)  # reject: key reused

The key record must outlive possible retries. If the service discards it after 24 hours but a job retries after two days, the request can run again. Define retention from the retry horizon and business rules; after expiry, the caller needs another way to reconcile the outcome. Store the response, not just “seen”: otherwise a retry cannot learn the result.

Two copies of a request can arrive before either finishes. A separate “check if key exists; then insert” races. Reserve the key atomically, for example with a database unique constraint or conditional write, and record an in-progress state. A duplicate can wait, receive an in-progress response, or retry later; it must not start a second charge. Upserts, unique constraints, and version checks can also make writes safe, but their guarantees depend on the transaction boundary. See indexes and transactions. A record held only in process memory disappears on restart; surviving one needs a durable record, committed in the same transaction as a local effect.

An error raised by the operation needs the same care. Release the key only when you know the effect did not happen, such as a validation failure before any external call. A timeout from a downstream service does not tell you that: the charge may have gone through. Keep the request unresolved and reconcile it by finding out what really happened, or pass the same key to a downstream operation that is itself idempotent. A crash can also leave a record stuck in progress; treat its outcome as unknown, not as permission to run again.

Duplicates, order, and the dedupe window

Deduplication needs storage. A consumer might keep (consumer_name, message_id) in a table with a unique constraint and commit that marker in the same transaction as its database update. This is the inbox pattern. The marker makes redelivery harmless for that consumer. If the marker expires, a late redelivery may run again; choose its lifetime from the maximum redelivery horizon.

Duplicates and ordering are separate problems. Processing message 2 once before message 1 once still gives the wrong result if message 2 assumed message 1 had run. For a balance, +5 then ×2 yields a different value from ×2 then +5. Two additions commute (+5 then +3 equals +3 then +5), but duplicate additions still change the answer. Use per-entity ordering or version checks where order matters; use deduplication where repeats matter. Neither replaces the other.

The database and event are two writes

Suppose an order service commits an order, then publishes OrderCreated. The publish can fail: the order exists, but no consumer hears about it. Publish first and the database commit can fail: consumers hear about an order that does not exist. These are two independent writes, so rearranging them does not make them atomic.

The transactional outbox puts the order row and an event row in the same database transaction. Either both commit or neither does. A relay reads unsent outbox rows, publishes them, then marks them sent. If publishing succeeds but the relay crashes before marking the row, it will publish again. Consumers still need deduplication, typically with an inbox or an idempotent handler.

The outbox: the order and its event commit together; the relay may publish twice, so consumers dedupe.

Change data capture is another way to drive the relay: it reads committed database changes instead of polling the outbox table. Either way, the outbox closes the order/event gap but not the duplicate problem. Say a relay publishes 100 events, marks 99 as sent, and crashes before marking the last one. After restart it publishes that one again. In this one-crash example, 100 publishes plus one replay produce 101 deliveries for 100 business effects. Further crashes can produce more; deduplicate every delivery.

For AI engineers

For AI engineers

Your agent framework may retry a tool call after a timeout. If that tool sends an email, buys an item, or writes a database row, give the action a stable key tied to the agent step and store its outcome. A model's repeated text is not a reliable dedupe key: the same action can be expressed differently, and similar text can represent different actions. Each inference attempt may still cost money: avoiding a repeated business effect does not avoid a repeated provider charge.

A training or ETL job may be restarted on the same input. Write deterministic partition names, replace or upsert outputs, and publish a completed output directory only after its contents are ready (an atomic rename where the filesystem supports it). An embedding pipeline should identify chunks by source and version so replay updates existing rows rather than adding duplicates. If a pipeline updates a database and emits an event, its outbox and the downstream inbox follow the same rules as the order example.

Common mistakes

  • Trusting “exactly once” end to end: read the feature's boundary and design external effects for replay.
  • Checking then inserting a key in two steps: concurrent requests can both pass the check; use an atomic reservation or unique constraint.
  • Reusing a key for a new payload: compare request identity and reject mismatches; scope keys by caller and operation so unrelated requests cannot collide.
  • Saving only “seen”: save the result so a retry can receive the original answer.
  • Publishing before the database commit: a consumer can act on an event for a transaction that rolls back; use an outbox.
  • Acknowledging before durable work: a crash can lose the message permanently; commit first, then ack.

Check yourself

A charge commits, but its HTTP response is lost. Should the client retry with a new key or the original key?

Use the original key and the same request. The server can return the stored result without a second charge. A new key represents a new logical request and could charge again.

Two workers receive the same message while the first is still running. Why is a “check, then insert” dedupe table unsafe?

Both workers may see no row before either inserts. A unique constraint or conditional reservation must decide ownership atomically; the other worker waits, gets an in-progress response, or retries.

A relay publishes an outbox event and crashes before marking it sent. What happens on restart, and what must the consumer do?

The relay can publish the event again. The consumer uses the event ID and a durable inbox marker committed with its effect, or another idempotent operation, so the repeated delivery has one business effect.

Your handler calls a payment provider, and the call raises a timeout. Should the handler delete the idempotency key so a retry can run?

Not unless it knows the charge did not happen. The provider may have charged and lost the reply, so deleting the key lets a retry charge again. Keep the request unresolved and reconcile with the provider, or send the same key if the provider treats it idempotently.

A worker acknowledges a message, then crashes before saving its database update. What guarantee did that ordering sacrifice?

The message may be lost without the update. Acknowledgement should follow the durable update; the resulting redelivery risk is handled with deduplication.

Lab

Build an idempotent handler and an at-least-once consumer in code/delivery-idempotency/. The supplied broker redelivers after a visibility timeout and can lose an acknowledgement. The key store is in memory: it models one process, not deduplication across restarts. Write an order and outbox event in one SQLite transaction, then relay pending events. Compare this with a supplied unsafe dual write when publishing fails. Run: cd code/delivery-idempotency && PYTHONPATH=starter python -m pytest tests -q

Go deeper

See it in the wild

Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.