Skip to content

Idempotency Keys: How Northwind Stopped Double-Charging Customers

13 min reading

Bind retries to operation meaning and protect the authoritative business effect.

Page details

Design for failure · Lesson 10

Published · Sources · 13 min reading · Last edited:

Know first: When Things Fail: Timeouts, Retries, and Availability Math.

Editorial correction:

Earlier design notes used unsupported universal performance or reliability claims. This revision explains conditional mechanisms and explicitly hypothetical examples; no author-run benchmark or production incident is asserted.

More
20px

In short. Give one intended charge one durable identity. Repeated attempts inspect and advance its recorded state instead of starting another charge.

A separate seen check leaves a race

A process checks whether an operation identifier exists, finds nothing and begins the reservation. Another process performs the same check before the first records completion. Both can now create effects. The existence of a deduplication table does not close the gap between checking it and changing the business state.

Recording the identifier after the effect leaves a crash window. Recording it before the effect and treating every record as completed can suppress work that never happened. The record therefore needs meaningful states, and its transition must be coordinated with the effect it represents.

A local memory cache cannot establish this property across independent workers or restarts. A shared cache may still have expiry, consistency or failure behavior that does not match the durable business operation. Choose the mechanism from the required effect boundary rather than from the convenience of a fast lookup.

Bind the operation to its meaning

A useful request contract carries a stable operation identifier scoped to the authenticated actor and operation type. The service binds that identity to the intended parameters. Reusing an identity for a materially different request should produce a conflict, not silently return the first request's result.

One operation identity across repeated attemptsMultiple attempts enter one authorization and identity boundary. A transaction records the operation result with the reservation effect. A repeated attempt returns the same logical result or a declared in-progress state.Repeated attemptssame intentionAuthorize + bind identityEffect + result recordCommitted resultor explicit pendingRetry reads the logical operation's state.

When the business effect and operation record share a database, a suitable transaction and uniqueness constraint can establish one accepted transition. Concurrent attempts must resolve the same identity under the selected isolation behavior. The loser then reads the recorded result or a declared pending state instead of creating another effect.

PostgreSQL's isolation documentation is a concrete reminder to inspect concurrency semantics rather than assume that any transaction prevents every anomaly. The application design here also requires the chosen uniqueness constraint and atomic update boundaries; isolation alone is not the whole protocol.

A Postgres record governs the next attempt

Northwind chooses Postgres for its durable operation record. The authenticated customer, action type and key identify the logical operation. A request fingerprint binds that identity to the amount, currency, order and other material parameters. A unique insertion claims the key atomically; two workers cannot both acquire an absent record by doing separate reads. The claim includes a lease expiry and a generation used to reject obsolete writers.

Hypothetical Northwind recovery contract; these are application states, not Stripe internals
Observed statePermitted transitionResponse or recovery
AbsentUnique insert → PROCESSINGPersist key, fingerprint, lease expiry and attempt generation before the external call.
PROCESSING, live leaseKeep the same ownerReturn in-progress status or wait within the caller’s deadline; another worker does not send another charge.
PROCESSING, expired leaseReconcile, then guarded takeover if safeQuery the provider using the same operation identity. Expiry alone does not prove the previous charge failed.
Confirmed successPROCESSING → COMPLETEDStore provider reference and the response; return the recorded result on later matching attempts.
Confirmed retryable failurePROCESSING → FAILED_RETRYABLE → PROCESSINGRetain the error and fingerprint. A guarded retry is permitted only when evidence and the provider contract establish safety.
Same key, different fingerprintRejectKeep the original operation unchanged; a deliberate new purchase needs a deliberate new identity.

The owner commits a completion only when the record still carries its current generation. That prevents a paused worker from publishing an obsolete local result after another worker takes over. A generation check in Postgres protects local state; the provider’s own idempotency or reconciliation contract protects the external effect. Both boundaries are needed when a worker can pause during a remote call.

