What Is Idempotency in REST APIs - and When You Don't Need an Idempotency Key
Ask what is idempotency in REST APIs and you will get the textbook line: an operation is idempotent if performing it twice leaves the system in the same state as performing it once. That is correct, and it is also why most engineers hear the word, nod, and still ship an endpoint that charges a customer twice.
The reason the concept exists is narrower than the definition suggests. Over a network, a client that sends a write and gets a timeout does not know whether the write happened. It has two bad options: retry and risk a duplicate, or give up and risk losing the operation.
Idempotency is the property that removes that dilemma. If retrying is harmless, the client can always retry. Everything else on this page - idempotency keys, key tables, stored responses - is machinery for giving that property to operations that do not have it naturally.
| Concept | Idempotency (and the idempotency key) |
|---|---|
| Where it sits | API design - sits at the write path of your HTTP handler, between the retrying caller and your database |
| In one sentence | An endpoint is idempotent when a retried request produces no additional effect, which is what makes it safe for a caller to retry after an ambiguous failure. |
The 60-Second Answer
What it does: makes a repeated request produce the same state as a single request, so a caller can retry safely.
The one problem it solves: the ambiguous failure. A timeout or dropped connection leaves the client unable to tell "never applied" from "applied, response lost" - without idempotency, every retry is a coin flip between a duplicate and a lost write.
The one cost it adds: durable server-side state per operation. You now store a client-supplied key plus enough of the original response to answer a replay, with a scope, a retention window, and a failure mode of its own.
Before you build it: check whether the write is already an upsert on a natural key, or expressible as PUT. If so, a unique index gets you the same guarantee for free.
How It Actually Works
The mechanism, step by step
- 1. Idempotency is a property of the effect, not of the response bytes
- 2. HTTP already labels which methods must be idempotent
- 3. The real trigger is the ambiguous failure window
- 4. Where you can, model the write as a state assertion
- 5. For genuine creates, the client supplies an idempotency key
- 6. The server claims the key before doing the work
- 7. A replay returns the stored result, not a second execution
- 8. Scope and expiry are design decisions, not defaults
1. Idempotency is a property of the effect, not of the response bytes
Same state, not same reply
An operation is idempotent if applying it once and applying it five times leave the resource in the same state. It does not require that every attempt return an identical response.
A second DELETE /orders/42 that returns 404 is still idempotent - the state after attempt two matches the state after attempt one. What breaks idempotency is a second attempt that creates a second order, sends a second email, or increments a counter again.
Keeping that distinction straight tells you what you actually have to protect: side effects, not status codes.
⚠️ In production — Teams burn review cycles arguing whether the replay should return 200 or 404 and skip the question that matters - whether the second attempt moved money. Pick a response convention, document it, and spend your effort on the effect.
2. HTTP already labels which methods must be idempotent
The method table is a promise
HTTP classifies GET, HEAD, OPTIONS and TRACE as safe, meaning they are read-only and therefore idempotent. PUT and DELETE are idempotent but not safe - they change state, but repeating them changes nothing further. POST and PATCH carry no idempotency guarantee.
That table is a contract you promise to honour, not something your framework enforces. Nothing stops you from writing a GET handler that bumps a view_count, and nothing stops a PATCH body from saying "add 10 to the balance".
The labels exist so that generic intermediaries - proxies, HTTP client libraries, caches - can retry a request without understanding its payload.
⚠️ In production — The moment you break the method contract, every layer that trusted it starts hurting you silently. A GET with a write side effect gets retried by an SDK, prefetched by a browser, and replayed by a cache, and none of those will show up in your own logs as a bug.
3. The real trigger is the ambiguous failure window
Timeouts, not double-clicks
A request and its acknowledgement are two separate events, and either can be lost. When the client sees a read timeout or a connection reset, the server may have committed the write and lost the response on the way back.
This is why "just disable the submit button" is not a solution. The duplicate you care about is not a user clicking twice - it is a retry after an ambiguous outcome, issued by software.
Idempotency converts that unknowable question into one you no longer have to answer: retry until you get a definitive response.
⚠️ In production — The retrying party is usually not the code you wrote. HTTP client libraries retry idle-connection failures by default, load balancers and service meshes have retry policies, queue consumers get redelivered after a visibility timeout, and mobile clients retry on network change. You have retries whether or not you designed for them.
4. Where you can, model the write as a state assertion
Make it idempotent for free
If the client can name the resource, the write becomes "make this resource look like this" rather than "create another one". Repeating it is naturally harmless.
# client generates the id, so a retry targets the same row
curl -X PUT https://api.example.com/orders/8f2c1b7e-... \
-H 'Content-Type: application/json' \
-d '{"sku":"A-100","qty":2}'
The database equivalent is an upsert on a natural key with a unique constraint. This is the cheapest idempotency available: no key table, no stored responses, no retention policy. Reach for it before you reach for anything else.
⚠️ In production — It requires the client to generate the identifier, which is impossible if your ids come from a database sequence. And "last write wins" is not the same as safe - two different clients PUTting concurrently can resurrect stale data. That is a concurrency problem, and it needs ETag with If-Match or a version column, not an idempotency key.
5. For genuine creates, the client supplies an idempotency key
The caller names the operation
When the operation really is "create a new thing with a server-assigned id", there is nothing for a retry to collide with. So the client sends a unique token identifying the logical operation, and the server uses it to recognise repeats.
curl -X POST https://api.example.com/charges \
-H 'Idempotency-Key: 3f6b0a92-4c1d-4a77-9f2e-...' \
-d '{"amount":4200,"currency":"EUR"}'
The key is generated once per logical operation and reused across every attempt. That is the entire mechanism, and it is also the part clients get wrong.
⚠️ In production — Idempotency-Key is a de facto convention, not a universally ratified part of HTTP - check the specific API's docs for the header name and whether it is required or optional. On the client side, the classic bug is generating the key inside the retry loop: a fresh key per attempt turns your dedupe layer into an expensive no-op.
6. The server claims the key before doing the work
Insert-first beats check-then-act
Reading the key table, finding nothing, then performing the write leaves a race window: two concurrent retries both read "nothing" and both proceed. Instead, claim the key first by inserting it and letting a unique constraint reject the loser.
CREATE TABLE idempotency_keys (
scope text NOT NULL,
key text NOT NULL,
status text NOT NULL, -- in_progress | done
request_fp text NOT NULL,
response jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (scope, key)
);
If the side effect lives in the same database, do the claim and the write in one transaction and the problem is solved by the transaction boundary.
⚠️ In production — You cannot share a transaction with an external payment gateway or email provider, so there is always a crash-in-between case: key claimed, effect unknown. Handle it explicitly - keep the row as in_progress, reject concurrent retries with a clear conflict response, and have a reconciliation path that asks the provider what happened. Teams that skip this get a key row that blocks all retries forever on an operation that never completed.
7. A replay returns the stored result, not a second execution
Answer the retry truthfully
A retry that arrives after the work is done must get a definitive answer, otherwise the client keeps retrying. That means storing the original outcome - status code and response body, or enough identifiers to rebuild it - and serving it back on replay.
This is the step that turns an idempotent endpoint into a small durable cache of its own responses, and it is where most of the real cost sits.
Many APIs also mark the replay, for example with a response header, so clients and support engineers can tell a replay from a first execution.
⚠️ In production — Stored response bodies inherit everything in them: PII, tokens, amounts. That makes your key table a data-retention and access-control concern, not just a dedupe helper. Decide early whether you store the whole body or only the id you can re-fetch from.
8. Scope and expiry are design decisions, not defaults
Per-caller, with a retry-length window
Scope keys per API credential or tenant. A globally unique key space lets one caller collide with - or probe for - another's operations.
Store a fingerprint of the request alongside the key. If the same key arrives with a different body, that is a client bug, and the right answer is a loud error rather than silently returning the old result.
Retention is a tradeoff rather than a number: the window must outlive the longest retry path that could reasonably reach you, and every extra day is storage you carry and PII you retain. Measure your own retry horizon instead of copying someone else's TTL.
⚠️ In production — The failure is quiet and asymmetric. A window shorter than your real retry horizon - a background job retried hours later, a partner's nightly reconciliation sweep - produces duplicates that look like fresh legitimate requests, because by then the key is gone and the endpoint is behaving exactly as designed.
## Where You Meet It
- A payments endpoint. The client sends
POST /chargeswith an idempotency key, the connection drops before the response arrives, and the client retries with the same key. The server finds the claimed key, returns the stored charge, and the customer is billed once. Without the key the client must choose between a possible double charge and a possible unpaid order, and both end up in support tickets. - A webhook consumer. Providers deliver at-least-once, so the same event id will arrive twice sooner or later - after a timeout on your side, or during a provider retry sweep. The consumer treats the provider's event id as the idempotency key and claims it in the same transaction as the state change, which makes redelivery a no-op instead of a duplicate refund.
- A queue worker with a visibility timeout. If a job takes longer than the timeout, the broker hands the same message to a second worker while the first is still running. Idempotency at the job's write path is what stops that from producing two shipments; the
in_progressstate is what stops the second worker from doing the work in parallel. - An infrastructure reconciliation loop. Config tools re-apply desired state on every run, which only works because the underlying writes are
PUT-shaped assertions keyed by resource name. No key table is involved - the idempotency comes from the shape of the operation, which is the cheapest version of this mechanism.
When You Actually Need It
- Your duplicate-row or double-charge incidents correlate with timeouts and 5xx spikes rather than with user behaviour - that pattern is the ambiguous-failure window, and it will not go away on its own.
- There is at least one retrying layer between the caller and your handler that you do not control: an SDK with default retries, a proxy or service mesh retry policy, or a queue that redelivers.
- The operation has an irreversible external side effect - moving money, sending a message, provisioning a resource, calling a partner API - so "clean it up afterwards" is not actually available.
- The write creates an entity with a server-generated id, so there is no natural key for a unique constraint to catch the second attempt.
- You consume an at-least-once stream (webhooks, events, a message broker) where redelivery is a documented property of the producer, not an anomaly.
- You run a public or partner API and cannot inspect or fix how callers retry, so the safety has to live on your side of the boundary.
When You Don't
- The write is already an upsert on a natural key - an email address, an external order number, a
(tenant_id, sku)pair. Add the unique constraint and handle the violation. That is idempotency, done, with no key table and no retention policy. - The endpoint is
PUTorDELETEand genuinely behaves as a whole-resource assertion. It is already idempotent by construction; bolting a key table onto it adds a storage dependency and a new failure mode in exchange for a guarantee you had. - Low-volume internal tooling where a duplicate is cheap and reversible: an admin form doing a few dozen writes a day from a browser, no SDK retries, no queue, and an operator who can delete a duplicate row in ten seconds. A unique index on the obvious natural key plus a disabled submit button is the correct engineering. Revisit it when the endpoint gets a programmatic caller or starts touching money.
- Read-only endpoints. If a
GETis not already repeatable, the bug is the hidden write in your handler. Remove it rather than making the read idempotent. - You are reaching for an idempotency key to fix lost updates or out-of-order writes. Wrong tool - keys dedupe identical operations, they do not order concurrent different ones. Use
ETagwithIf-Match, or a version column with a compare-and-set. - You are building a general cross-service idempotency framework before any endpoint has the property. Make the one money-touching endpoint idempotent end to end first; the framework requirements you guess at now will not survive contact with the external-side-effect crash case.
What People Get Wrong
"POST can't be idempotent - it's in the spec."
The spec says clients may not assume POST is idempotent, which is different from saying you cannot implement it that way. A specific POST endpoint with an idempotency key is idempotent in practice; what you lose is the ability for a generic intermediary to retry it blindly, because the dedupe depends on a header it knows nothing about.
"With idempotency keys we get exactly-once semantics."
You get at-most-once effects for retries carrying the same key, on top of at-least-once delivery. The client can still fail to learn the outcome - it may never see any response - so it needs a way to ask later. Exactly-once across a network boundary is not available; what you are building is at-least-once delivery plus receiver-side dedupe, which behaves like once when both halves hold.
"We dedupe keys in the cache layer, which is fast and good enough."
It is good enough until the cache evicts under memory pressure, fails over, or loses its most recent writes. If the dedupe store is less durable than the side effect it protects, you have a duplicate window whose size is set by someone else's eviction policy. Put the key where the write commits, or accept the window as a measured, documented decision.
"Retries are the client's problem."
The ambiguity is created by your API, not by the client. An endpoint that cannot be safely retried forces every caller to choose between duplicates and data loss, and they will resolve it inconsistently - which means your data, not theirs, ends up wrong.
Why It Was Built This Way
The constraint is older than REST: over an unreliable channel, a message and its acknowledgement are separate events, and the acknowledgement can be lost. A sender that gets no reply cannot distinguish "never arrived" from "arrived, applied, reply lost". No amount of client-side cleverness closes that gap, because the information the client needs is on the other side of the failure.
So the responsibility has to move to the receiver - and for the receiver to recognise a repeat, the sender must give the operation a stable name. That is the whole reason the key is client-supplied rather than server-generated: a server-generated id would be assigned after the request arrived, which is precisely the moment you cannot trust.
What was traded away is statelessness. REST's practical appeal was that the server kept no per-request memory, which is what made horizontal scaling easy to reason about. An idempotency key store puts durable per-operation state back on the server, and it has to be at least as durable as the side effect it guards - which usually means it lives in your primary database rather than somewhere cheap. You also inherit a retention policy, a scoping model, and a response cache holding whatever sensitive fields your write returned.
HTTP's method table was the earlier, cheaper answer to the same constraint: label methods so that generic intermediaries can retry without understanding the payload. It works, and it costs nothing, but it only covers operations expressible as whole-resource assertions. POST is the residue - the operations that genuinely create something new and therefore have no name to assert against. Idempotency keys are what you pay to give that residue the same retry safety that PUT gets for free.
Related Briefs
What to Read Next
- http idempotent vs safe methods
- at-least-once vs exactly-once delivery
- optimistic locking with etag and if-match
Idempotency is not a feature you add to an API; it is a property an operation either has or lacks, and your job is to notice which. Most writes can be reshaped into assertions over a natural or client-supplied key, and those cost you a unique index. Spend the key table, the stored responses, and the retention policy only on the operations that genuinely create something new and genuinely cannot be undone - and when you do, design the crash-between-claim-and-effect case before you ship, because that is the one that will page you.
댓글
댓글 쓰기