AlgoViz

Idempotency

medium 26 min

An idempotent operation has the same effect whether it runs once or many times.

Video lesson · Chapter 1 of 6

Two attempts, one intended charge

0:00 / 5:07

Idempotency

1:17Reel

Theory

Read or listen first. About 2 min.

What it is

An operation is idempotent if doing it several times leaves the system in the same state as doing it once. Setting a light to on is idempotent. Flipping the switch is not.

It is about the effect, not about the answer. Deleting a file twice may answer "done" and then "not found", but after both calls the file is gone, so the delete is idempotent.

Why it exists

When a request times out, the client cannot know whether the server did the work. The request may have been lost, or the answer. If it does not try again, the work may never happen. If it does, the work may happen twice.

Idempotency removes the bad half of that choice. If repeating is harmless, the client can simply retry until it gets an answer. That is why retries, queues, webhooks and crash recovery all depend on it.

A short history

  1. 1870

    The mathematician Benjamin Peirce introduces the word, from the Latin idem (same) and potent (power), for elements that stay the same when multiplied by themselves.

  2. 1997

    RFC 2068, the first HTTP/1.1 standard, says that GET, HEAD, PUT and DELETE share the property of idempotence.

  3. 2017

    Stripe publishes a widely read article on designing APIs with idempotency keys.

  4. 2022

    RFC 9110, today's HTTP standard, defines idempotent methods again. A separate draft for an Idempotency-Key header was still a draft in November 2026.

Words to know

Idempotent
Same effect once or many times.
Safe
Meant only to read. Every safe method is idempotent, but not the other way round.
Idempotency key
A unique value the client makes for one intention and sends with every attempt.
Replay
Answering a repeated request with the stored answer, without doing the work again.
Claim
Inserting the key before the work, so that only one request may do it.
Retry window
How long clients may still repeat a request. Keys must live at least that long.

How it works

Step through the idea, or press Play.

Step 1 of 3

One key per intention. The client makes it once and keeps it for all retries

Understand it

Start here

The lift and the juice machine

Press a lift button once or five times: one lift comes. Press a juice machine's button five times and you get five cans. The first is idempotent. The second becomes so with a small trick.

Two buttons
3Pressed 1 time

The ticket belongs to the wish for one juice, not to the press. A second juice needs a second ticket.

The problem

A timeout means: I do not know

A customer clicks Pay $99.99. The server charges the card, and then the network fails before the answer arrives. The customer clicks again, and once more.

Without a key

After one retry 199.98,aftertwo199.98, after two 299.97. Every part did what it was told.

How often does it happen?

100,000 paymentsday×0.1%=100 lost answers a day100{,}000\ \tfrac{\text{payments}}{\text{day}} \times 0.1\% = 100\ \text{lost answers a day}
Assumption: 1 in 1,000 answers is lost after the work was done. Without protection that is up to 100 double charges a day.

With a key

Same key, same answer, one charge.

By nature

What is idempotent already

Idempotent

  • SET balance = 100
  • DELETE FROM users WHERE id = 5
  • PUT /users/123
  • Adding to a set

Not idempotent

  • balance = balance + 100
  • INSERT INTO orders ... without a unique key
  • POST /payments
  • Appending to a list, sending an email

HTTP methods

MethodIdempotentSafeWhy
GETYesYesReads only
PUTYesNoSets a resource to X
DELETEYesNoAlready deleted is still deleted
POSTNoNoCreates something each time: needs a key
PATCHNot promisedNoDepends on the change it describes
The standard says what a method promises. Your code must keep the promise: a GET that counts views in a billed counter breaks it.
HTTP
PUT /users/123    {"name": "Asha"}      -> user 123 is AshaPUT /users/123    {"name": "Asha"}      -> user 123 is Asha (same)POST /users       {"name": "Asha"}      -> created user 123POST /users       {"name": "Asha"}      -> created user 124 (a duplicate)PATCH /accounts/123  {"op": "add", "amount": 100}   -> 100, then 200PATCH /accounts/123  {"balance": 100}               -> 100, then 100
Absolute values can be repeated. Relative changes cannot.