A definite business rejection is not automatically retryable. Preserve its final result rather than spinning through FAILED_RETRYABLE. If a failure is ambiguous, retain uncertainty in PROCESSING or an explicit unresolved work record until reconciliation supplies evidence. A nullable response column is not a state machine: a retry must inspect the state before attempting to read a completed response.

Keep completed records for at least 24 hours in this application design, and longer when the supported client retry window requires it. Scope retention together with provider key expiry and durable business uniqueness. If the provider can no longer recognize an old identity, a fresh request is a new risk decision, not transparent recovery. Expired uncertain work stays visible for investigation instead of being deleted with ordinary cache entries.

Count attempts, effects and retained identities

Hypothetical scenario. Choose 1,000 logical reservation requests. Eighty each receive one additional attempt after an uncertain response. The transport handles 1,000 + 80 = 1,080 attempts. If all requests are accepted and the effect boundary enforces the stated identity contract, the intended number of reservations remains 1,000.

The difference is 80 avoided extra effects under these assumptions, not 80 avoided network requests. The service still authorizes, looks up state and returns a result for retries. Resource planning must account for attempts even when the business effect is safely deduplicated.

For retention, choose 10,000 new operation records per day, seven days of supported retries and 300 bytes of logical record payload. The retained count is 10,000 × 7 = 70,000; payload is 70,000 × 300 = 21,000,000 bytes, or 21 MB using decimal units. Indexes, replica copies, storage allocation and larger result bodies are excluded.

If clients can retry after eight days but records expire after seven, the service has a one-day interval outside the promised deduplication coverage. It must reject expired identities, retain durable business uniqueness or state a narrower supported retry contract. Simply deleting the record cannot preserve an unlimited promise.

Now choose an external provider call that succeeds, followed by a crash before the local success record. Retrying creates another effect unless the provider accepts the same operation identity or the application can reconcile the existing action. A local database transaction cannot atomically include an arbitrary external service.

Toy payment estimate. Choose 1,000,000 payment intents per day and a 0.1% timeout fraction. Then 1,000,000 × 0.001 = 1,000 calls end with an unknown response. Assume 30% of those had already committed at the provider: 1,000 × 0.30 = 300 committed-but-unconfirmed actions. Blindly retrying all unknown calls under new identities can therefore create about 300 duplicates per day under these assumptions. The remaining 700 did not commit in this model; the timeout count alone cannot tell the two groups apart.

Choose a retry deadline before choosing delay settings. Full-jitter exponential backoff draws a delay uniformly from zero to min(cap, base × 2^attempt), as described in AWS’s Exponential Backoff and Jitter. With hypothetical base 0.1 seconds, cap 1 second and attempt index 3, the upper bound is min(1, 0.1 × 8) = 0.8 seconds. A chosen draw of 0.3 seconds consumes that much of the remaining deadline. Jitter spreads load; only the operation contract makes another attempt safe.

In the wild: provider rules and recovery points

Stripe’s API v1 documentation says matching retries return the saved status and body, including 500 responses, after execution begins. It compares parameters and permits pruning keys once they are at least 24 hours old. Its API v2 behavior differs. Those are public API rules, not evidence about Stripe’s internal tables or locks.

Brandur Leach’s Postgres idempotency design illustrates local atomic phases and recovery points around foreign state changes. Its example is a reference application, not a Northwind incident. The useful lesson is to record progress before crossing an external effect boundary so a retry can resume from evidence instead of restarting every step.

Northwind’s FAILED_RETRYABLE state is its own policy. A cached provider 500 is not permission to create a replacement payment identity. Sam first checks the provider’s current object and supported retry behavior. If neither reveals whether the original effect exists, the operation remains unresolved and an authorized review decides the next action.

End-to-end effects cross local boundaries

For an external action, first establish what the provider promises about repeated identities, retention and parameter mismatch. Store enough request and result evidence to reconcile an uncertain outcome. A status query can help only if it identifies the same operation reliably; searching for a similar amount or timestamp is not equivalent.

An outbox coordinates the database change and intent to publish. It does not by itself make a downstream payment, email or shipment occur once. The recipient must handle repeated deliveries at its own effect boundary. This connects directly to the queue lesson's distinction between acceptance, processing and business completion.

