What is an idempotency key and why should a frontend send one?
IntermediateNetworking and HTTP interview questionBy UIRound, updated 23 November 2026
Short answer
An idempotency key is a unique id the client sends with a non-idempotent request, usually in an Idempotency-Key header on a POST. The server records the result for that key, and if the same key arrives again it returns the stored result instead of doing the work twice. The frontend generates the key once per user action and reuses it on every retry, so a timeout, a double click or a flaky network cannot place two orders.
Why a frontend needs it
A request that fails does not tell you whether the server did the work. Consider a payment:
- The user clicks Pay. The browser sends
POST /payments. - The server charges the card and writes the payment.
- The response is lost: the mobile connection drops, a proxy times out, or your
AbortSignal.timeoutfires first.
The client now sees an error. If it retries, or the user clicks again, a plain POST charges the card a second time. If it does not retry, a payment that did fail stays failed and the user gives up. Without help from the server, the client cannot do the right thing.
The same applies to anything that creates something or has side effects: orders, bookings, transfers, sending a message, submitting a form that triggers an email. GET, PUT and DELETE are idempotent by definition, so retrying them is already safe. POST and usually PATCH are not. See how a frontend should retry failed requests for which failures are worth retrying at all.
How it works
POST /payments HTTP/1.1
Content-Type: application/json
Idempotency-Key: "3f6c1d2e-8b4a-4f7e-9c1d-2a5b6e7f8091"
{ "orderId": "ord_812", "amount": 4999, "currency": "INR" }On the server, roughly:
- Look up the key, scoped to the user or account.
- Not seen: store it as in progress, together with a fingerprint of the request body, then do the work and store the response status and body against the key.
- Seen and finished: return the stored response. Do not run the work again.
- Seen and still in progress: a concurrent duplicate. Reject it so the client retries later.
- Seen with a different body: a client bug. Reject it rather than guess.
The Idempotency-Key header is being standardised in an IETF draft from the HTTPAPI working group, which is still an Internet-Draft, not an RFC. It defines the value as a Structured Field string, hence the quotes above, and suggests 400 when a required key is missing, 409 Conflict while the first request is still being processed, and 422 Unprocessable Content when a key is reused with a different payload. It leaves expiry to each API, which should publish its own policy.
Stripe's API is the best-known implementation, and the draft credits its documentation. Stripe takes the key as a bare value without quotes, so match whatever your API documents. It accepts an Idempotency-Key on every POST, takes keys up to 255 characters, and suggests random V4 UUIDs. For its v1 API, the first response for a key, including a 500, is replayed on retries, keys can be pruned once they are at least 24 hours old, and reusing a key with different parameters returns an error.
Generate the key per user action, not per request
This is the part interviews probe. The key identifies the intent: "this user placing this order once". It must stay the same across every attempt to fulfil that intent, and change when the intent changes.
function createSubmitter<T>(url: string) {
let key: string | null = null;
return {
// Call when the user edits the form: a different payload is a new action.
reset() {
key = null;
},
async submit(body: T): Promise<Response> {
key ??= crypto.randomUUID(); // first attempt creates it, retries reuse it
const response = await fetchWithRetry(url, {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": `"${key}"` },
body: JSON.stringify(body),
});
if (response.ok) key = null; // done: the next submission is a new action
return response;
},
};
}(fetchWithRetry retries network errors, timeouts and 503s with backoff, sending the same headers each time.)
Rules that follow from "one key per action":
- Same key on automatic retries, and on a manual Try again after an ambiguous failure such as a timeout or network error.
- New key when the payload changes. If the user edits the cart and pays again, it is a new action. Reusing the old key gets a
422or, worse, the old result. - New key after a definitive result. Success, or an error that means the request was rejected and nothing happened, ends the action.
- Survive reloads when it matters. If the tab crashes during payment and the user returns, the retry should carry the original key. Store it with the draft in
sessionStorageor IndexedDB, and keep it in each queued item of an offline outbox. - Never derive it from personal data. Do not use an email or phone number as the key. A random UUID from
crypto.randomUUID()(available in secure contexts) is enough.
Disabling the button is not enough
Disable the submit button while a request is in flight; it stops the common double click and gives feedback, as in a LoadingButton that blocks double submits. It does not cover:
- Two tabs submitting the same checkout.
- A retry library, service worker or offline queue resending after a lost response.
- A user who reloads and submits again because the first attempt looked stuck.
- Clicks that land before the disabled state renders.
The client-side guard prevents most duplicates; the server-side key makes the rest harmless. A good design uses both.
Frontend details that come up
- CORS.
Idempotency-Keyis not a CORS-safelisted request header, so a cross-origin request with it triggers a preflight, and the server must list it inAccess-Control-Allow-Headers. - Showing the result. A replayed response looks exactly like the original, so the UI does not need a special case: show the confirmation. Some APIs add a header to mark a replay, which is useful in logs.
- Ambiguous final failures. If every retry fails, do not tell the user "payment failed" when you do not know. Say the status is being checked, and poll a status endpoint for the order, which is how UPI payment flows handle it.
- Know what your API replays. If it stores error responses too, as Stripe's v1 API does for a
500, retrying with the same key returns the same error. Decide with the backend when a new attempt deserves a new key. - Not just payments. Comments, chat messages and form submissions benefit too. Chat apps often send a client-generated message id that doubles as the idempotency key and as the key for matching the optimistic message to the server's copy.
Practise the full flow in a fault-tolerant checkout with idempotent submission, and see it in a larger design in an internet banking app with idempotent transfers.
Follow-up questions interviewers ask
Is an idempotency key the same as request deduplication on the client?
No. Client deduplication shares one in-flight promise for identical GETs inside one page. An idempotency key is enforced by the server, across tabs, devices, reloads and retries, and is meant for writes.
Why not let the server dedupe by comparing the request body?
Two identical bodies can be two genuine actions: the same coffee ordered twice on purpose. Only the client knows whether a second request is a retry or a new intent, and the key is how it says so.
How long should the server keep keys?
Long enough to cover every realistic retry, including offline queues and users returning to a tab. The draft leaves the policy to each API; Stripe's v1 API, for example, may prune keys after 24 hours. The client should not rely on a key working after that.
Where should the key be generated, on the client or the server?
On the client, because it must exist before the first attempt is sent, and that attempt is the one whose response may be lost. A server can hand out a token when the checkout page loads, which works the same way, as long as the same value is reused for every attempt.
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Build a fault-tolerant React checkout flow with idempotent submission, recovery, and persistent stateHard75 min
- Build a
LoadingButtonthat keeps its width, blocks double submits and stays accessibleMedium35 min - Design an internet banking web app: fund transfers with OTP, idempotency, session timeouts, security headers and accessibilityHard60 min
- Design UPI payments on the web like PhonePe or Paytm: intent, collect and QR flows, status polling, retries and double-payment safetyHard60 min
- Implement retry with exponential backoff and jitterMedium40 minFree
- Design Amazon/Flipkart checkout: pricing, cart synchronization, payments, and failure recoveryHard60 min