How does an API handle retried POSTs with an Idempotency-Key?
Question
A mobile client retries POST /v1/charges after a network timeout, sending header Idempotency-Key: k1. The starter handler caches responses by key in a dictionary.
- What goes wrong when the client reuses
k1with a different amount ({"amt": 900}instead of{"amt": 500}), or when two identical retries arrive at the same millisecond? - Update
post_chargeto scope keys by user and hash the payload with SHA-256. Replay the stored(status, body)on a match, return422on a mismatch, and return409while the first call is still running. - How do you make the initial key claim safe across multiple app servers?
SEEN = {}
def post_charge(key, body, run_charge):
if key in SEEN:
return SEEN[key]
res = (201, run_charge(body))
SEEN[key] = res
return resShow hints (3)
- "HASH THE REQUEST"
Compute a canonical JSON SHA-256 digest of
body(sort_keys=True). Compare it against the saved digest whenever(user, key)already exists. - "BLOCK CONCURRENT RETRIES"
Reserve
(user, key)in anin_progressstate before runningrun_charge. A second request arriving mid-flight gets409 Conflictinstead of double-charging. - "CLAIM IN DATABASE"
Across multiple servers, enforce a composite
UNIQUE (user_id, key)constraint and insert atomically withON CONFLICT DO NOTHING.
Show checked explanation
Scope every Idempotency-Key to the authenticated user and store a SHA-256 hash of the canonical request payload. Claim (user_id, key) atomically in the database as in_progress before charging. On a retry, return 422 if the payload hash differs, 409 if still running, or replay the exact saved HTTP status and body.
import hashlib import json store, ids = {}, iter(("ch_1", "ch_2")) # prod: DB table + ID generator def post_charge(user, key, body, run_charge): fp = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() if (user, key) in store: old_fp, code, res = store[(user, key)] if old_fp != fp: return 422, {"error": "payload mismatch"} return (code, res) if code else (409, {"error": "in progress"}) store[(user, key)] = (fp, 0, None) # atomic DB UNIQUE claim in prod store[(user, key)] = (fp, 201, run_charge(body)) return 201, store[(user, key)][2] for b in ({"amt": 500}, {"amt": 500}, {"amt": 900}): print(post_charge("u1", "k1", b, lambda x: {"id": next(ids), **x}))
(201, {'id': 'ch_1', 'amt': 500})
(201, {'id': 'ch_1', 'amt': 500})
(422, {'error': 'payload mismatch'})Ran the starter and fixed handler on CPython 3.12.10, plus a two-thread SQLite 3.49 ON CONFLICT race test in a temporary directory. Checked by an editor other than the author.
Walkthrough
POST is not idempotent in RFC 9110, so repeating a timed-out POST /v1/charges normally bills the card twice. An Idempotency-Key header makes retries safe, but only if the handler handles all four outcomes:
| Situation | Stored state | HTTP response | Side effect |
|---|---|---|---|
First call with k1, {"amt": 500} | Claimed in_progress, then done | 201 + ch_1 | Charged once |
Retry k1, {"amt": 500} | done, hash matches | 201 + ch_1 (replay) | None |
Retry k1, {"amt": 900} | Hash mismatch | 422 (or 409) | None |
Concurrent k1, {"amt": 500} | in_progress, hash matches | 409 Conflict | None |
Why fingerprint the payload. The starter returns ch_1 (500) even when a buggy client reuses k1 to charge 900. Hashing canonical JSON (sort_keys=True) catches parameter reuse right away while staying insensitive to JSON key order.
Why scope keys by user. Storing keys globally lets user u2 collide with u1's key or even read u1's saved response body. Always key on (user_id, idempotency_key).
Atomic multi-server claim. A check-then-write dictionary fails when two requests hit different servers at once. Move the lock into PostgreSQL or SQLite with a UNIQUE (user_id, key) constraint:
INSERT INTO idempotency_keys (user_id, key, payload_hash, state) VALUES (?, ?, ?, 'in_progress') ON CONFLICT (user_id, key) DO NOTHING;
Exactly one request gets rowcount == 1 and executes the charge. Every concurrent twin gets rowcount == 0, reads the existing row, and returns 409 Conflict (with a short Retry-After) until the winner commits the stored status and body.
Common mistakes
- Replaying the cached
201response without comparing a payload hash. A caller who accidentally reuses an old key for a new amount thinks the new charge succeeded. - Checking
SELECTbeforeINSERTacross multiple app servers. Two simultaneous retries both see no row and charge the customer twice. - Sharing idempotency keys across tenants or users. Scoping only by
keyrisks collisions and cross-user response leaks. - Caching a transient
503timeout response forever. Release or delete the key on pre-execution transient errors so a later retry can actually succeed.
Follow-up questions
- "What if the server crashes while the row is stuck in in_progress?" Store a
locked_untillease timestamp on thein_progressrow. If the server crashes before talking to the payment gateway, an expired lease can be reclaimed. If an external charge may already have fired, reconcile with the gateway using the same idempotency key before retrying. - "How long should you retain stored idempotency keys?" Match your client retry window, commonly 24 hours to 7 days, then purge expired rows with a background cleanup job. Storing keys forever bloats indexes, while expiring them in 10 seconds breaks slow mobile retries.
- "Should you store and replay 4xx client validation errors under the key?" Usually no for malformed
400/422validation errors, because the caller must fix the body and resubmit. Persist deterministic outcomes once the request passes validation and enters the write transaction.
What a strong answer covers
Scopes keys to (user_id, key), hashes canonical payloads to reject mismatched reuse with 422, and claims keys atomically via UNIQUE + ON CONFLICT DO NOTHING so concurrent retries return 409 instead of double-charging.
Open in interactive practice deck →