Scrivio Interview library
ConceptFoundations6 min read · updated 13 November 2026

An idempotency key is a unique value a client sends with a non-idempotent request, such as POST, so the server can recognise a retry. The details of how the server treats the key decide whether retries are really safe.

What should the server do when the same key arrives again with the same body, with a different body, and while the first request is still running? What exactly does it store?

For a repeated key with the same request, the server returns the stored status and body of the first attempt without running the operation again. For the same key with a different body, it rejects the request, usually with 422, by comparing a stored hash of the canonical request. For a key whose first attempt is still running, it returns 409 Conflict, optionally with Retry-After. Per key it stores the client it belongs to, the request hash, the state, the response and an expiry such as 24 hours, and the client must reuse one key for every retry of one logical operation.

Why this question is asked

Networks fail in the worst possible place: after the server has done the work but before the client sees the response. The client cannot tell whether the payment or order was created, so it retries, and without protection the operation happens twice. Idempotency keys are the standard answer, and interviewers ask about them because the idea is easy to state and the details are easy to get wrong. In this answer, we will recap what idempotency means, then walk through the three cases the question names, look at exactly what the server stores and why, and finish with the client's side of the contract.

1A Quick Recap of Idempotency

An operation is idempotent when doing it twice has the same effect as doing it once. HTTP defines GET, PUT and DELETE as idempotent: setting a field to 5 twice leaves it at 5. POST is not: 'create a payment of 50 dollars' twice creates two payments.

An idempotency key turns a POST into something safe to retry. The client generates a unique value, typically a UUID, for one logical operation and sends it in a header such as Idempotency-Key. The server remembers the key and what happened, so when the same key arrives again it can recognise the retry. The interesting part is what 'recognise' means in each situation.

2Case 1: The Same Key With the Same Body

This is the normal retry. The first attempt succeeded, the response was lost, and the client sends the identical request again. The server looks up the key, sees that it completed, and returns the stored response: the same status code and the same body, for example 201 Created with the payment id. It does not run the operation again.

Notice that the server replays the original response rather than computing a new one. If it returned, say, 200 with the current state of the payment, the client might treat the retry differently from the first attempt. Replaying makes the retry indistinguishable from the original, which is exactly what the client needs.

3Case 2: The Same Key With a Different Body

Here the client has reused a key for a different operation, for example a key for a 50 dollar payment sent again with 80 dollars. This is a client bug. If the server replayed the stored response, the client would believe the 80 dollar payment exists; if it ran the new request, the key would no longer protect anything.

So the server rejects it, typically with 422 Unprocessable Content and an error code such as idempotency_key_reused. To detect it, the server stores a hash, for example SHA-256, of the canonical request: method, path and body with keys in a fixed order, so that harmless differences such as whitespace do not count. On every retry it compares the new hash with the stored one.

4Case 3: The Same Key While the First Attempt Is Still Running

A client times out after 10 seconds and retries while the first attempt is still talking to a slow payment provider. The server must not start a second execution, and it should not block the retry indefinitely while waiting. The usual answer is 409 Conflict with an error code such as request_in_progress, optionally with Retry-After: 2, telling the client to come back shortly. By then the first attempt has usually finished, and the retry gets the stored response.

Detecting this safely needs an atomic step. The first attempt must claim the key before doing any work, by inserting a record in state IN_PROGRESS with a unique constraint on the key. A second attempt's insert fails on the constraint, so it reads the record and sees IN_PROGRESS. A 'read, then insert if missing' check would let two attempts arriving within milliseconds both see nothing and both run.

Step throughHandling a request with Idempotency-Key
  1. Insert key as IN_PROGRESS (unique)atomic claim, scoped to the client
  2. Insert succeeded?
    YesRun the operation, store response, mark COMPLETEDNoRead the existing record
  3. Stored request hash matches?
    YesCheck the stateNoReturn 422: key reused for another request
  4. State is COMPLETED?
    YesReplay stored status and bodyNoReturn 409 with Retry-After

