Card 03/ 06

ConceptDifficulty: Intermediate2 min

Idempotency Key Rules: Scope, Expiry and a Different Body

A key belongs to one client and one operation, lasts a limited time, and must not be reused for a different request.

An idempotency key needs three rules to be safe: it is scoped to one client, so two clients that pick the same value do not share results; it expires after a stated window, so the server need not store every key forever; and it is bound to the request it first arrived with, so reusing it for a different request is refused rather than answered with the wrong result.

Each misuse of a key, what the server detects, and the response it sends
MisuseWhat the server detectsResponse
The same key with a different bodyThe stored request fingerprint differs from this one422 Unprocessable Content
The same key while the first request is still runningThe key is recorded as in progress409 Conflict
No key on an endpoint that requires oneThe header is missing400 Bad Request
The same key after the window has passedNothing; the key is unknownTreated as a new request

Scope. The server stores keys per client, typically per API key or account, so the lookup is client and key together. Without that, one client could receive another's stored response by guessing or reusing its key.

Expiry. Keys are kept for a window long enough to cover every realistic retry, commonly 24 hours. The API documents it, because a client that retries a day later with the same key gets a second operation.

Fingerprint. With the key the server stores a fingerprint of the request, usually a hash of the method, path and body. A retry must match it. A client that reuses the key for a different amount has a bug, and silently returning the first payment's result would hide that.

What gets stored. The status and body of the final response, including a failure the client caused, such as a 400. A retry of a request that was refused for an invalid card gets the same refusal. A failure on the server's side, such as a crash before completion, should leave the key free so the retry can run.

The codes. 422 and 409 for misuse come from the IETF Idempotency-Key draft rather than a published RFC, and may change before it becomes one. Document whichever codes the API sends.

So store the key per client, with a fingerprint and an expiry, and record it before the work starts.