Part 3 · Blueprint 12
Idempotency Keys & Distributed Retries
15 min reading · Sources · Editorial review pending
A lost response cannot distinguish an unexecuted request from a completed effect.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: SQL vs. NoSQL vs. NewSQL Storage Engines, Message Queues & Event Streams: Kafka vs. RabbitMQ.
Sixty-second mental model
Problem: A lost response cannot distinguish an unexecuted request from a completed effect.
Use: Retain a stable identity and reconcile ambiguous completion.
Design boundary: Treat a logical operation and its attempts as different identities. Idempotency requires a stable key, request meaning, durable result and concurrency behavior; a tracing identifier by itself supplies none of those guarantees.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing idempotent retries. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one attempt means and which component owns the operation record.
Think of one claim ticket reused for repeated attempts. Separate the requester from operation record, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
- Exponential backoff
- Increasing retry delays multiplicatively according to a bounded policy. Analogy: Waiting progressively longer between repeat calls.
- Idempotency
- Repeated application of a defined operation having the same relevant effect as one application. Analogy: Submitting the same claim ticket again does not create another order.
- Idempotency key
- A stable request identity used to recognize repeated attempts of one operation. Analogy: A claim number shared by retries of the same order.
- Jitter
- Random variation in timing used to reduce synchronized behavior. Analogy: Staggering arrival times so everyone avoids the same rush.
- Retry
- Another attempt after a failure, timeout or retryable response. Analogy: Calling again after an uncertain conversation.
Architecture and worked reasoning
Design boundary: Treat a logical operation and its attempts as different identities. Idempotency requires a stable key, request meaning, durable result and concurrency behavior; a tracing identifier by itself supplies none of those guarantees.
Responsibilities on the request path
Workload and limiting resource
Hypothetical workload: 1,000 logical operations and 200 one-time retries produce 1,200 network attempts. Without deduplication, up to 1,200 effects could be attempted; a correct idempotency contract preserves 1,000 logical outcomes. If records are retained for 24 hours, the contract must explain a retry arriving after that window rather than silently promising indefinite deduplication.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Bind an operation key to the normalized request.
- Reserve or find that identity atomically.
- Commit its effect and recoverable outcome under a defined boundary.
Observation and recovery path
- On retry, compare request meaning.
- Return the recorded result or pending/unknown state.
- Retain identity at least as long as supported retries can arrive.
Failure that changes the decision
Hypothetical scenario: A provider accepts a transfer but its response is lost. A new key may create a second transfer; first recover or reconcile using the original identity and provider guarantees.
Attempt this decision before reading the explanation
What if two simultaneous requests reuse one key with different bodies?
Reject conflicting meaning rather than picking a convenient result. The registry must atomically bind the identity and ensure concurrent callers cannot both initiate distinct effects.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
In short. Give one intended charge one durable identity. Repeated attempts inspect and advance its recorded state instead of starting another charge.
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.
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.
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.
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.
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.
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.
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.
Layer 3 · Internals
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Database operation record | Can join identity and the protected mutation in one transaction. | Retention and contention belong to the primary storage budget. |
| Separate deduplication store | Can accelerate recognition for eligible repeated work. | It does not automatically commit atomically with an external effect. |
Recovery decision
Hypothetical scenario: A provider accepts a transfer but its response is lost. A new key may create a second transfer; first recover or reconcile using the original identity and provider guarantees.
Reject conflicting meaning rather than picking a convenient result. The registry must atomically bind the identity and ensure concurrent callers cannot both initiate distinct effects.
Write your design before revealing the review
What if two simultaneous requests reuse one key with different bodies?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
Reject conflicting meaning rather than picking a convenient result. The registry must atomically bind the identity and ensure concurrent callers cannot both initiate distinct effects.
A provider accepts a transfer but its response is lost. A new key may create a second transfer; first recover or reconcile using the original identity and provider guarantees.
Check your understanding
What if two simultaneous requests reuse one key with different bodies?
Reject conflicting meaning rather than picking a convenient result. The registry must atomically bind the identity and ensure concurrent callers cannot both initiate distinct effects.
How would you recover from this failure: A provider accepts a transfer but its response is lost. A new key may create a second transfer; first recover or reconcile using the original identity and provider guarantees.
Start with the exact boundary that failed. Bind an operation key to the normalized request. Reserve or find that identity atomically. Commit its effect and recoverable outcome under a defined boundary. Then recover evidence through the observation path: On retry, compare request meaning. Return the recorded result or pending/unknown state. Retain identity at least as long as supported retries can arrive. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical workload: 1,000 logical operations and 200 one-time retries produce 1,200 network attempts. Without deduplication, up to 1,200 effects could be attempted; a correct idempotency contract preserves 1,000 logical outcomes. If records are retained for 24 hours, the contract must explain a retry arriving after that window rather than silently promising indefinite deduplication. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Treat a logical operation and its attempts as different identities. Idempotency requires a stable key, request meaning, durable result and concurrency behavior; a tracing identifier by itself supplies none of those guarantees.
Which component in this topology could be removed from a smaller first deployment?
Caller retry, Operation registry, Domain transaction, Result record name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Bind an operation key to the normalized request.
What evidence must a caller have before relying on the observation path?
On retry, compare request meaning. Return the recorded result or pending/unknown state. Retain identity at least as long as supported retries can arrive. Reject conflicting meaning rather than picking a convenient result. The registry must atomically bind the identity and ensure concurrent callers cannot both initiate distinct effects.
45-minute interview rubric
- 00–05: scope attempt and operation record.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw operation record, numbered writes and reads.
- 28–40: challenge recovery: Retain a stable identity and reconcile ambiguous completion.
- 40–45: defend operation_id placement, observations and remaining assumptions.
Go deeper
- Idempotent requests | Stripe API Reference · Primary document · docs.stripe.com. Retain a stable identity and reconcile ambiguous completion. Verified 2026-10-26.
- Exponential Backoff And Jitter | AWS Architecture Blog · Primary document · aws.amazon.com. Retain a stable identity and reconcile ambiguous completion. Verified 2026-10-26.
- Implementing Stripe-like Idempotency Keys in Postgres — brandur.org · Primary document · brandur.org. Retain a stable identity and reconcile ambiguous completion. Verified 2026-10-26.
- PostgreSQL: Documentation: 17: 13.2. Transaction Isolation · Primary document · www.postgresql.org. Retain a stable identity and reconcile ambiguous completion. Verified 2026-10-26.
- RFC 9110: HTTP Semantics · Primary document · www.rfc-editor.org. Retain a stable identity and reconcile ambiguous completion. Verified 2026-10-26.
Decision log
Retain a stable identity and reconcile ambiguous completion.
Preserve attempt identity and operation record ownership.
Revisit changed workload, observations or recovery objectives.