Keys

The idempotency key

A unique value that the client makes and sends with the request. The server uses it to see that two requests are the same intention.

HTTP
POST /api/v1/payments HTTP/1.1Content-Type: application/jsonIdempotency-Key: 8f14e45f-ceea-467f-a8b8-6b5d9b1a1f50{ "amount": 9999, "currency": "usd", "customer_id": "cus_demo" }
The amount is in cents. The key is an example.

A good key

  • Different for each different intention
  • The same for every retry of it
  • Made by the client, before the first attempt
  • Random, such as a version 4 UUID
  • Saved on the device, so a restart does not lose it

A bad key

  • Made again for each attempt
  • Made by the server: the client never receives it if the answer is lost
  • Contains an email address or a name
  • User plus action plus time of the attempt: the time changes on a retry
  • Short enough to collide

Can two random keys be the same?

p≈n22⋅2122,n=109;⇒;p≈10181.06×1037≈10−19p \approx \frac{n^2}{2 \cdot 2^{122}}, \qquad n = 10^9 ;\Rightarrow; p \approx \frac{10^{18}}{1.06 \times 10^{37}} \approx 10^{-19}
A version 4 UUID has 122 random bits. After a billion keys the chance of any collision is still negligible.

Where must a key be unique?

ScopeSame key on payments and refundsComment
Per endpointAllowed: they are separateFriendly to clients
GlobalConflict: already usedSimple, but one user's key meets another's
Per userTwo users may use the same keyAlways include this, or one user could receive another's stored answer
User + endpoint + keyAllowedA good default

How long to keep it

TimeUsed for
24 hoursStripe's API v1 may remove keys after at least this long
48 to 72 hoursA common choice for your own API
7 daysCareful, or when offline devices sync late
30 days and moreWhen retries come from queues or people
Longer than the longest possible retry. After that a repeated request counts as new, so the business table needs its own unique key too.

Build

The server's steps

Claim, work, save

A client sends a POST with key k1 to a payment API inside our system. First the API claims k1 in a database that holds keys and payments, second it charges the card network outside our system and passes on key k1, third it saves the result in the database.
The key store is a table in the same database as the payments, so result and key are saved together. The same key travels on to the card network.

What to do with a key

No key at all on an endpoint that needs one: answer 400.
SQL
CREATE TABLE idempotency_keys (  user_id       VARCHAR(64)  NOT NULL,  endpoint      VARCHAR(128) NOT NULL,  key           VARCHAR(255) NOT NULL,  request_hash  CHAR(64)     NOT NULL,           -- SHA-256 of the body  status        VARCHAR(12)  NOT NULL,           -- processing, completed  response_code INTEGER,  response_body JSONB,  created_at    TIMESTAMPTZ  NOT NULL DEFAULT now(),  expires_at    TIMESTAMPTZ  NOT NULL,  PRIMARY KEY (user_id, endpoint, key));CREATE INDEX idempotency_expiry ON idempotency_keys (expires_at);-- every hour; never touch a key whose work is unresolvedDELETE FROM idempotency_keysWHERE expires_at < now() AND status = 'completed';
PostgreSQL. The primary key is the unique constraint, so it needs no second index.
  1. 1

    Claim

    Insert the key as processing. If the insert is refused, look at the existing row.

  2. 2

    Work

    Process the request and pass a key on to every system you call.

  3. 3

    Complete

    Store the status code and body, and set completed, in the same transaction as your own changes.

  4. 4

    Answer

    Return the result. If this answer is lost, the next request finds it stored.

Races

Two requests at the same moment

Both look for the key, both find nothing, both go on: a double charge. Looking first and writing later always leaves a gap.

Three database tools

