Learn

PATTERN · ORIGINAL

Consistency and idempotency in practice

What read-your-writes, linearizable and eventual consistency mean for a real feature, why retries create duplicates, and how idempotency keys and idempotent consumers make "effectively once" possible.

Two questions come up in almost every design that moves money, holds inventory, or sends messages. First: when one person changes something, who sees the change, and when? Second: when a request is retried, does the action happen twice? The first is about consistency. The second is about idempotency. They are separate ideas, but they meet at the same spot on your sketch: the write to the store that holds the truth.

This article skips formal definitions where a concrete feature makes the point better, and focuses on what to draw and say.

Consistency guarantees, by what the user sees

Eventual consistency

Replicas accept the write at different times, and if writes stop, they all converge. In between, a reader can see old data, and two readers can see different data. That is fine for a like count, a profile photo, or a follower list: a few seconds of staleness costs nothing.

What eventual consistency does not tell you is how long or in what order. If a user posts a comment and then reloads the page, a plain eventually consistent read might not show the comment. That feels broken even though nothing is wrong with the data.

Read-your-writes and other session guarantees

Read-your-writes promises that a user always sees their own writes, even if others see them later. It is often all a product needs. Common ways to get it:

  • Route a user's reads to the primary for a short window (say 10 seconds) after they write.
  • Have the client remember the version or log position of its last write and ask for a replica that has caught up to at least that point.
  • Show the write optimistically on the client from local state while the server catches up.

Close relatives: monotonic reads (you never see data go backwards, usually done by sticking a session to one replica) and consistent prefix (you never see a reply before the message it answers, which matters in chat).

Linearizable

Linearizability means the system behaves as if there is one copy of each item and every operation takes effect at a single instant between its start and its end. Once a write completes, every later read, from anyone, sees it. This is what you need when two people race for the same thing: the last seat, the last unit of a limited giveaway, a username, a lock.

It costs coordination. A linearizable write needs agreement from a leader or a quorum, so it is slower and becomes unavailable on the minority side of a network partition. Do not ask for it everywhere. Ask for it on the one or two keys where a race would break an invariant.

Conditional writes: the tool you actually reach for

In practice you rarely say “make the database linearizable”. You use a single-key atomic operation that the store already provides:

  • Insert if absent: create a short alias or a username only if nobody has it.
  • Compare-and-set on a version: update the document only if its version is still 17.
  • Conditional decrement: UPDATE stock SET n = n - 1 WHERE id = ? AND n > 0, then check that one row changed.

These give you linearizable behaviour exactly where it matters, scoped to one row or key, without making the rest of the system pay. On hotel booking or a giveaway, naming the conditional write that enforces “never oversell” is usually the strongest single thing you can say. Reservations and contention goes deeper on holds and hot inventory.

OptionWins whenCosts
EventualStaleness is harmless: counts, feeds, profiles, search indexesUsers may not see their own change; ordering surprises without extra care
Read-your-writesUsers edit their own data and expect to see it on reloadSession routing or version tracking; others can still see old data
Conditional write on one keyA single item has an invariant: unique name, stock never below zeroContention on hot keys; only covers one key at a time
Linearizable across many keys (transactions)An invariant spans items: debit one account and credit anotherCoordination latency, lower availability under partition, harder to scale

Why retries create duplicates

Here is the failure that idempotency exists to fix. A client sends “transfer 100 from A to B”. The server does the transfer, commits it, and starts sending the response. The connection drops. From the client's point of view, the request timed out. It has no way to know whether the transfer happened.

It has two choices. Give up, and maybe the transfer never happened. Retry, and maybe it happens twice. Every layer has this problem: mobile apps retry, load balancers retry, SDKs retry, queue consumers get redelivered messages. You cannot make the network reliable, so you must make the retry safe.

Some operations are naturally safe to repeat. “Set the display name to Ana” leaves the same state if applied twice. “Add 100 to the balance”, “send an email”, and “charge the card” are not. The design work is turning the second kind into the first.

Idempotency keys

The client generates a unique key (a random UUID is fine) for each logical operation and sends it with every attempt of that operation. The server records the key together with the outcome. If the same key arrives again, the server returns the stored outcome instead of doing the work again.

FIG. 3ORIGINAL SKETCH
POST + key1claim key2debit + credit3same txn4at least once5stored resultClient appkey = uuid per actionTransfer APILedger DBone transactionIdempotency keysunique (account, key)OutboxNotifierretry = same key
An idempotent transfer: the API claims the idempotency key and applies the ledger change in one transaction, so a retry with the same key returns the stored result instead of moving money twice.

Record the key atomically with the effect

The key is only useful if “key recorded” and “work done” cannot disagree. If you check a cache for the key, do the transfer, then write the key, a crash between the last two steps loses the key and the next retry transfers again. Put the key row and the ledger rows in the same database transaction, with a unique constraint on the key. A concurrent duplicate then fails the constraint and waits for, or reads, the first attempt's result.