Sometimes the appropriate operation is naturally state-setting rather than additive. Repeating “set the preferred locale to this value” can preserve the same intended state, while repeating “increment the credit balance” generally cannot. Concurrent legitimate changes still require an ordering or conditional update rule.

The key is reused for another purchase

Hypothetical scenario. A mobile client reuses its previous operation identifier for a different item. The server finds a completed operation and returns its receipt without comparing request meaning. The new purchase appears successful even though the receipt describes another action.

Bind identity to canonical operation parameters and reject incompatible reuse. Canonicalization itself must preserve distinctions that matter to the business, such as item identity, currency or quantity. Blindly hashing a raw serialization can also treat semantically identical representations as different operations.

Authorization remains necessary on every attempt. Scope records to the actor and tenant, prevent cross-tenant receipt lookup, and avoid exposing sensitive results through a guessed identifier. Deduplication is a correctness tool, not proof of permission. Audit records should identify who requested and authorized the action while limiting sensitive payload retention.

Avoid the once-only slogan

“The handler ran once.” It may run repeatedly while one transactionally protected effect is accepted. State which effect the contract covers.

“A new key makes a retry safe.” A new key generally represents a different operation to the deduplication mechanism. Preserve identity across attempts of the same intention.

“An HTTP method proves the application implementation is safe.” RFC 9110 defines method idempotency in terms of intended server effects. A method label does not repair a handler that violates its semantics or establish a separate business workflow's deduplication policy.

Use identity where uncertainty can repeat effects

Use explicit operation identity when callers may repeat an additive action after uncertainty. Declare scope, parameter binding, concurrent behavior, retention, pending states and recovery. Show callers how to distinguish an accepted operation from a completed downstream effect.

Do not turn every read into a durable operation record without a reason. Nor should an idempotency layer hide business conflicts: two different users can legitimately submit distinct operations that compete for the same inventory. The invariant still needs an atomic reservation decision.

The next lesson asks how to observe this flow. Metrics need to distinguish attempts from logical operations, and a trace that ends in timeout must not be treated as conclusive evidence that the effect failed.

Limits of the guarantee

This design relies on enforced uniqueness, guarded transitions and a provider contract that can identify the original effect. Lease timeouts, cache expiry and HTTP method names alone establish none of those properties. The arithmetic is hypothetical, and retained payload estimates exclude indexes and logs. Define what happens after the provider’s recognition window, during reconciliation outages and when an action cannot be safely retried.

Check yourself: locate the effect boundary

Two workers both find no previous identifier. What must the design add?

A coordinated uniqueness and effect transition at the authoritative store. Separate prechecks do not prevent concurrent creation. Define the losing attempt's pending or completed response as well.

A provider completed an action, but the local process crashed. Can a local deduplication table prove the action failed?

No. Reuse the provider's supported identity or reconcile the operation using reliable evidence. A missing local completion record leaves an uncertain external outcome.

A retry has the old key but changes quantity. Should the cached receipt be returned?

No. The identity no longer matches the same intended parameters. Reject conflicting reuse and require a deliberate new operation for a genuinely new action.

The lease expired while a worker was paused after sending a charge. Is a new charge safe?

No. Reconcile the original provider action first; acquire a new local generation only under a safe recovery transition.

A matching retry receives the same saved provider 500. Does FAILED_RETRYABLE permit a new key?

No. The application’s state names do not override provider semantics. Inspect the operation and preserve unresolved state until its effect is known.

Northwind decision log

Keep one action identity across uncertain attempts.

Persist the fingerprint and result with the operation identity.

Resolve a timed-out charge before creating another action.

Move the timeout across an uncertain action

Assume the response is lost. A retained provider-enforced key binds repeated delivery to one effect; a new key can create another. Earlier timeouts require reconciliation rather than a guessed outcome.

With a commit at 400 ms and timeout at 500 ms, the caller still has an unresolved action until confirmation. Reusing the enforced key preserves one effect.

Go deeper: retries, remote calls and recovery