Idempotency: The Machinery

The Idempotency: the contract part was the contract a client programs against. This part is how that contract is implemented and why the implementation is forced into this exact shape — a request that spans your database and a card network can't use a single ACID transaction, because those two systems will never share one (see What a payment is).

Why "Check, Then Act" Is Broken

The naive idempotency implementation is one SELECT followed by one branch: look the key up, and if it's not there, do the work. That's broken for two independent reasons, and both matter:

The race. Two requests carrying the same key can reach the "does this key exist" check before either has written anything. Both see "no." Both proceed. Both charge the card. The check and the act are not atomic with each other, so the check buys you nothing under concurrency — which is exactly the situation a client retrying after a timeout creates: the original request may still be in flight at the exact moment the retry lands.

The work itself isn't transactional. Even with the race fixed, "do the work" here means "write to your own database and call the card network." Those are two separate systems. You cannot wrap both in one COMMIT — there is no distributed transaction manager spanning your Postgres instance and Visa's network (see What a payment is). So even a correctly-serialized check-then-act still leaves a window where your local write has happened but the foreign call hasn't, or vice versa, and a crash in that window needs a real recovery story, not just "don't race."

The interleaving that produces a double charge under naive check-then-act
The interleaving that produces a double charge under naive check-then-act

Atomic Phases and Recovery Points

The fix in the published design is to stop treating "handle the request" as one step and instead split it into atomic phases, separated at every point where a foreign state mutation happens — a card network call, an email send, anything outside your own database. Each phase's local effects commit in a single local transaction, together with an advance of a recovery_point column on the idempotency-key row. A crash can only ever lose you the phase currently in flight; everything before the last committed recovery point is durable and never re-executed.

The row that makes this possible, from the reference design (illustrative shape, not a confirmed Stripe production schema — see the callout above):

CREATE TABLE idempotency_keys (
    idempotency_key TEXT NOT NULL
        CHECK (char_length(idempotency_key) <= 255),
    locked_at       TIMESTAMPTZ DEFAULT now(),
    recovery_point  TEXT NOT NULL,          -- 'started' | 'ride_created' | 'charge_created' | 'finished'
    response_code   INT  NULL,
    response_body   JSONB NULL,
    user_id         BIGINT NOT NULL
);

CREATE UNIQUE INDEX idempotency_keys_user_id_key
    ON idempotency_keys (user_id, idempotency_key);   -- the per-account scoping from §1, enforced here

Walk a ride-charge request through it (the example from the reference design, generalized):

  1. Recovery point: started. Before any other work, insert the idempotency-key row itself — key, locked_at = now(), recovery_point = 'started' — in its own transaction. This row is both the record of intent and the lock (next section).
  2. Recovery point: ride_created. Local-only work: create the "ride" record, compute the amount. Commit this together with advancing recovery_point to ride_created in the same local transaction. No foreign system has been touched yet, so this phase is trivially safe to redo from scratch on retry.
  3. Foreign mutation: call the card network. Charge the card, passing Stripe its own idempotency key derived from your local key row's id (e.g. "rocket-rides-atomic-#{key.id}") — so if this exact call is retried, Stripe's own idempotency layer (see Idempotency: the contract) protects you a second time, independently of your local lock.
  4. Recovery point: charge_created. The instant the network call returns, commit the charge id locally and advance recovery_point. If the process dies after the network call succeeds but before this commit, a retry resumes here — it does not re-call the network from scratch, it re-derives the same Stripe idempotency key, so even a "duplicate" foreign call is caught by Stripe's own layer.
  5. Recovery point: finished. Cache the final response code and body on the row, commit. Every subsequent request with this key now falls through to "already finished," and returns the cached response without re-executing anything.
Recovery points for one idempotency key, as a state machine
Recovery points for one idempotency key, as a state machine

A retry that arrives after a crash doesn't restart from started — it reads the row's current recovery_point and jumps straight to the phase after it. That's the entire trick: durability comes from a sequence of small local ACID transactions, each of which either fully happens or fully doesn't, chained together by a recovery cursor that only a foreign call is allowed to sit in front of.

The Key Row As a Lock — What Happens On a Simultaneous Collision

This is the reader's first question, precisely: two API calls with the same idempotency key arrive at essentially the same instant. What happens?

The idempotency-key row is created and locked first, before any other work — that insert is itself the arbiter. Under the reference design's isolation guarantees, if two transactions both try to acquire the same key row, the database aborts one of them. The request that loses gets neither a duplicate charge nor a silent wait nor a half-built object back — it gets an explicit, immediate answer: 409 Conflict. Stripe's own public API reference lists exactly this status for exactly this cause: "409 · Conflict · The request conflicts with another request (perhaps due to using the same idempotent key)."

Two requests, one key, one winner
Two requests, one key, one winner

The client-side consequence is the sharper half of this answer. 409 here does not mean "give up" — it means "the other attempt at this exact operation is still running; you may not need to do anything at all." The correct client policy is: back off briefly (a few hundred ms, then retry, matching a normal exponential-backoff schedule) and retry with the identical key and body — not a new key, not a different operation. Doing that either returns the now-finished result of the request that won the race, or (rarely) another 409 if it's still running, or lets you become the new lock-holder if the original request has actually died (next section).

Locks Must Expire