4 steps in order. Play them, or step through them one at a time.

5What the Server Stores per Key

Each record holds a small set of fields, and each one has a reason. The key itself, together with the client or account it belongs to, because keys are scoped per client: two customers who happen to generate the same value must not see each other's responses. The request hash, for case 2. The state, IN_PROGRESS or COMPLETED, for case 3. The response, status and body, for case 1. Timestamps and an expiry, because keys only need to outlive the retry window; 24 hours is a common choice, after which the record is removed.

SQL
CREATE TABLE idempotency_key (
client_id text NOT NULL,
key text NOT NULL,
request_hash bytea NOT NULL, -- SHA-256 of method, path, canonical body
state text NOT NULL, -- IN_PROGRESS or COMPLETED
status_code int, -- 201
response_body jsonb, -- {"id": "pay_81", ...}
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL, -- created_at + 24 hours
PRIMARY KEY (client_id, key)
);

The primary key on (client_id, key) is what makes the claim in case 3 atomic and what scopes keys per client.

6The Client's Half of the Contract

All of this only works if the client creates one key per logical operation and reuses it on every retry of that operation. The key should be generated when the user confirms the action, stored with the pending operation, and sent again on each retry, including after an app restart. A common mistake is to generate a fresh UUID for every HTTP attempt, for example in a generic interceptor. Then every retry looks like a new operation to the server, and the whole mechanism silently does nothing.

7Follow-up questions

Should a 500 response be stored and replayed for the same key?

It depends on whether the operation could have had an effect. If the server failed before doing anything, for example validation crashed, it is better to delete or release the record so the client's retry runs again; replaying a 500 forever would turn a temporary failure into a permanent one. If the failure happened after a side effect may have occurred, such as a timeout from the payment provider, the server must not simply rerun it; it should record the uncertain state and resolve it (for example by asking the provider with the same key) before answering. Many APIs replay 4xx results and successful results, and treat 5xx as retryable.

Why 409 and not just wait for the first attempt to finish?

Waiting holds a thread and a connection on the server for an unknown time, and under load a burst of retries would pile up waiting. Returning 409 quickly with Retry-After keeps the server responsive and leaves the timing to the client.

How long should keys live?

Long enough to cover every realistic retry, including a mobile app that retries after being offline for a while. 24 hours is common; payment APIs sometimes keep them longer. Keeping them forever only adds storage cost.

8Conclusion

In this answer, we saw that an idempotency key lets a server recognise retries of a non-idempotent request. A repeat with the same body gets the stored response replayed, a repeat with a different body is rejected with 422 by comparing request hashes, and a repeat while the first attempt runs gets 409 with Retry-After. The server stores the owner, the request hash, the state, the response and an expiry, claims the key atomically, and relies on the client to reuse one key for all retries of one operation.

What to say in the interviewAbout 90 seconds aloud

Open with

An idempotency key is a unique value the client sends with a POST so the server can recognise a retry. There are three cases. If the same key comes back with the same request and the first attempt completed, I return the stored response, the same status and body, without running the operation again.

Then, if they want more

If the same key comes back with a different body, that is a client bug, so I reject it, usually with 422, and I detect it by storing a hash of the canonical request and comparing. If the first attempt is still running, I return 409 Conflict, maybe with Retry-After, instead of running it twice or blocking.

To make that safe under races, the first attempt claims the key by inserting a row in state IN_PROGRESS with a unique constraint, so a concurrent attempt fails the insert rather than both passing a read-then-write check.

Per key I store the client or account it belongs to, because keys are scoped per client, the request hash, the state, the stored status and body once it completes, and an expiry, typically around 24 hours.

And I would stress the client's side: it must create one key per logical operation, when the user confirms, and reuse it on every retry, even after an app restart. If it generates a fresh key per HTTP attempt, the whole mechanism silently does nothing.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What should the server do when the same key arrives again with the same body, with a...": https://scrivio-interview-library.netlify.app/architecture/api-design-at-scale/084674f246/