download

How does an API handle retried POSTs with an Idempotency-Key?

Backend~12 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. What goes wrong when the client reuses k1 with a different amount ({"amt": 900} instead of {"amt": 500}), or when two identical retries arrive at the same millisecond?
  2. Update post_charge to scope keys by user and hash the payload with SHA-256. Replay the stored (status, body) on a match, return 422 on a mismatch, and return 409 while the first call is still running.
  3. How do you make the initial key claim safe across multiple app servers?
"CODE · PYTHON"
SEEN = {}


def post_charge(key, body, run_charge):
    if key in SEEN:
        return SEEN[key]
    res = (201, run_charge(body))
    SEEN[key] = res
    return res
Show hints (3)
  1. "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.

  2. "BLOCK CONCURRENT RETRIES"

    Reserve (user, key) in an in_progress state before running run_charge. A second request arriving mid-flight gets 409 Conflict instead of double-charging.

  3. "CLAIM IN DATABASE"

    Across multiple servers, enforce a composite UNIQUE (user_id, key) constraint and insert atomically with ON 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.

"SOLUTION · PYTHON"
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}))
"OUTPUT"
(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:

SituationStored stateHTTP responseSide effect
First call with k1, {"amt": 500}Claimed in_progress, then done201 + ch_1Charged once
Retry k1, {"amt": 500}done, hash matches201 + ch_1 (replay)None
Retry k1, {"amt": 900}Hash mismatch422 (or 409)None
Concurrent k1, {"amt": 500}in_progress, hash matches409 ConflictNone

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:

"SQL"
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 201 response without comparing a payload hash. A caller who accidentally reuses an old key for a new amount thinks the new charge succeeded.
  • Checking SELECT before INSERT across 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 key risks collisions and cross-user response leaks.
  • Caching a transient 503 timeout 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_until lease timestamp on the in_progress row. 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/422 validation 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 →

Original OfferVibe question. RFC 9110 Idempotent Methods · MDN Idempotent · PostgreSQL INSERT ON CONFLICT · SQLite UPSERT.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.