Idempotency
medium 26 minAn idempotent operation has the same effect whether it runs once or many times.
Video lesson · Chapter 1 of 6
Two attempts, one intended charge
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
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.
1997
RFC 2068, the first HTTP/1.1 standard, says that GET, HEAD, PUT and DELETE share the property of idempotence.
2017
Stripe publishes a widely read article on designing APIs with idempotency keys.
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.
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.
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
How often does it happen?
With a key
By nature
What is idempotent already
Idempotent
SET balance = 100DELETE FROM users WHERE id = 5PUT /users/123- Adding to a set
Not idempotent
balance = balance + 100INSERT INTO orders ...without a unique keyPOST /payments- Appending to a list, sending an email
HTTP methods
| Method | Idempotent | Safe | Why |
|---|---|---|---|
| GET | Yes | Yes | Reads only |
| PUT | Yes | No | Sets a resource to X |
| DELETE | Yes | No | Already deleted is still deleted |
| POST | No | No | Creates something each time: needs a key |
| PATCH | Not promised | No | Depends on the change it describes |
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 100Keys
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.
POST /api/v1/payments HTTP/1.1Content-Type: application/jsonIdempotency-Key: 8f14e45f-ceea-467f-a8b8-6b5d9b1a1f50{ "amount": 9999, "currency": "usd", "customer_id": "cus_demo" }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?
Where must a key be unique?
| Scope | Same key on payments and refunds | Comment |
|---|---|---|
| Per endpoint | Allowed: they are separate | Friendly to clients |
| Global | Conflict: already used | Simple, but one user's key meets another's |
| Per user | Two users may use the same key | Always include this, or one user could receive another's stored answer |
| User + endpoint + key | Allowed | A good default |
How long to keep it
| Time | Used for |
|---|---|
| 24 hours | Stripe's API v1 may remove keys after at least this long |
| 48 to 72 hours | A common choice for your own API |
| 7 days | Careful, or when offline devices sync late |
| 30 days and more | When retries come from queues or people |
Build
The server's steps
Claim, work, save
What to do with a key
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';- 1
Claim
Insert the key as processing. If the insert is refused, look at the existing row.
- 2
Work
Process the request and pass a key on to every system you call.
- 3
Complete
Store the status code and body, and set completed, in the same transaction as your own changes.
- 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
| Tool | What the second request sees | Enough? |
|---|---|---|
INSERT with a unique constraint | An error for a duplicate key | Yes |
INSERT ... ON CONFLICT DO NOTHING RETURNING key | No row returned (not a row with NULL) | Yes, and no error to catch |
SELECT ... FOR UPDATE | Waits, if the row exists | Not 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.
| Died | State | Next step |
|---|---|---|
| Before the charge was sent | Nothing happened outside | Release the key, let the client retry |
| After sending, before the answer | Unknown | Ask the card network with the same key |
| After the answer, before saving | Charged, not recorded | Same lookup, then complete the key |
| After saving | Completed | Ordinary replay |
Recovering a stuck key
Which answers do you store?
| Result | Store it? | Why |
|---|---|---|
| Success | Yes | Replay it |
| Card declined | Yes | It is the final result of this intention; a new card is a new intention |
| Invalid input (400) | Usually no | No work was done; the client may fix it |
| Server error (500) | Differs | Stripe's API v1 stores and repeats it, even a 500 |
| Timeout to another system | Never as failed | The effect is unknown: keep processing and recover |
Patterns
Four ways to get it
| Pattern | How | Good | Careful | Best for |
|---|---|---|---|---|
| Client key | Idempotency-Key header | Flexible, widely used | Clients must keep it | General APIs |
| Request hash | hash of user, endpoint and body | No client change | Two honest, identical purchases look like one | Operations where equal means same |
| Business key | checkout:cart_42 | Has meaning, survives any retry | You must find the natural unit | Workflows |
| Unique constraint | UNIQUE (user_id, order_reference) | Simple, atomic | Fetch and return the existing row yourself | Creating one resource |
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 sameThe 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).
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.