Lesson 4 of 14 · 20m
Idempotency Keys: How Retried POSTs Stop Double-Charging
The Idempotency-Key contract: one key per logical operation, stored responses replayed byte-for-byte, and dedupe inside the transaction.
A mobile client calls POST /v1/payments. The request reaches your server, the charge succeeds, and the response dies in a tunnel. The client sees a timeout and retries — correctly, because a timeout means "I don't know what happened," not "it failed." You charge the customer twice. Nothing in this chain misbehaved, and that is the point: POST is not idempotent, and the network is indistinguishable from success-then-silence. Retries are guaranteed by every HTTP client ever written; deduplication is your problem.
The Idempotency-Key contract
The pattern Stripe made standard: the client generates a unique key per logical operation — a UUID per attempted payment, not per HTTP attempt — and sends it as Idempotency-Key. The server stores the key alongside the result. A replayed key gets the stored response back, byte-for-byte, without the handler running again.
POST /v1/payments
Idempotency-Key: 9d3e2a1c-7f44-4a9e-9d0f-2b8e5c1a6f30Scope the key to the authenticated account — keys are only unique per caller, and you don't want account A's key suppressing account B's legitimate payment. Stripe prunes keys after 24 hours; a shorter TTL than that, and a legitimately slow retry loop (think a flaky CI job with hourly retries) falls off the table and double-runs anyway.
The three replay cases
- First request completed: return the stored response — status, body, everything, including if it was a 4xx. A stored failure is still the answer to that operation.
- First request still in flight: do not run the handler twice concurrently. Either block the second request until the first settles, or return
409 Conflictwith aRetry-After. Stripe chose the conflict route. - Same key, different body: that's a client bug, not a retry — return a 4xx (a
problem+jsonunprocessable-entity) rather than silently serving the first result.
Put the dedupe in the transaction
The check-then-insert pattern has a TOCTOU hole: two same-key requests interleave, both see "no key stored," both charge. The durable version is a unique constraint — UNIQUE (account_id, idempotency_key) — inserted in the same transaction as the work, so the database itself arbitrates the race. The second transaction fails on the constraint, rolls back its side effects, and you look up the winner's stored response.
Idempotency beyond the header
GET, PUT, and DELETE are already idempotent by spec — a retried PUT /v1/users/7 lands on the same state. PATCH is the murky one: it's safe if your updates are absolute ({"status": "archived"}), dangerous if they're relative ({"balance_delta": -500} — a retry double-applies). Ban relative mutations on network-facing resources, or treat PATCH like POST and require the key. And the backup control lives in your data model regardless: a UNIQUE constraint on (order_id, charge) means the retry that slips past everything still can't double-write.
Client side, document the inverse rule: retries reuse the same key, with exponential backoff and jitter. A client that generates a fresh key per attempt defeats the mechanism entirely — and that's a bug you'll find in their code, not yours, but it becomes your incident either way.
Try this
Implement Idempotency-Key on POST /v1/payments: the table, the unique constraint, the three replay branches, the response store. Then fire the same request twice concurrently and a third time with a different body. If any two of the three produce two charges, you built a cache, not idempotency.
Pitfalls
- Key-per-attempt clients: a new UUID on every retry is a dedupe mechanism that dedupes nothing.
- Scoped wrong: keys unique globally (one user's key blocks another's) or not scoped to account at all.
- Caching only successes: the stored 4xx is still the response to that operation.
- Dedupe before the transaction: check-then-insert races; let the constraint decide.
PATCHwith relative mutations:{balance_delta: -500}is two withdrawals on a retry.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Building a Production REST API With Node.js and Express
Build a REST API in Node.js and Express the way production systems need: input validation, JWT auth, refresh token rotation, status codes, rate limiting, idempotency keys, and centralized error handling.
GraphQL Over HTTP Is Finally a Spec. Your Server Probably Still Says 200.
The GraphQL over HTTP specification shipped its first edition on November 12, ending the decade of '200 Not OK.' Validation errors get 422, partial results get a new 294 status, and a dedicated media type tells clients the body is safe to parse.
Strings Are Lying to You: Unicode Length, Case and Normalization in PHP, Python and JavaScript
One family emoji is 18 bytes, 8 JavaScript code units, 5 Python characters and 1 thing a human sees. I ran the same Unicode tests through PHP 8.6, Python 3.15 and Node 26: each gave a different answer for length, case and truncation, a KELVIN SIGN lowercases into a real username, and PHP 8.6's...
PHP and WordPress Patched a Day Apart. Your Front End Decides Which PHP Bugs Reach You.
PHP 8.5.13, 8.4.28, 8.3.37 and 8.2.36 fix 18 CVEs, seven rated 9.2, and WordPress 7.1.5 fixes 20 more issues. Most of the PHP bugs only fire under specific settings, so I checked the official Docker images for each condition. The images were patched the same day, and the patch quietly turns off...