53 // journal

Idempotency keys: retry a payment five times, charge once

engineering · 2026-11 · 7 min read · engineering · payments · api

journal/idempotency-keys
Idempotency keys: retry a payment five times, charge once

fig.01 · same key, same params: replayed, not re-executed

The phone loses signal between "pay" and the response. The server charged the card; the app saw a timeout. Your retry logic does the honest thing and sends the request again, and now the customer owns two charges and a support ticket. HTTP already solved this for the idempotent methods: a GET or DELETE can be retried forever because repeating it changes nothing beyond the first application. POST has no such promise, so every payment API had to invent one. The invention is a string the client makes up and the server remembers: the idempotency key.

The constraint

A retry is only dangerous when the server cannot tell it apart from a new request. On a dropped connection the client cannot know whether the request arrived, executed, or died mid-write. What the client needs is a name for the operation that survives the retry, so "did this run?" stops being a guess and becomes a lookup. The constraint on that name: it must be generated by the client (the server cannot help you identify a request it never saw), unique to the operation (reusing it for a different operation must fail loudly, not silently), and cheap to store, because the server keeps one per operation for as long as retries are plausible.

The options

Dedupe after the fact. Charge twice, detect the duplicate in reconciliation, refund one. This is a cleanup strategy, not a fix: the customer sees the double charge before you do, and refunds take days where the charge took seconds.

Unique constraint on a business ID. Your own API can require order_id to be unique and reject a second insert. This works inside your schema and is worth having anyway, but it does not travel: your payment provider does not index on your order ID, and it cannot help a client retrying a call to an API you do not control.

Button discipline. Disable "pay" after the first tap. Covers exactly one failure (an impatient user) out of several (timeout, crash, process restart, background retry job). Keep it; it is not the mechanism.

Client-generated idempotency key. The client invents a token per operation, sends it in a header, and the server stores the first response under that key. Retries with the same key get the stored response back instead of a re-execution. This is what Stripe, Adyen, and the IETF's in-progress standard all converged on.

The mechanism

The contract has three branches, and a working implementation is about twenty lines. The model below stores key -> {params, response} and mimics what a payment endpoint does with it; the branch labels come from the IETF draft's error semantics. Run it with node idempotent.mjs:

// what a payment endpoint does with an Idempotency-Key
const keys = new Map(); // key -> { params, response }
let ledger = 0;         // charges actually executed

function pay(key, params) {
  const seen = keys.get(key);
  if (seen) {
    if (seen.params !== params) return "422 key reused with different params";
    return `200 ${seen.response} (replayed)`;
  }
  const response = `ch_${++ledger} for ${params}`;
  keys.set(key, { params, response });
  return `201 ${response}`;
}

const key = crypto.randomUUID();          // one key per operation
console.log(pay(key, "amount=2500"));     // first attempt
console.log(pay(key, "amount=2500"));     // retry after a timeout
console.log(pay(key, "amount=2500"));     // user mashes pay again
console.log(pay(key, "amount=9000"));     // same key, a different purchase
console.log(`ledger: ${ledger} charge(s)`);
201 ch_1 for amount=2500
200 ch_1 for amount=2500 (replayed)
200 ch_1 for amount=2500 (replayed)
422 key reused with different params
ledger: 1 charge(s)

Four requests, one charge. The draft formalizes the branches: a missing key gets a 400 ("Idempotency-Key is missing"), a key retried while the original is still executing gets a 409 ("A request is outstanding for this Idempotency-Key"), and a key reused with a different payload gets a 422. It also lets the server store a request fingerprint (a checksum or field match) alongside the key so "same key, different body" is detected rather than replayed.

Two details worth knowing are missing from the draft entirely. There is no standardized replay indicator: Stripe marks replayed responses with an Idempotent-Replayed: true header, but the working group declined to standardize one as out of scope. And the draft sets no expiry: the resource "SHOULD define such expiration policy and publish it," which is why the windows below differ by provider.

