Api idempotency retry
Design idempotency-key support and client retry guidance for a public API so integrators retry safely - key derivation and per-caller scoping, storage TTL and replay windows, atomic claim mechanisms (DB unique constraint, SERIALIZABLE row lock, conditional writes), payload-mismatch rejection, in-flight duplicate handling, exponential backoff with jitter, retry budgets, timeout propagation, and SDK retry defaults. Use whenever the user mentions an Idempotency-Key header, duplicate or double-submitted requests, safe POST retries, backoff, or jitter - even if they never say "idempotency". Do NOT use for what the error response signals (samber/developer-platform-skills@api-error-design) or webhook delivery retries (samber/developer-platform-skills@webhook-platform-design).
By- name:
- api-idempotency-retry
- description:
- Design idempotency-key support and client retry guidance for a public API so integrators retry safely - key derivation and per-caller scoping, storage TTL and replay windows, atomic claim mechanisms (DB unique constraint, SERIALIZABLE row lock, conditional writes), payload-mismatch rejection, in-flight duplicate handling, exponential backoff with jitter, retry budgets, timeout propagation, and SDK retry defaults. Use whenever the user mentions an Idempotency-Key header, duplicate or double-submitted requests, safe POST retries, backoff, or jitter - even if they never say "idempotency". Do NOT use for what the error response signals (samber/developer-platform-skills@api-error-design) or webhook delivery retries (samber/developer-platform-skills@webhook-platform-design).
API Idempotency and Retry
You design the two halves of one guarantee: server-side idempotency keys that make a retried write safe, and client-side retry behavior that uses them responsibly. Shipping either half alone is the trap - Resilience4j's own docs state it as a hard constraint, not a suggestion: retried operations must be idempotent, so retry guidance without key support (or the reverse) leaves the guarantee open exactly where a dropped connection tests it.
Two facts frame everything below:
- Exactly-once delivery is impossible over an unreliable network (Tyler Treat's canonical argument, grounded in the FLP result). What a key actually buys is effectively-once: at-least-once delivery plus duplicate collapse, bounded to the scope where idempotency is actually implemented.
- There is no ratified standard behind the
Idempotency-Keyheader. The IETF draft (draft-ietf-httpapi-idempotency-key-header) expired in April 2026 without ratification. The header name is consistent across the industry because Stripe popularized it, but the semantics (TTL, mismatch behavior, concurrency handling) are whatever each provider decided, so yours must be designed and documented, never assumed.
Memory (advised): When memory lives in a file, consider using developer-platform-context.md; if a different memory system is in use, rely on that instead. The file is an advisory reference, not a mandatory requirement. Separate task info in different sections. Remove finished tasks. Add a date to a task; no date for general project context. Some interview responses may differ between 2 tasks.
Clarifying questions
Ask these before designing anything; each answer changes a later step. Batch them - this is a tactical design task, not a strategy interview.
- Paradigm: REST, gRPC, or both? (gRPC carries deadline propagation natively; REST needs the header convention and explicit deadline plumbing)
- Which endpoints are non-idempotent? Request the endpoint list or OpenAPI spec and enumerate every state-changing operation.
- What storage backs the key store - a relational DB with unique constraints and transactions, a conditional-write KV store, or only a cache? (rules atomic-claim options in or out - see step 4)
- Do any requests call an external, non-rollbackable system mid-flight (a charge, an outbound email)? (drives recovery points - see step 5)
- Which SDK languages do you ship, and do integrators also call raw HTTP? (drives how much of the retry mechanics you can default for them - see step 6)
- What is the longest possible retry chain - dead-letter-queue replay windows, dispute windows, scheduled re-runs? (drives TTL - see step 3)
- By when must the guarantee hold: a one-off fix (stop the duplicate charges one client is filing tickets about), or a compounding contract every future endpoint inherits? What is the effort ceiling on the claim mechanism - a ship date that rules out a schema or isolation-level migration, or existing fluency with SERIALIZABLE workloads? (re-ranks the claim menu - see step 4: a hard date promotes whatever the current store already supports, a compounding mandate promotes the richer claim lifecycle, and a ceiling that forbids a schema migration deletes the rungs it cannot reach rather than ranking them last)
Who controls the retry loop
Every retry decision is made by a developer or a program, whoever bought the product. The design splits by who controls the retry loop:
- First-party developers - you control both ends; internal convention plus code review covers most of it. The cheapest audience to serve.
- Third-party integrators calling raw HTTP - they write their own retry loop from your docs alone. They need the full contract published: key semantics, TTL, mismatch and in-flight behavior, and a worked backoff example, because no standard fills the gaps for them.
- SDK-mediated callers - your SDK is their retry loop. Its defaults (backoff, jitter, attempt caps, key auto-generation) are the contract most callers will never read past, so wrong defaults ship duplicates at fleet scale.
Design for raw-HTTP integrators first - a contract complete enough for them is what your own SDKs then automate - and treat SDK defaults as the highest-leverage artifact, since they decide behavior for the majority who never read the docs.
Workflow
- Identify retry-unsafe endpoints.
- Design the key contract.
- Set storage and TTL.
- Claim the key atomically.
- Design the response semantics.
- Write client retry guidance and SDK defaults.
- Document the contract for integrators.
Each step has a section below, in order.
1. Identify retry-unsafe endpoints
- RFC 9110 - the one ratified document relevant here - defines GET, PUT, and DELETE as idempotent methods and POST as not. It says nothing about the
Idempotency-Keyretrofit pattern. - Enumerate every state-changing endpoint. Each must either accept an idempotency key or be explicitly documented as unsafe to retry - the review-level check
samber/developer-platform-skills@public-api-design-reviewperforms; this skill builds what makes the first option true. - Verify claimed idempotency, don't trust the method: a PUT that appends to a log or a DELETE that decrements a counter is not idempotent whatever the method promises.
2. Design the key contract
- The client mints the key, the server never derives it. AWS's Builders' Library names the rejected alternative: a server-side hash of request parameters breaks when two genuinely identical requests are both intended (launching two identical instances on purpose) - a caller-provided key expresses intent an inferred one cannot. Stripe, AWS, Twilio, and Resend all put the client in charge.
- Scope keys per caller -
(account_id, idempotency_key)- never globally. Stripe, AWS, and the standard Postgres reference implementation all key on the pair, so the same key string reused by different accounts never collides. - Recommend a derivation to clients. Three work; rank them for the client rather than listing them (Resend's own recommendation order):
- value:
event-derived > request-scoped > random UUID reused across retries - effort:
event-derived > request-scoped > random UUID reused across retries - efficiency:
event-derived > request-scoped > random UUID reused across retries- value and effort rank identically here, so their spread decides the ratio: minutes wide on effort (name the key after an identifier the caller already holds) against the whole guarantee on value. - Default rung: event-derived (
order-confirm-${orderId}) - deterministic by construction, so a retry cannot fail to reuse the key. Move down to request-scoped when no stable business identifier exists at call time, and to a reused random UUID when the caller is a stateless script. Nothing is starved here: every rung costs one line of client code. - Never rank a fourth rung below these: a fresh value per attempt (
Date.now(),randomUUID()regenerated on retry) defeats the mechanism entirely, so document it as the anti-pattern instead.
- value:
- Guard the payload: the same key with a different request body is a client bug - reject it (409 is the field convention; Resend names it
409 invalid_idempotent_request), never silently replay. The expired IETF draft generalizes this into an optional payload fingerprint stored beside the key; a checksum of the payload is the simplest form. - Store both outcomes. Stripe saves failures as well as successes - including 500s - so a retry replays the exact original result. Decide explicitly whether a stored failure replays verbatim (Stripe v1) or the operation may be re-attempted without side effects (Stripe v2); leaving it undecided is a design gap.
3. Set storage and TTL
- Retention is two separate concerns, not one TTL (Brandur Leach's reference implementation):
- Replay window (~24h) - governs idempotent-replay correctness; also the documented convention at Stripe, Resend, and Twilio.
- Reaper threshold (~72h) - a longer operational window that keeps records alive for human recovery, so a bad Friday deploy's failed requests survive the weekend for Monday's fix.
- Set the replay window from the longest retry chain (question 6), never from storage cost. A 24-hour TTL behind a 7-day DLQ replay is a duplicate waiting to happen. AWS retains EC2 run tokens for the resource's lifetime plus a grace period - which is what lets a late retry get a consistent answer even after the resource was deleted.
- After expiry, treat a reused key as a brand-new request - every provider surveyed does; none returns an error for post-TTL reuse.
- Store the full response verbatim (status, headers that matter, body), not a summary - the replay must be indistinguishable from the original.
4. Claim the key atomically
A check-then-insert is a TOCTOU race under concurrent retries: both callers see "absent" and both proceed. The claim must be a single atomic operation the storage layer arbitrates. Three mechanisms appear in production, ranked:
efficiency:
DB unique constraint > conditional-write OCC > row lock + SERIALIZABLEeffort:
row lock + SERIALIZABLE > conditional-write OCC > DB unique constraintvalue:
row lock + SERIALIZABLE > DB unique constraint == conditional-write OCCDefault rung: a unique constraint on
(account_id, idempotency_key). The database picks the single winner; the loser gets its 409 from theINSERTfailure itself, not an application-level check. Nearly free - one index - and transaction isolation gives the fencing guarantee below at no extra cost.Conditional-write OCC (DynamoDB-style) delivers the same single-winner claim on stores without unique-constraint transactions - the tie on the value line is real: same guarantee, different storage family. Your answer to question 3 rules one of these two out rather than ranking it; a ruled-out option is deleted, not demoted.
Row lock + SERIALIZABLE transaction is the starved option.
- Value: a
locked_atcolumn inside a SERIALIZABLE transaction represents in-flight as a first-class state, survives lock expiry, and anchors resumable recovery points. - Effort: isolation-level tuning, serialization-abort retry handling - so it loses every efficiency round.
- Promote it when requests span foreign state mutations (question 4): multi-step requests need the richer claim lifecycle, not just a winner-picker.
- Value: a
Whatever the mechanism: the claim and the business mutation must commit as one ACID unit - AWS states this as a hard requirement, not a best practice. A claim outside the transaction it guards can record a token for a resource that was never created, or the reverse.
A bare Redis
SETNX+ TTL lock is not a fourth option. Kleppmann's analysis: without a fencing token, a client paused past its lease expiry can still write after the lock moved on - no timing assumption saves you. No surveyed vendor uses a distributed lock for the claim; if Redis is all you have, layer fencing tokens on top, and know the DB constraint sidesteps the problem entirely.This ranking is a default, not a law. Re-rank against the storage answer and the effort ceiling (questions 3 and 7): a team already running SERIALIZABLE workloads gets the starved option far cheaper than the effort line assumes. A ship date that forbids a schema migration promotes whichever mechanism their current store already supports.
5. Design the response semantics
The bug in most homegrown implementations is treating a key as binary - seen or not-seen. A key is a three-state machine: absent, in-flight, complete. The retry that hits an in-flight key is not the bug ("your client library did exactly what it was configured to do when the connection dropped"); the bug is a server with no way to say "seen, not finished."
| Outcome | What happened | Correct behavior |
|---|---|---|
| Never received | Network drop before processing | Retry proceeds as a first attempt; the claim wins normally |
| Received, not processed | Claim held, no terminal result yet | Return an in-flight conflict, or resume from the last recovery point once the original lock expired |
| Processed, response lost | Result committed; response never arrived | Replay the stored response verbatim - no re-execution |
For the in-flight case, pick one:
- Reject with 409 (Resend's
409 concurrent_idempotent_requests, documented advice "wait and retry") - simplest and safest default. - Block until the bounded result, when the caller needs it synchronously.
- Return 202 plus a status URL, for long-running effects.
Never let the second caller through because the first "seems stuck." The expired IETF draft deliberately made in-flight conflict and completed replay different responses, not fallbacks of each other.
- Reject with 409 (Resend's
For multi-step requests (question 4), decompose into atomic phases separated by each foreign state mutation, persisting a recovery point between phases - a retried request resumes exactly where it left off instead of re-running an external call already made. Record intent before calling out, so a crash between call and response leaves evidence.
Run recovery as active background jobs, not passive expiry (Brandur's model):
- A completer pushes abandoned in-flight requests through to completion.
- A reaper deletes expired keys and logs what it couldn't finish for a human.
What the error responses look like - codes, envelope,
retryableflag,Retry-After- issamber/developer-platform-skills@api-error-design's territory; consume its signals, don't redesign them here. Distinguishing your two 409 meanings (payload mismatch vs in-flight) with distinct machine-readable codes is that skill's taxonomy applied to this skill's states.
See references/key-lifecycle-walkthrough.md for the full worked lifecycle: schema, claim query, all three states' responses, and a multi-step recovery-point example.
6. Write client retry guidance and SDK defaults
- Retry an explicit allowlist, never a blanket catch: 429 (honoring
Retry-After), 502, 503, 504, connection timeouts and resets - 500 cautiously (some 500s are a real bug that retries identically). Never retry non-429 4xx, auth failures, or exceptions that are bugs. Four independent sources (tenacity, Resilience4j, Resend, and the response-signaling side) converge on this exact split - cite it as convergent practice, not one vendor's opinion. - Never retry a read timeout on a non-idempotent operation without an idempotency key already in place. This is the exact boundary condition the server half of this skill exists to close.
- Backoff must carry jitter. Ranked (Marc Brooker's AWS analysis, the canonical source):
- value:
full jitter > decorrelated jitter > equal jitter > no jitter - effort:
full jitter == decorrelated jitter == equal jitter == no jitter- a real tie, not a dodge: each is one formula or one library flag, identical to write, test, and reverse, so no rung buys its value with more of the reader's time. - efficiency: the value order unchanged, since equal effort cancels out of the ratio.
- Default rung: full jitter (
sleep = random(0, min(cap, base * 2^attempt))) - lowest total client work and lowest server load, at slightly more total time to completion. - Starved by that order: decorrelated jitter, which completes faster for more total work. Promote it when a user-facing call sits inside a tight deadline and time-to-success outweighs fleet load. Equal jitter is Brooker's "clear loser" among jittered options, and no jitter re-synchronizes the fleet into the exact spike that caused the failures - keep neither in the menu you hand an integrator.
- Re-rank against what you know about the caller: a single-instance batch job pays none of the fleet synchronization cost this order assumes.
- value:
- Bound both attempt count and total duration, not attempts alone - a per-attempt-reasonable loop can blow past the caller's own budget. Log every retry (attempt, error, next wait); a silent retry loop hides an outage in the making.
- Add a fleet-wide retry budget, distinct from per-caller caps: stop retrying once retries exceed a set share of traffic over a sliding window. A hundred instances each retrying three times amplify load 300x while every instance looks reasonable in isolation. AWS's token bucket is the named implementation, tuned to engage the quota sooner in a real outage: 14 tokens per transient-error retry, 5 per throttle retry.
- Propagate the deadline: one overall deadline set at the top, per-attempt timeouts budgeted inside it - never a fresh overall timeout per attempt, which silently extends the caller's real wait. Set single timeouts at 2-3x measured p99, not an OS default. gRPC's relative-timeout-on-the-wire model is the citable mechanics for chains.
- Point integrators at their language's retry library (tenacity, Resilience4j, or equivalent) before describing formulas - the formula is a one-liner there, pre-debugged. When pairing with a circuit breaker, state the stacking order:
Retry → CircuitBreaker → RateLimiter → Bulkhead. - For SDKs you ship: default retries ON with backoff + jitter and a bounded attempt count (AWS defaults to 3 total), and auto-generate idempotency keys for unsafe operations where the SDK can. Defaults are the contract for callers who never read docs. How your retry defaults interact with the platform's rate-limit policy - whether SDK retries count against quota, adaptive throttling - is
samber/developer-platform-skills@api-rate-limit-policyterritory.
Formulas, budget mechanics, and deadline math: references/backoff-jitter-formulas.md. Cross-vendor defaults to calibrate yours against: references/vendor-sdk-retry-defaults.md.
7. Document the contract for integrators
Because no standard defines the semantics, your documentation is the only normative source your integrators have. Document, per the audience split above:
- Which endpoints accept the key, the header name, max key length, and the recommended derivation.
- Scoping, the replay window as a concrete number, and what happens after it expires ("treated as a new request").
- Both conflict behaviors, each with its distinct error code: payload mismatch and in-flight duplicate.
- Whether a stored failure replays or re-attempts (the Stripe v1/v2 distinction, applied to your API).
- A worked retry loop with concrete numbers - schedule, cap, jitter - like Resend's documented
1s → 2s → 4s → 8scapped at 30s. - Never write "exactly-once delivery" - the claim is provably false across an open network. Write what is true instead: retries are safe within the documented key scope and window. Correct the claim wherever marketing already made it (Treat's steelman: Kafka's exactly-once holds only inside a closed transactional system; a public API is by definition not one).
Failure modes
Anti-pattern checklist - each is a direct audit finding:
- A key accepted but never stored or honored - tells the client retrying is safe when it isn't; worse than no key at all.
- A fresh key value generated per attempt.
- Check-then-insert claiming (TOCTOU race).
- Binary key state with no in-flight representation.
- Same key, different payload, silently replayed.
- Replay window shorter than the longest retry chain (the 24h-TTL-behind-7-day-DLQ trap).
- A bare
SETNXlock with no fencing token as the claim. - No decision on whether stored failures replay or re-execute.
- Retry loop that resets its overall timeout each attempt.
- Backoff without jitter.
- "Exactly-once" anywhere in the docs.
Measurement
- Concurrency gate: fire N identical concurrent requests with one key against a state-changing endpoint - exactly one side effect must execute; the other N-1 get the in-flight conflict or the stored replay. Binary pass; iterate the claim design until it holds. This is the definitional guarantee, testable directly.
- Crash-recovery gate: kill the server between atomic phases of a multi-step request, then retry - the request must resume from its recovery point with zero repeated external calls. Binary pass where question 4 answered yes.
- Duplicate side-effect rate in production: within the documented scope and window the design target is zero by definition - track it as the alarm that the gates regressed, not as a tunable threshold.
- Orphaned-key rate (claimed, never completed - the completer's queue): no published industry threshold exists, so set the baseline from your own first month and watch the trend, as with any unsourced operational metric.
Invocation examples
- "Add Idempotency-Key support to our POST /payments and POST /orders endpoints - we're seeing duplicate charges when mobile clients retry on timeout."
- "Write the retry guidance section of our API docs, and pick the backoff defaults for the Python and Node SDKs we ship."
- "Two concurrent webhook handlers both created the same invoice - audit our idempotency implementation and find the race."
References
- references/key-lifecycle-walkthrough.md - worked key lifecycle: schema, atomic claim, three-state responses with real 409 codes, recovery points, completer/reaper.
- references/backoff-jitter-formulas.md - the three jitter formulas with trade-offs, retry-budget mechanics, deadline propagation, timeout setting.
- references/vendor-sdk-retry-defaults.md - how AWS, Stripe, Google Cloud, Twilio, and Resend default retry and idempotency behavior; what to copy and what to flag.
Open this reference as its own page
Backoff, jitter, retry budgets, and deadlines - the math
Canonical source for the jitter comparison: Marc Brooker, AWS Architecture Blog, "Exponential Backoff and Jitter" (2015, updated 2023 - the update states the guidance "continues to serve as a pillar for how Amazon builds remote client libraries"). His core finding: capped exponential backoff alone "helps only a small amount" under contention - jitter, not backoff, is what reduces total client work in a retry storm.
The four strategies
| Strategy | Formula | Trade-off |
|---|---|---|
| Full jitter (recommended default) | sleep = random(0, min(cap, base * 2^attempt)) |
Lowest total client work and lowest server load; slightly more total time to completion |
| Decorrelated jitter | sleep = min(cap, random(base, sleep_prev * 3)) |
More total work than full jitter, completes slightly faster |
| Equal jitter | half the backoff fixed, other half randomized | Brooker's "clear loser" among the jittered approaches - more work than full jitter and much slower |
| No jitter (plain exponential) | sleep = base * 2^attempt |
Categorically the worst - so slow in total that Brooker's own comparison graph leaves it off |
Why no-jitter fails at fleet scale: 1,000 clients that failed together all retry at exactly t+100ms, t+200ms, t+400ms - re-creating the overload spike that caused the failures. Full jitter spreads the same population across the whole window.
Brooker's 2019 follow-up ("Timeouts, retries and backoff with jitter", AWS Builders' Library) extends jitter to any periodic job, with one caution: apply jitter consistently per host, so an overload pattern stays diagnosable instead of looking like random noise.
A concrete documented schedule
Resend's documented client loop - a citable worked example for integrator docs:
const delay =
Math.min(1000 * Math.pow(2, attempt), 30000) + // 1s → 2s → 4s → 8s ... cap 30s
Math.random() * 1000; // jitter
Prefer the retry library over hand-rolled math wherever one exists - the formula is one line there, pre-debugged:
- Python (tenacity):
wait_exponential_jitter(initial=1, max=10), bounded withstop_after_attempt(5) | stop_after_delay(60) - JVM (Resilience4j):
IntervalFunction.ofExponentialBackoff(...)withexponentialBackoffMultiplier: 2
Bound both attempts and total duration (the tenacity combinator above): each attempt can look reasonable while the loop blows past the caller's own budget. Log every retry - attempt number, error, next wait; both libraries treat retry logging as a default, not an opt-in.
Retry budget: the fleet-wide cap
Per-caller attempt caps cannot prevent amplification: a fleet of 100 instances each retrying 3 times amplifies load on a struggling downstream by 300x while every instance's cap looks reasonable in isolation.
- Mechanism: track the ratio of retried to original requests over a sliding window (e.g. 1 minute); once it exceeds the budget (e.g. 20%), stop retrying and fail fast.
- Named implementation - AWS SDK standard mode's token bucket: each retry deducts tokens, each success replenishes; when the bucket empties, the SDK returns the error without retrying. 2026 rebalance: a transient-error retry now costs 14 tokens (up from 5); a throttling retry still costs 5 - the higher transient cost makes the quota engage sooner during a sustained outage, so the downstream recovers faster.
Deadline propagation
- Set one overall deadline at the top of the call; budget per-attempt timeouts inside it. Never create a fresh overall timeout inside each retry attempt - that silently extends the caller's real wait past what they committed to, and the "successful" retry may answer a caller who already gave up.
- Down a call chain, pass the remaining budget with the request so each hop subtracts its own time before calling deeper - a mid-chain service must never start work whose timeout exceeds what the top-level caller has left. gRPC is the citable mechanics: deadlines are absolute in the API but sent as relative timeouts on the wire, converted at each hop, precisely to dodge clock skew between machines.
- Setting a single timeout value: measure p99 latency under normal load and set the timeout at 2-3x that p99 - not a round number, and never the OS default (120-300s, which pins a thread to a hung connection for minutes).
Pattern stacking
When retry is combined with other resilience patterns, the execution order matters (Resilience4j's documented order):
Retry → CircuitBreaker → RateLimiter → Bulkhead → call
- Retry wraps the outermost layer, so one logical call can still retry across circuit-breaker rejections during the half-open probe.
- The circuit breaker is retry's complement, not its substitute: once a downstream is confirmed down, the OPEN state short-circuits further retries instead of making every caller pay the full backoff schedule.
- Half-open recovery must gate to one or two trial requests, not the whole backlog, or it re-creates the thundering herd.
Open this reference as its own page
Idempotency key lifecycle - worked walkthrough
A complete pass through one key's life, from first claim to reaping, using the default-rung mechanism (DB unique constraint) and the patterns from the Postgres reference implementation (Brandur Leach, brandur.org/idempotency-keys). No vendor publishes their production internals, so treat this as an independent, Stripe-inspired reference design, not Stripe's disclosed code.
Storage schema
Relational-flavored for concreteness; every column maps to a concept any store needs.
CREATE TABLE idempotency_keys (
id BIGSERIAL PRIMARY KEY,
account_id BIGINT NOT NULL, -- per-caller scope, never global
idempotency_key TEXT NOT NULL, -- client-minted, e.g. up to 255 chars (Stripe's cap)
request_fingerprint TEXT NOT NULL, -- payload checksum for the mismatch guard
locked_at TIMESTAMPTZ, -- non-NULL = in-flight; drives lock recovery
recovery_point TEXT NOT NULL DEFAULT 'started', -- resumable position for multi-step requests
response_status INT, -- stored outcome: both success AND failure
response_body JSONB, -- replayed verbatim on completed retry
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (account_id, idempotency_key) -- the atomic claim: the DB picks one winner
);
The atomic claim
Never SELECT then INSERT - under concurrent retries both callers see "absent" and both proceed (TOCTOU). Insert first and let the constraint arbitrate:
INSERT INTO idempotency_keys (account_id, idempotency_key, request_fingerprint, locked_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (account_id, idempotency_key) DO NOTHING
RETURNING id;
- A returned row: this caller won the claim; proceed as a first attempt.
- No row: the key exists. Read it and branch on its state (next section).
- The claim insert and the business mutation commit in one transaction (or the first atomic phase's transaction) - the AWS hard requirement: token recorded and effect applied are all-or-nothing.
Branching on an existing key - the three states
State: complete (response_status set) - first compare request_fingerprint.
- Fingerprint matches → replay
response_status+response_bodyverbatim. No re-execution, even if the stored outcome is a 500 (Stripe v1 semantics: the retry gets exactly what the original got). - Fingerprint differs → payload mismatch, a client bug. Reject:
HTTP/1.1 409 Conflict
{ "code": "invalid_idempotent_request",
"message": "This idempotency key was already used with a different request payload. Use a new key, or resend the original payload." }
(Resend's documented code name; fix advice belongs in the message - see samber/developer-platform-skills@api-error-design for message rules.)
State: in-flight (locked_at recent, no stored response) - the original is still running. Default handling, per the field convention:
HTTP/1.1 409 Conflict
{ "code": "concurrent_idempotent_requests",
"message": "A request with this idempotency key is currently in progress. Wait and retry." }
Never let the second caller through because the first "seems stuck" - the alternatives (block for the bounded result; 202 + status URL for long-running effects) also keep exactly one executor. The expired IETF draft made this deliberate: in-flight conflict and completed replay are different responses, not fallbacks.
State: in-flight but lock expired (locked_at older than the lock timeout) - the original crashed or was abandoned. This caller may take over the lock (an atomic conditional UPDATE ... SET locked_at = now() WHERE locked_at < $threshold) and resume from recovery_point - not from the beginning.
Multi-step requests: recovery points around foreign state mutations
A request that calls an external, non-rollbackable system mid-flight (a card charge, an outbound email) cannot be one transaction. Decompose into atomic phases separated by each foreign call:
Phase 1 (txn): claim key, validate, create local order row → recovery_point = 'order_created'
-- foreign state mutation: charge the card --
Phase 2 (txn): record charge id → recovery_point = 'charge_recorded'
-- foreign state mutation: send confirmation email --
Phase 3 (txn): store final response → recovery_point = 'finished'
- Within each phase, everything commits or nothing does (ACID).
- Record intent before each foreign call - a crash between the call and its response then leaves evidence to reconcile, instead of a silent duplicate on retry.
- A retry (or the completer) reads
recovery_pointand resumes at the right phase:charge_recordedmeans the card is charged - never charge again, continue to the email.
Retention: two horizons, then reaping
- Replay window (~24h) - governs correctness: retries inside it replay; a reused key after it is treated as a brand-new request (every surveyed provider does this; none errors on post-TTL reuse). Set it from the longest retry chain - DLQ replays, dispute windows - not from storage cost. Tell integrators the operational consequence, as Resend does: "complete your retry logic well within 24 hours."
- Reaper threshold (~72h) - governs operations: records outlive the replay window so a bad Friday deploy's failed requests survive the weekend for a developer to push through on Monday.
The two background jobs
- Completer: finds requests that look abandoned mid-flight (claim held, lock expired, client gave up) and pushes them to completion using only idempotency keys and recovery points - no per-endpoint knowledge.
- Reaper: deletes records past the reaper threshold, attempts cleanup on anything unfinishable, and logs what it couldn't finish for a human to chase.
Recovery is these active processes, not passive expiry - expiry alone leaves half-finished requests half-finished forever.
Client-side pairing
The key only works if the client reuses it across retries of one intent. For critical calls, write the intent to a durable queue with a pending status before the first attempt, so the retry state - key included - survives an application restart.
Derivation, in the recommended order:
- Event-derived (
order-confirm-${orderId}) - deterministic by construction. - Request-scoped (
reset-${userId}-${resetRequestId}). - A random UUID generated once and reused.
The anti-pattern that defeats everything: Date.now() or a fresh crypto.randomUUID() per attempt.
Open this reference as its own page
Vendor SDK retry and idempotency defaults - cross-vendor comparison
How five platforms actually default and document this behavior, to calibrate your own SDK defaults and docs against. What converges is safe to copy; what diverges is exactly the part no standard settles - decide it explicitly for your own API.
The comparison table
| Vendor | Default retry mode | Max attempts | Backoff / idempotency behavior |
|---|---|---|---|
| AWS SDK v2 / CLI v2 | standard |
3 (incl. initial) | Exponential + jitter, gated by a token-bucket retry quota (14 tokens per transient-error retry, 5 per throttling retry, since the 2026 rebalance) |
AWS SDK adaptive mode |
opt-in | 3, same jitter | Adds a client-side rate limiter reacting to throttling; not recommended for multi-tenant apps unless tenants get isolated clients |
| Stripe SDKs | client sets or omits the idempotency key; no fixed attempt cap | n/a | v1: retry with the same key replays the previously saved response verbatim; v2: attempts to complete without side effects and may return an updated response |
| Google Cloud client libraries | per-service, varies | varies | Distinguishes unconditionally idempotent operations (GET, list) from conditionally idempotent ones needing preconditions/ETags before retry is safe |
| Twilio | 24-hour idempotency window on config/orchestrator operations | n/a | Outbound webhook deliveries retried with exponential backoff up to 48 hours |
| Resend | idempotency opt-in per request | n/a | 24-hour key retention; two named 409 codes split payload-conflict from concurrent-in-flight |
What to copy - the convergent core
- Retries on by default, bounded (AWS's 3 total attempts is the concrete anchor), with exponential backoff + jitter - since the 2023 update, most AWS SDKs ship this in standard/adaptive modes.
- A ~24-hour key retention window (Stripe, Resend, Twilio independently) - provided your retry chains actually fit inside it.
- Client-minted keys, V4 UUID recommended, generous length cap (Stripe: up to 255 characters).
- Payload-mismatch on a reused key rejected, never silently replayed.
What to flag, not generalize
- Stripe v1 vs v2 is a real behavioral fork - name the generation.
- v1: pure replay - same key returns the identical stored response, including a stored 500.
- v2: supervised retry - may complete the operation without duplicating side effects, returning a response that differs from the original attempt.
- "Stripe's idempotency model" without a version is an ambiguous claim.
- Google Cloud has no single cross-product idempotency-key spec analogous to Stripe's.
- Cloud Storage uses object preconditions.
- Individual APIs document their own retry guidance.
- AIP-155 defines request IDs for the broader surface.
- Scope any "Google does X" claim to the specific API.
- Verified vs inferred: none of Stripe, AWS, or Resend publish the isolation level or lock implementation behind their production key stores. Only the independent Postgres reference implementation (Brandur Leach's, Stripe-inspired) is concrete there - treat claims about "how Stripe's database enforces this" as inference from that reference design, never as disclosed internals.
What this means for the SDK you ship
- The defaults decide behavior for the majority of callers who never read past installation - treat them as API contract, reviewed like one.
- Auto-generate an idempotency key for retry-unsafe operations when the SDK controls the request (Stripe's SDKs do) - the caller gets safe retries without knowing the mechanism exists.
- Expose the knobs (attempts, max delay, per-request key override) but make the zero-config path the safe one.
- Document the defaults in the SDK README with the same precision as the raw-HTTP contract: mode, attempt count, backoff shape, which operations get automatic keys.
More in this playbook
Cross crm opportunity sync
Coordinate opportunities and customer records across multiple CRMs while preserving attribution, visibility, commissions, and governance.
IntegrationsMIT Wade Foster + 1Co-founder & CEO @ ZapierInstall zapier
Install and connect Zapier, routing to the right surface (MCP, SDK, or CLI) for what the person needs. Use when someone says "install Zapier", "add Zapier", "connect Zapier", or "set up Zapier", or when they want an AI client (Claude, ChatGPT, Cursor) to use their apps, want to call Zapier from code, or want Zapier in the terminal.
IntegrationsMIT Wade Foster + 1Co-founder & CEO @ ZapierMcp sheet cache bridge
Keep Zapier Tables or another MCP-connected record store as the source of truth while Google Sheets-based tools read an event-driven cache tab.