When the effect is in another system you cannot share a transaction with (a card network, an email provider), pass your key through if the provider supports one, and record the attempt state (started, succeeded, failed) so a retry knows whether to resume, wait or return. Card payments is a good place to practise this.

Scope

Keys must be scoped to whoever generated them. Make the unique constraint (account_id, key), not just key, so one client cannot collide with or probe another's keys. Also store a hash of the request parameters: if the same key comes back with a different amount, that is a client bug, and the right answer is an error, not silently returning the old result.

Expiry

Keys cannot live forever, and they do not need to. They exist to cover the retry window. If clients retry for at most a few minutes, keeping keys for 24 hours gives a wide margin. Pick a number based on the longest realistic retry, including a phone that goes offline and resumes the next morning, and write it down as a contract. For money movement, some teams keep the key for as long as the record itself; storage is cheap compared with a double payment.

Dedupe when you cannot control the sender

Sometimes the duplicate comes from a source that will not send a key: a webhook provider, a sensor, an upstream queue. Then derive one. Use the provider's event id if it has one; otherwise hash the fields that define “the same event” (source, type, natural id, timestamp bucket). Keep a dedupe table or set with a TTL slightly longer than the source's maximum redelivery window.

Be honest about what natural dedupe catches. Two legitimately separate events with identical fields will be merged. That is usually acceptable for notifications and analytics, and usually not acceptable for payments, which is why payment APIs insist on explicit keys.

At-least-once plus idempotent consumer equals effectively once

Messaging systems offer roughly three delivery promises. At-most-once can lose messages. Exactly-once delivery across independent systems is not something a network can promise end to end. At-least-once never loses a message but may deliver it more than once. The practical recipe is: use at-least-once delivery, and make the consumer idempotent. The result is that each message's effect happens once, even if the message arrives three times.

An idempotent consumer does one of these:

  • Records the message id in the same transaction as its write, and skips ids it has already processed.
  • Makes the write itself idempotent: an upsert keyed by a natural id, or “set status to shipped” instead of “advance status by one step”.
  • Uses a version check: apply the update only if the stored version is older than the message's version, which also handles out-of-order delivery.

The transactional outbox in Fig. 3 is the same idea on the producer side. Instead of writing to the database and then publishing an event (a crash in between loses the event), write the event to an outbox table in the same transaction and let a relay publish it at least once. Downstream consumers dedupe. This is how a notification service avoids both missed and doubled sends. Queues, retries and dead letters covers the delivery side in more detail.

Putting it on the board

When a question involves money, inventory or messages, add three small things to your sketch: the conditional write or transaction that enforces the invariant (accent that box), the idempotency key with its scope and expiry written next to the API, and “at least once, consumer dedupes by id” written next to every async arrow. That is often enough to answer the first two follow-ups before they are asked. For how per-key ordering and partitioning interact with this, see partitioning and ordering; for why the Dynamo paper chose eventual consistency for a shopping cart, see that case study.

TAKE THIS TO YOUR NEXT SKETCH

  • Pick consistency per feature: eventual for counts and feeds, read-your-writes for users editing their own data, conditional writes for single-key invariants.
  • Ask for linearizable behaviour only on the keys where a race breaks an invariant, and name the conditional write that enforces it.
  • Timeouts make the outcome unknown, so every client retries; design every non-idempotent write to survive a retry.
  • Store the idempotency key in the same transaction as the effect, with a unique constraint scoped to the caller.
  • Give keys an expiry longer than the longest realistic retry and reject a reused key with different parameters.
  • At-least-once delivery plus an idempotent consumer gives each effect exactly once; use an outbox to publish events reliably.

PRACTICE WITH THIS

Now sketch one.

OFF-SITE READING · NOT WRITTEN BY US

Further reading

  • Designing robust and predictable APIs with idempotency

    Stripe blog

    A payments team explains why network failures make retries unavoidable and how client-supplied keys let a server answer a retry with the original result.

  • Idempotent requests (API reference)

    Stripe documentation

    A concrete, production contract for idempotency keys, including how long keys are kept and what happens when a retry carries different parameters.

  • Making retries safe with idempotent APIs

    Amazon Builders’ Library

    Covers client request tokens, what to return when a token is reused with different input, and how to record the token atomically with the side effect.

  • Consistency Models

    Jepsen

    A clickable map of consistency models and how they relate, with short definitions of linearizability, sequential consistency and session guarantees.

  • Eventually Consistent

    Werner Vogels, All Things Distributed

    A short essay from Amazon’s CTO on client-side guarantees such as read-your-writes and monotonic reads under eventual consistency.

Next: Counting at scale: exact when it matters, approximate when it does not