Where it bites

The window ends. On Stripe's v1 API, "Stripe retains keys for at least 24 hours and can remove them after that. Reusing a key after it's removed can execute a new request." The retry that worked at hour 3 is a brand-new operation at hour 30. Their guidance bounds retries of an unresolved operation to the first 24 hours; past that you stop and reconcile. API v2 widened the window to 30 days and changed the semantics: retries "don't repeat successful operations" but re-execute failed work rather than replaying the error. Adyen's window is 7 to 14 days, keys are scoped to the company account, and "idempotency keys will not be checked for duplication in other regions," so multi-region integrations dedupe per region or not at all.

Cached errors replay too. Stripe v1 caches the response "after the API method begins execution, including errors," so a retry of a 400 or 500 returns the same error, not a fresh attempt. If the operation needs different parameters, that is a different operation: it gets a new key. Meanwhile errors before execution begins (bad parameters, invalid API key, rate limiting) are never cached, so they are safe to retry as-is. The subtle one is the indeterminate 500: the operation "might have produced side effects even though you received an error," so Stripe's advice is to reconcile via webhooks or the object itself before retrying with a new key, or you are back to charging twice by a slower route.

Concurrency is a real case. A retry that arrives while the original still runs gets a 409, not a replay. The fix is wait-and-retry with the same key; minting a new key there starts a second operation.

Your own API is the harder version. Implementing the server side means atomic check-and-store under concurrency (a unique index on the key column, not a read-then-write), response storage for the key's whole window, and fingerprint comparison on every hit. It is a small feature with a distributed-systems tail; if your API takes payments, the alternative is that every client implements dedupe with refunds.

The numbers

  • Stripe v1: keys retained "at least 24 hours," up to 255 characters, POST only (GET/DELETE are idempotent already). Replayed responses carry Idempotent-Replayed: true.
  • Stripe v2: 30-day replay window scoped to the same account or sandbox and the same API; POST and DELETE both accept keys; a missing key gets an auto-generated UUID.
  • Adyen: 7 to 14 days, 64 characters max, company-account scope, no cross-region deduplication.
  • IETF Idempotency-Key draft: still an Internet-Draft as of November 2026, not an RFC; the value is a quoted Structured Field string, and a UUID is the recommended key format.

Our position

For money, bookings, or any write the user pays for, idempotency keys are the floor, not a feature. Generate the key once per operation and persist it with the operation's local record, so a process restart retries with the same key instead of inventing a new operation; Stripe's own docs suggest deriving it from a user-attached object like a cart ID, which gives you that property for free. Bound retries to the provider's documented window, never reuse a key across different parameters, and treat 5xx as "outcome unknown, reconcile first" rather than "try again harder." And if you are the API, the same discipline is yours: receivers that cannot survive duplicate delivery have the same bug one layer down, which is where webhook handlers live.

The takeaway

KEY
client-generated, one per operation; uuid or derive
from a stable id (cart/order id); persist it locally
RETRY
same key + same params replays the first result;
never reuse a key with different params (422/400)
WINDOW
stripe v1: 24h. stripe v2: 30d. adyen: 7-14d.
past the window a retry is a new operation
CONFLICT
retry while the original runs returns 409:
wait and retry; a new key starts a second operation
ERRORS
post-execution errors get cached and replayed;
5xx is indeterminate: reconcile before retrying
SCOPE
keys dedupe per account (adyen: per region too);
get/delete are already idempotent (v2 delete

still accepts keys); get sends nothing

Payments and checkout flows are where we apply this pattern in our product engineering work, including the storefront sync behind Grain and Vine, and the server-side half (atomic storage, fingerprint checks, expiry) is the same receiver-discipline problem as idempotent webhooks. If your checkout can charge twice, send us the flow.

// next step

We work this way on client projects too.

Tell us what you are making. We reply with a plan, a timeline, and a price.

← the journal