404human Experience Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

Stripe-style idempotency keys: stopping double charges under retries

How Stripe-style idempotency keys prevent double charges on mobile networks and retries: key scoping, payload hash checks, concurrent in-flight locks, and edge cases.

Published
Read time
5 min read
Kind
guide
Topics

A user taps Pay $49.00 on subway Wi-Fi. Your server charges the card, writes the ledger entry, and tries to send back 200 OK—right as the train enters a tunnel. The mobile app sees a network timeout, retries the POST /payments call automatically, and charges the customer $49.00 twice.

Networks do not offer “exactly-once” HTTP delivery. Retries are guaranteed to happen—from mobile SDKs, load balancers, browser refreshes, and background workers. Stripe-style idempotency keys are the industry-standard contract that makes retries completely safe for payments, refunds, ledger transfers, and order creation.

While building our Payment Sandbox (double-entry PostgreSQL ledger + two-phase payments + hosted checkout), an independent review even caught a subtle interaction between conflict handling, retries, and restore paths that could double-charge if not guarded atomically (the fixes had bugs too). Here is the exact state machine that closes every loophole.

The Stripe-style idempotency contract

The client generates one unique key (e.g., UUIDv4) per logical user intent—not per HTTP attempt—and sends it in the Idempotency-Key header on every retry of that intent:

POST /v1/payments HTTP/1.1
Authorization: Bearer sk_live_...
Idempotency-Key: 9f4c2b8e-3a7d-4e92-b1c0-7a1d5e8f2c34
Content-Type: application/json

{"amount_cents": 4900, "currency": "USD", "customer_id": "cus_123"}

When the server receives that request, there are four possible outcomes—not two:

Server state for (tenant_id, idempotency_key)Request payload hash matches?Exact HTTP response
1. Key never seen beforeN/AClaim key atomically (in_progress), execute payment, store response, return result
2. Key already completedYesReplay the exact original HTTP status & body (with Idempotent-Replayed: true) — zero side effects
3. Key already completed or in_progressNo (mismatch!)Return 422 Unprocessable Entity (idempotency_key_payload_mismatch) — never silently replay!
4. Key currently in_progress (concurrent retry)YesReturn 409 Conflict (request_in_progress, with Retry-After: 1) so the client retries cleanly once the first attempt finishes

Why naive “check then insert” still double-charges

The classic broken implementation runs SELECT * FROM idempotency_keys WHERE key = $1, sees zero rows, charges the card, and then runs INSERT INTO idempotency_keys.

If two retries arrive 5 milliseconds apart (very common when a user double-taps or a proxy retries aggressively), both SELECT queries see zero rows and both charge the card!

The atomic PostgreSQL state machine

Scope the primary key by (tenant_id, method, route, idempotency_key) so two tenants can never collide, and let PostgreSQL’s UNIQUE constraint + INSERT ... ON CONFLICT DO NOTHING decide the single winner atomically (for the full schema and cleanup queries, see idempotency keys in PostgreSQL):

CREATE TABLE idempotency_keys (
  tenant_id       UUID        NOT NULL,
  idempotency_key TEXT        NOT NULL,
  request_hash    BYTEA       NOT NULL, -- SHA-256 of method + path + canonical body
  status          TEXT        NOT NULL CHECK (status IN ('in_progress', 'completed', 'failed_retryable')),
  response_status INTEGER,
  response_body   JSONB,
  locked_until    TIMESTAMPTZ NOT NULL,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, idempotency_key)
);

Claim the key in one atomic statement:

INSERT INTO idempotency_keys (
  tenant_id, idempotency_key, request_hash, status, locked_until
)
VALUES ($1, $2, $3, 'in_progress', now() + interval '60 seconds')
ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
RETURNING idempotency_key;
  • If 1 row returned: You own the key exclusively. Proceed to execute the payment/ledger write, then update status = 'completed', response_status, and response_body inside the same database transaction as your local ledger write!
  • If 0 rows returned: Read the existing row:
    • If request_hash != $3 → immediately return 422.
    • If status = 'completed' → return the stored response_status and response_body.
    • If status = 'in_progress' and locked_until > now() → return 409 Conflict (Retry-After: 1).

Three real edge cases that break payment APIs

1. Which errors should be cached vs. retried?

Never cache a transient 500 Internal Server Error or 503 Service Unavailable as a permanent completed result—otherwise a 2-second database hiccup poisons that checkout key forever.

  • Validation / client errors (400, 422 before side effects): Safe to delete or leave uncached (or store only deterministic business rejections like card_declined).
  • Transient server/network errors (500, 502, 503 before upstream charge confirmed): Mark failed_retryable or release the lock so the client’s retry can actually succeed.
  • Ambiguous crash after calling an external payment processor: Pass the same idempotency key downstream to Stripe/your processor! Then retrying is safe end-to-end across both your database and the processor.

2. Crash recovery when a worker dies mid-in_progress

Suppose a server claims status = 'in_progress' and gets kill -9’d before updating the row. Without a lease timeout (locked_until), that key stays stuck in 409 Conflict forever!

  • If no external side effect happened yet (local-only transaction), rolling back the Postgres transaction clears the claim automatically.
  • If an external API call happened outside the DB transaction, only reclaim an expired in_progress row (locked_until <= now()) by querying the downstream processor with the same downstream idempotency key—never blindly firing a brand-new unkeyed charge!

3. Restores, webhooks, and double-entry guardrails

Never rely on the HTTP idempotency table as your only defense against double-charging. Pair it with:

  • A UNIQUE constraint on (payment_id, event_type) in your immutable ledger table (see double-entry accounting enforced by PostgreSQL triggers).
  • A concurrency test that fires 10 parallel POST /payments requests with the exact same Idempotency-Key and asserts that exactly 1 ledger debit row exists afterward.

Frequently asked questions

What is a Stripe-style idempotency key? An idempotency key is a unique client-generated token (usually a UUIDv4 sent in an Idempotency-Key HTTP header) attached to a mutating request like POST /charges. If the network drops and the client retries the exact same request with the same key, the server returns the original stored result instead of charging the customer a second time.

What should happen if a client reuses the same idempotency key with a different amount or payload? Reject the request immediately with HTTP 422 (Unprocessable Entity) or 409 (Conflict). Always store a SHA-256 hash of the canonical request parameters alongside the idempotency key so an accidental key reuse with a different dollar amount can never silently replay the wrong receipt.

How long should you keep idempotency keys? Stripe retains idempotency keys for at least 24 hours; many payment and order APIs retain them for 24 to 72 hours (or longer for asynchronous webhook/batch jobs). After pruning, the same key is treated as a fresh request—so clients should always generate a brand-new key per distinct user checkout attempt.

Related reading