ToolWhat the second request seesEnough?
INSERT with a unique constraintAn error for a duplicate keyYes
INSERT ... ON CONFLICT DO NOTHING RETURNING keyNo row returned (not a row with NULL)Yes, and no error to catch
SELECT ... FOR UPDATEWaits, if the row existsNot for a new key: there is no row to lock. Use it after the insert.

Crashes

The server dies in the middle

A key stays in processing for ever if its server crashed. What may happen next depends on whether the outside world was touched.

DiedStateNext step
Before the charge was sentNothing happened outsideRelease the key, let the client retry
After sending, before the answerUnknownAsk the card network with the same key
After the answer, before savingCharged, not recordedSame lookup, then complete the key
After savingCompletedOrdinary replay
You cannot tell the first three apart from inside. So always ask, or repeat the call with the same key if the other side is idempotent.

Recovering a stuck key

Some lookups show new charges only after a delay. Not found yet is not the same as never happened.

Which answers do you store?

ResultStore it?Why
SuccessYesReplay it
Card declinedYesIt is the final result of this intention; a new card is a new intention
Invalid input (400)Usually noNo work was done; the client may fix it
Server error (500)DiffersStripe's API v1 stores and repeats it, even a 500
Timeout to another systemNever as failedThe effect is unknown: keep processing and recover

Patterns

Four ways to get it

PatternHowGoodCarefulBest for
Client keyIdempotency-Key headerFlexible, widely usedClients must keep itGeneral APIs
Request hashhash of user, endpoint and bodyNo client changeTwo honest, identical purchases look like oneOperations where equal means same
Business keycheckout:cart_42Has meaning, survives any retryYou must find the natural unitWorkflows
Unique constraintUNIQUE (user_id, order_reference)Simple, atomicFetch and return the existing row yourselfCreating one resource
The old worry about hash collisions is not the issue with SHA-256. Two people who really want the same thing twice is.
SQL
ALTER TABLE orders  ADD CONSTRAINT unique_order_ref UNIQUE (user_id, order_reference);INSERT INTO orders (user_id, order_reference, amount)VALUES ('user_123', 'checkout_42', 9999)ON CONFLICT (user_id, order_reference) DO NOTHING;-- then SELECT the order: the first call and the retry answer the same
Often you need no separate key table at all.

The same idea elsewhere

  • Queues

    Delivery is usually at least once. The consumer keeps the ids it has handled.

  • Webhooks

    The event id is the key.

  • Jobs

    Write to an output named after the day, then replace it. Running again gives the same file.

  • Infrastructure

    Describe the wanted state (three servers) instead of an action (add a server).

See also webhooks, queues, and retries for when and how often to repeat.

Limits

What it does not give you

It does

  • Make retries harmless
  • Turn at-least-once delivery into one effect
  • Let clients be simple: repeat until answered

It does not

  • Deliver exactly once over a network
  • Order requests or stop lost updates
  • Undo something that must not have happened
  • Protect a click on two different devices, unless the key comes from the business

Numbers

What it costs

One insert and one update per write, and storage for the window. With 100,000 payments a day and 2 KB each, 72 hours are 300,000 rows or 600 MB. That is small beside one wrong charge, so the cost is rarely the reason to leave it out.

Summary

The whole topic in one minute.

A lost answer looks the same as a lost request, so clients must repeat requests, and writes must be safe to repeat. Prefer operations that are idempotent by nature: set instead of add, a PUT to a chosen id, a unique constraint on a business key.

For the rest, the client makes one key per intention. The server claims it with a unique insert, does the work, stores the answer with the work, and replays it later. The hard part is a crash in the middle: ask the other side before trying again.

  • Idempotent means: once or many times, the same effect.
  • A timeout means unknown, so clients must retry and writes must allow it.
  • GET, PUT and DELETE are idempotent by definition. POST needs a key, PATCH depends.
  • One client-made key per intention, claimed by a unique insert, scoped to the user.
  • Save answer and work together, and recover stuck keys by asking, not by guessing.

Sources