Idempotency Keys
When to Use Idempotency Keys
In Practice
Idempotency-Key header. Server stores key → response for 24h; second request with the same key returns the cached response instead of re-running the work.How Idempotency Keys Comes Up in Interviews
Scenario
You're building a checkout flow. The client POSTs to /charge, the network drops mid-response, the client retries, and the user gets charged twice. Which technique prevents this without forcing the client to know whether the first call committed?
Idempotency keys let the client send a unique key per logical operation; the server dedupes against it so retries return the cached response instead of re-running the charge. Optimistic concurrency would help for conflicting writes but doesn't dedupe retries of the same operation.
Idempotency keys solve the 'I don't know if my last request committed' problem that's intrinsic to any non-idempotent mutation over an unreliable network. The server stores the key → response mapping for some window (Stripe keeps it for 24 hours), so a retry with the same key short-circuits to the cached response instead of re-running the charge. The subtle implementation detail is what the server does mid-flight: if a second request with the same key arrives while the first is still executing, you need a lock or a conflict response, otherwise you can double-charge despite the dedupe. Stripe's API returns a 409 in that case; most well-designed idempotency layers persist the key with a 'pending' state before doing the work.
Scenario
In a REST API, GET, PUT, and DELETE are idempotent: sending the same request twice leaves the server in the same state as sending it once. POST /orders creates a new order every time, so a mobile client that retries after a timeout can place the same order twice. What makes that POST safe to retry?
The client generates a unique key for each logical order and sends it in an Idempotency-Key header. The server stores the key with its response, and a retry carrying the same key gets the stored response back without creating a second order. Backoff only spaces retries out, and optimistic concurrency protects edits to an existing resource from conflicting writes, so neither one stops a duplicate create.
REST conventions interviewers expect: resources are plural nouns (/orders, /orders/42), the HTTP method carries the action, and the status code reports the outcome. GET reads and changes nothing, POST to a collection creates (201 Created with a Location header), PUT replaces the resource at a known URL, PATCH updates some of its fields, and DELETE removes it (often 204 No Content). GET, PUT, and DELETE are idempotent by definition, which is why clients and proxies can retry them safely. POST is not, and PATCH is not guaranteed to be, so a create that may be retried needs an idempotency key, and the server should keep each key at least as long as the client's retry window.