A key row locked forever by a process that crashed mid-request would permanently wedge that one key — every future retry (including the client's own legitimate one) would get 409 forever, with no path forward. The published design handles this with a lock-timeout: a key is only treated as "actively locked" while locked_at is more recent than some fixed window (the reference implementation's own constant, illustrative rather than a Stripe-production number); past that window, a new request is allowed to steal the lock and resume from whatever recovery_point was last committed, exactly as if it were a normal retry. That window is a real tradeoff, not a free parameter: too short, and two merely-slow (not crashed) requests can both believe they've acquired the lock, recreating the original race; too long, and a single crashed worker can stall an otherwise-healthy retry for uncomfortably long.

The reference design names three background processes that keep this whole mechanism honest without waiting on a client to trigger recovery:

EnqueuerMoves committed staged-job rows into the real queue (next section)
CompleterFinds keys stuck mid-phase past the lock timeout and finishes them on the client's behalf
ReaperDeletes old key rows (illustrative retention: ~72h) so the table doesn't grow unbounded

The reaper's retention window and Stripe's own documented key-retention floor (see Idempotency: the contract: "at least 24 hours") are conceptually the same idea at two different layers — one is how long the client-facing replay contract holds, the other is how long the implementation keeps the row around internally — and there's no requirement they be numerically identical; the client-facing promise only needs to be a lower bound on the internal one.

Why This Isn't Two-Phase Commit

Two-phase commitRecovery-point pattern
CoordinatorA dedicated component all participants trustNone — each phase's own local transaction is the only coordinator
Participant requirementEvery system must implement prepare/commit/abortNone — the foreign system only needs a plain request/response API
Failure modeA participant can block the whole transaction indefinitelyA crash loses at most one in-flight phase; retry resumes from the last committed recovery point
What's actually atomicThe whole distributed transaction, in principleOnly each local phase; the foreign call itself is never rolled back, only compensated (see Sagas and compensation)

There is no prepare phase, no coordinator, and no participant voting — nothing here asks the card network "can you commit?" before deciding to proceed, because the network has no such API and never will. What actually buys the durability is much cheaper than 2PC: a single local ACID transaction that atomically records "I am about to attempt X" (the recovery-point advance immediately before a foreign call) and, separately, another local transaction that records "X returned Y" immediately after. Two-phase commit across all of a system's foreign dependencies is theoretically possible but essentially never built in practice, because it requires every counterparty to speak the same distributed-transaction protocol — the card network doesn't, your email provider doesn't, nothing outside your own database does. The recovery-point pattern sidesteps the requirement entirely: it accepts that the foreign call itself cannot be transactional, and makes only the bookkeeping around it transactional, on both sides. Forward-reference: this is precisely the same trade the Sagas and compensation part makes at a larger scale with sagas and compensating transactions — no cross-system lock, only local transactions plus a recorded intent that a recovery process can act on.

Background Jobs Have To Be Idempotent Too — The Transactional Outbox

The same "your database and the outside world don't share a transaction" problem recurs the moment a request needs to trigger a side effect — send a receipt email, decrement inventory, notify a fulfillment queue. Enqueue that job by calling the job system directly from inside the request, and you've reintroduced exactly the bug idempotency keys exist to prevent, just for a background job instead of a charge: enqueue before the surrounding local transaction commits, and a rollback after that point leaves a job queued for work that, as far as your database is concerned, never happened.

The fix Stripe's published design uses — a genuinely reusable pattern worth naming precisely — is a transactional outbox (the article's own term is a transactionally-staged job drain): instead of calling the job system directly, insert a row describing the job into a plain table in your own database, in the same local transaction as the business write it's conditioned on. A separate process — an enqueuer — polls that table and only pushes rows into the real job queue after they're visible, which by definition means their transaction committed. If the transaction rolls back, the staged-job row never existed and nothing is ever enqueued. If the transaction commits, the row is guaranteed visible and the enqueuer will eventually find it — a job is never lost for a transaction that committed, and never fired for one that didn't.

Transactional outbox: the job can't outlive a rollback or outrun a commit
Transactional outbox: the job can't outlive a rollback or outrun a commit

Three Tools That Look Similar and Protect Different Things

MechanismWhat it actually protectsWhere it fails
Idempotency key (this part)One logical POST, replayed any number of times within the retention window, executes its foreign effect at most onceOnce the key is pruned (see Idempotency: the contract); doesn't protect two different keys that both happen to represent the same real-world operation
Consumer-side deduplication (see Webhooks)A message-delivery layer (webhooks, a queue) that redelivers the same event, processed once by the receiverOnly as good as the dedup window/store the consumer keeps; a redelivery outside that window, or a consumer restart that loses its dedup state, reprocesses
Database unique constraintThe absolute last line of defense at the storage layer — two rows that must not both exist, enforced even if every layer above this one has a bugCatches the write, but not the foreign side effect that may have already fired before the constraint violation surfaced (exactly the receipt-email trap above)

None of these three substitutes for either of the others — a resilient payment path layers all three, because each one is the backstop for a different failure mode the others don't cover.

The Invariants

  • Guarantees: A request arriving while an identical key is in flight gets an immediate, explicit 409 rather than blocking, duplicating, or reading a half-committed object; a crash mid-request loses at most the single atomic phase in flight, never work already past a committed recovery point; a background job staged in the same transaction as its triggering write is never enqueued for a rollback and never lost for a commit.
  • Does not guarantee: That every real Stripe production detail matches this published pattern exactly — it's the documented design, not a leaked org chart; that a client treating 409 as terminal will behave correctly; or that a lock-expiry window is ever "correct" in both directions at once — it's a tuned tradeoff between false contention and stalled recovery, not a solved problem.