The short answer: An idempotency key is a unique value a client sends with a request that changes state, such as creating a payment or an order, so that if the request is retried, the server performs the operation only once and returns the same result. The client generates the key (a random UUID is typical) once per logical operation and reuses it on every retry. The server stores the key with a fingerprint of the request and the response, atomically claims the key before doing the work, replays the stored response for repeats, rejects the same key with a different payload, and expires keys after a set period.
Networks fail in an annoying way: they don't tell you which side the failure happened on. A client sends "charge this card $50," waits, and gets a timeout. Did the request never arrive? Did it arrive, succeed, and the response got lost on the way back? From the client's side, these look identical. Retrying is the obvious response, and in the second case, it charges the customer twice.
Idempotency keys solve this. They're the reason you can safely retry requests to well-designed payment APIs, and they're worth adding to any endpoint where doing something twice is a problem: creating orders, sending emails, transferring money, provisioning resources, or triggering expensive jobs. This guide explains how they work, how to implement them correctly (including the concurrency edge cases that naive versions miss), and how they fit with retries, queues and webhooks.
Idempotency in plain terms
An operation is idempotent if doing it several times has the same effect as doing it once. Setting a user's email to a specific address is idempotent: do it twice and the result is the same. Adding $50 to a balance is not: do it twice and the balance is $100 higher.
HTTP already defines some methods as idempotent by design: GET, PUT and DELETE should have the same effect no matter how many times they're repeated. POST, which is typically used to create things, is not. Idempotency keys are a way to make specific POST (and PATCH) requests safe to retry, by letting the server recognise a repeat.
Idempotency keys step by step
The client generates a unique key for each logical operation (each attempt to create one payment, say) and sends it in a header. The server uses that key to remember what it did.
POST /v1/payments HTTP/1.1
Content-Type: application/json
Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324
{ "amount": 5000, "currency": "usd", "customer": "cus_123" }
Stripe's API is the best-known example. Its documentation on idempotent requests describes the behaviour: Stripe saves the status code and body of the first request made with a given key, whether it succeeded or failed, and returns that same result for subsequent requests with the same key. Keys can be up to 255 characters, a V4 UUID or another random string with enough entropy is suggested, and keys can be removed after they're at least 24 hours old. If a request reuses a key with different parameters, Stripe returns an error, to protect against accidental misuse.
There's also a standards effort. The IETF HTTP API working group's draft, "The Idempotency-Key HTTP Header Field," describes the same header and suggests response codes for the main error cases, such as 422 when a key is reused with a different payload and 409 when a request arrives while the original with the same key is still being processed. It's still a draft, but it's a sensible reference for your own API's behaviour.
The client side: generate once, reuse on retry
The single most important client rule: generate the key once per logical operation, before the first attempt, and reuse it for every retry of that operation. A new key per attempt defeats the whole mechanism, because the server sees each retry as a brand new request.
import { randomUUID } from "node:crypto";
export async function createPayment(input: PaymentInput) {
const idempotencyKey = randomUUID(); // once, outside the retry loop
return withRetries(() =>
fetch("https://api.example.com/v1/payments", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey, // same key on every attempt
},
body: JSON.stringify(input),
}),
);
}
For operations that span a user's session, such as a checkout page, generate the key when the page loads or when the order is created in a draft state, and keep it until the operation completes. If the user double-clicks "Pay," both clicks send the same key, and only one payment happens. If the browser crashes and the user returns, a key stored with the draft order lets the retry be recognised too.
When the server reports an error, the client has to decide whether to retry with the same key or start a new operation with a new key. A retry with the same key is right for network errors, timeouts and server errors. If the request failed validation, fix the input and use a new key, since it's now a different operation. The retry rules (which errors to retry, backoff with jitter, limits) are the same as for any API; the guide on handling API rate limits and retries covers them in detail.
The server side: a correct implementation
A naive implementation looks up the key, and if it isn't found, does the work and saves the result. That has a race: two requests with the same key arriving at nearly the same moment both see "not found," and both do the work. Double-clicks and aggressive client retries make this more common than you'd think. A correct implementation claims the key atomically before doing anything.
The storage
CREATE TABLE idempotency_keys (
key text NOT NULL,
scope text NOT NULL, -- e.g. the account or API key that sent it
request_hash text NOT NULL, -- fingerprint of method, path and body
status text NOT NULL, -- 'processing' | 'completed'
response_code int,
response_body jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (scope, key)
);
Keys are scoped per client (per account or API key), so two customers who happen to generate the same key can't collide or, worse, see each other's responses. The request hash lets you detect the same key being reused for a different request.
The flow
- Claim the key. Insert a row with status
processing. If the insert succeeds, this request owns the operation. UseINSERT … ON CONFLICT DO NOTHING(or catch the unique violation) so the database's constraint, not application code, decides who wins. - If the key already exists, inspect it. If the request hash differs, reject with 422: same key, different request. If the status is
processing, another request is still working on it; return 409 so the client retries a little later. If it'scompleted, return the stored response code and body. - Do the work. Process the operation.
- Save the result. Update the row with the response code and body and set the status to
completed.
export async function handleIdempotent(
scope: string,
key: string,
requestHash: string,
work: () => Promise<{ status: number; body: unknown }>,
) {
const claimed = await db.query(
`INSERT INTO idempotency_keys (scope, key, request_hash, status)
VALUES ($1, $2, $3, 'processing')
ON CONFLICT (scope, key) DO NOTHING
RETURNING key`,
[scope, key, requestHash],
);
if (claimed.rowCount === 0) {
const { rows } = await db.query(
`SELECT request_hash, status, response_code, response_body
FROM idempotency_keys WHERE scope = $1 AND key = $2`,
[scope, key],
);
const existing = rows[0];
if (existing.request_hash !== requestHash) {
return { status: 422, body: { error: "Idempotency key reused with a different request" } };
}
if (existing.status === "processing") {
return { status: 409, body: { error: "A request with this key is still in progress" } };
}
return { status: existing.response_code, body: existing.response_body };
}
const result = await work();
await db.query(
`UPDATE idempotency_keys
SET status = 'completed', response_code = $3, response_body = $4
WHERE scope = $1 AND key = $2`,
[scope, key, result.status, JSON.stringify(result.body)],
);
return result;
}
Making the work and the record agree
The code above has one remaining gap: if the server crashes after doing the work but before saving the result, the key stays in processing forever, and the work might have happened. How you close that gap depends on what the work is.
- If the work is local database writes, do them in the same transaction as the update that marks the key completed. Either both commit or neither does, and a crash leaves no half-finished state. This is the cleanest case.
- If the work calls another service, pass an idempotency key to that service too, derived from yours. Then, if your server crashes and the operation is retried, the downstream call is also safe to repeat. Payment providers support this precisely so you can chain safely.
- For keys stuck in
processing, record when the claim was made, and let a later retry take over a claim older than a timeout, re-running the work (which is safe if the steps above are in place) or checking the downstream system for the outcome.
Some teams model the work as a series of recovery points: claim the key, create a local record, call the external service with a derived key, mark complete. Each step is safe to repeat, and a retry resumes from wherever the previous attempt stopped.
Design details that matter
Defining "the same request"
The request hash should cover what defines the operation: usually the method, the path and the body. Normalise the body first (for example, parse and re-serialise JSON with sorted keys) so that harmless differences in whitespace or key order don't trigger false mismatches. Don't include headers that legitimately change between retries, such as tracing IDs or timestamps.
Deciding which responses to store
Store successful responses and errors caused by the request itself, such as a card being declined, so retries get the same answer. Don't store errors that happened before the operation really started, such as a failed authentication check or a rate-limit rejection; for those, release the key (or never claim it), so a corrected retry can proceed. Stripe, for example, doesn't save a result when a request fails validation or conflicts with another request that's running at the same time.
Key retention
Keys must live longer than any plausible retry window. Stripe's 24-hour minimum is a reasonable baseline for most APIs. Delete expired keys with a scheduled job, and document the expiry so clients know that reusing a very old key starts a new operation.
Required or optional
For endpoints where duplicates are costly (payments, transfers, orders), consider requiring the header and rejecting requests without it with a clear 400 error. For others, accept it optionally. Either way, document the behaviour, including the error codes for mismatches and in-progress conflicts.
Idempotency beyond HTTP APIs
The same idea, recognising a repeat and doing the work once, shows up all over distributed systems.
- Webhook consumers. Webhook providers deliver events at least once, so the same event can arrive more than once. Store each event's ID when you process it, and skip IDs you've seen. Most providers include a unique event ID for exactly this reason.
- Queue workers. Most queues offer at-least-once delivery: a message can be delivered again if a worker crashes or takes too long to acknowledge it. Make each job idempotent, often by keying it on a business identifier, such as "send welcome email for user 42," and recording completion. The guide to background jobs on serverless platforms covers this in the context of job runners.
- Natural keys. Sometimes the data provides the key. A unique constraint on
(order_id, line_number)or on an external transaction ID makes duplicate inserts fail harmlessly, which is idempotency enforced by the schema. - AI agents with tools. An agent that retries a tool call after a timeout can trigger the same action twice. Tools that create or send things should accept an idempotency key that stays the same across retries of one intended action. The guide to designing tools for AI agents discusses making tools safe to retry.
Testing idempotency
Idempotency bugs appear under concurrency and failure, so test those conditions directly:
- Send the same request twice in sequence and assert one side effect and identical responses.
- Send the same request many times concurrently and assert exactly one side effect, with the others receiving 409 or the stored response.
- Reuse a key with a different body and assert a 422-style error.
- Simulate a crash between doing the work and saving the result, then retry, and confirm the outcome is correct.
- Check that keys from different clients don't collide.
- Confirm that expired keys are cleaned up and that reusing one starts a new operation.
Common mistakes
- Generating a new key per attempt on the client, which makes retries look like new requests.
- Check-then-act on the server without an atomic claim, which lets concurrent duplicates through.
- Global key namespaces, where one client's key can collide with another's.
- Ignoring payload mismatches, so a reused key silently returns the result of a different operation.
- Storing transient failures, so a retry after a temporary problem keeps replaying the error.
- Expiring keys too soon, before slow clients have finished retrying.
- Forgetting downstream calls, so your endpoint is idempotent but the payment provider call inside it isn't.
Retrofitting idempotency into an existing API
Adding idempotency keys to an API that's already in use can be done without breaking existing clients, because the header is opt-in at first.
- Start with the riskiest endpoints: payments, transfers, order creation and anything that sends messages to customers.
- Accept the header optionally. Requests without it behave exactly as before; requests with it get the new guarantees.
- Update your own clients first, including your web and mobile apps and any internal services, so they generate and reuse keys correctly.
- Document it with examples, the expiry period and the error codes for mismatched payloads and in-progress requests.
- Watch the data. The number of requests that hit an existing key tells you how often duplicates were happening before, which is often a surprise and a useful argument for the work.
- Consider making it required for the riskiest endpoints in a future API version, with plenty of notice for integrators.
Logging replayed responses separately from fresh ones also helps support teams: when a customer says "I clicked pay twice," you can see exactly what happened and show that they were charged once.
Idempotency, PUT and natural upserts
Idempotency keys aren't the only way to make an operation safe to repeat, and sometimes they're not the simplest. If you can design an endpoint so that the operation itself is idempotent, you don't need a key at all.
The classic technique is to let the client choose the identifier. Instead of POST /orders, where the server assigns a new ID each time, the client generates the order ID and sends PUT /orders/{id}. A PUT to the same URL with the same body creates the order the first time and changes nothing the second time, because it's describing the desired state of one specific resource rather than asking for a new one. In the database, that becomes an upsert keyed on the client-supplied ID, or an insert that ignores a duplicate key.
This works well for resources whose final state is fully described by the request: user profiles, settings, documents, records synchronised from another system. It works less well for operations that are actions rather than states, such as "charge this card" or "send this email," where there's a side effect beyond the stored record. Those are exactly the cases where idempotency keys earn their place.
Another pattern is the conditional request. HTTP's If-Match header with an ETag lets a client say "apply this update only if the resource hasn't changed since I read it." A retry of an update that already succeeded fails the condition harmlessly, rather than applying twice. This protects against lost updates from concurrent editors as well as from retries, which makes it a good fit for collaborative editing and admin tools.
In practice, well-designed APIs mix these approaches: client-chosen IDs and PUT for state, conditional requests for concurrent edits, and idempotency keys for actions with external side effects. Choosing the right one per endpoint keeps the implementation simpler than applying one mechanism everywhere.
Idempotency keys in client SDKs
If you publish an SDK for your API, build idempotency into it so integrators get it right by default. A good SDK generates a key automatically for each call to a state-changing method, reuses that key across its own internal retries, and lets callers pass their own key when they need to retry across process restarts or deduplicate at a higher level, such as one key per order in their own database.
Expose the key in errors and logs as well. When an integrator contacts support about a possible duplicate, being able to quote the idempotency key lets your team find the exact request, see whether it was replayed, and confirm what happened. That turns a stressful conversation about double charges into a quick lookup.
Finally, document the edge cases plainly: what happens when a key is reused after expiry, what the in-progress conflict response looks like, and which endpoints accept keys. Integrators can only rely on guarantees they know about.
Performance and storage costs
An idempotency table adds a write to every state-changing request, so it's worth keeping it lean. Index it by scope and key (the primary key above does this), store response bodies compactly, and avoid saving very large responses; for endpoints that return big payloads, store a reference to the created resource and rebuild the response on replay instead. Expire rows on schedule so the table doesn't grow forever. For very high-traffic APIs, some teams keep keys in a fast key-value store with a time-to-live, but the atomic claim and the agreement between the work and the record still need the same care, so don't trade correctness for a small speed gain.
Frequently asked questions
What is an idempotency key?
An idempotency key is a unique value, often a random UUID, that a client sends with a request that changes state. The server uses it to recognise retries of the same operation, performing the work only once and returning the stored result for repeat requests with the same key.
How do idempotency keys prevent duplicate payments?
The client generates one key per payment attempt and reuses it on every retry. The server records the key and the result of the first request, so if a timeout causes the client to retry, the server returns the original result instead of charging the card again.
Who should generate the idempotency key, client or server?
The client. Only the client knows when two requests are retries of the same intended operation, so it must generate the key before the first attempt and send the same key on every retry. The server scopes keys per client and stores the result.
What should happen if the same key is sent with a different request body?
The server should reject it with an error rather than returning the stored result. The IETF draft for the Idempotency-Key header suggests 422 for a reused key with a different payload, and Stripe returns an error when parameters don't match the original request.
How long should idempotency keys be stored?
Longer than any realistic retry window. Twenty-four hours is a common baseline; Stripe states that keys can be removed after they are at least 24 hours old. Document the expiry period and clean up old keys with a scheduled job.
The takeaway
Retries are unavoidable, and without idempotency, retries create duplicates. An idempotency key lets the client say "this is the same operation as before" and lets the server answer "I already did that, here's the result." Generate the key once per operation on the client, claim it atomically on the server, check the payload matches, store the result, and extend the same guarantee to the services you call. It's a small amount of code that turns timeouts from a source of double charges into a non-event.
Author at LuminaryEra
The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.
View all articles





