API Idempotency: Keys, Storage, Retries
"A client generates an idempotency key, which is a unique key that the server uses to recognize subsequent retries of the same request." — Stripe API reference, Idempotent requests
Summary: A network call can fail after the work was done, so the client cannot tell "it did not happen" from "it happened and I did not hear back". An idempotency key turns that doubt into a rule: the client sends one ID for one intended operation on every attempt, and the server does the work once, remembers the answer and repeats it. Focus: Why POST needs a key, the Idempotency-Key header draft, key scope, format and entropy (UUIDv4, ULID, derived keys), the storage record (status, fingerprint, stored response, TTL), the concurrent-duplicate problem (unique constraint, SELECT ... FOR UPDATE, Redis SET NX PX, 409), mismatched payloads (422), crashes between the side effect and the record, replay with Idempotent-Replayed, key propagation to payment providers, natural idempotency, idempotent consumers, cleanup and observability, and how Stripe, Adyen, Square, PayPal and AWS do it. Learning goal: Make any state-changing endpoint safe to retry: pick the key and its scope, store a claim atomically, run the side effect exactly once or make it idempotent itself, replay the stored answer, expire the record, and prove all of it with tests that fire concurrent duplicates.
This chapter owns the implementation of idempotency for client-facing APIs. The HTTP contract (which methods are idempotent, status codes, resource design) lives in REST API Design; when and how a client retries (backoff, jitter, budgets) lives in Timeouts, Retries & Jitter; the consumer side of a message queue (dedup table, "process then mark") lives in Idempotent Consumers & the Inbox Pattern; the wider payment flow is in Payment Processing Architecture; distributed locks are in Distributed Locking. The architecture-level summary is one block in Service Communication; this page is the deep version.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a timeout is not an answer | Why it exists |
| The IETF draft, Stripe's post, AWS's article | Where it comes from |
| Why POST needs a key and GET does not | Network ambiguity |
| The header, its syntax and error codes | The Idempotency-Key header |
| Who may reuse which key | Key scope |
| UUIDv4, ULID, derived keys, entropy | Key format |
| The table or Redis record | Storage |
| Same key, different body | Fingerprint and 422 |
| Two copies of one request at once | Concurrent duplicates |
| Crash between the charge and the record | Partial failure |
| Replaying the first answer | Response replay |
| Provider keys, derived keys, outbox | Downstream propagation |
| PUT, upsert, conditional write | Natural idempotency |
| Queues and webhooks | Idempotent consumers |
| TTL and cleanup | Cleanup |
| Metrics and logs | Observability |
| What Stripe, Adyen, Square, PayPal and AWS do | Products |
| Exact numbers, codes and knobs | Mechanics |
| Working code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| Which store, which policy | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on experiments | Lab |
| Beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The idea in six steps.
| Step | What happens | Who does it |
|---|---|---|
| 1 | The client creates a key (UUIDv4) for one intended operation | Client |
| 2 | It sends Idempotency-Key: K with every attempt of that operation | Client |
| 3 | The server atomically claims (scope, K) with status in_progress and stores a fingerprint of the request | Server |
| 4 | It runs the side effect once and stores the response with status completed | Server |
| 5 | A retry with the same key and the same body gets the stored response plus Idempotent-Replayed: true | Server |
| 6 | A different body with the same key gets 422; a copy that arrives while the first runs gets 409 | Server |
Which requests need a key.
| Method | Idempotent by definition (RFC 9110)? | Needs a key? | Why |
|---|---|---|---|
| GET, HEAD, OPTIONS | Yes (and safe) | No | No side effect |
| PUT | Yes | No, usually | Replaces the whole resource; second call changes nothing |
| DELETE | Yes | No | Second call finds nothing to delete (response may differ, state does not) |
| POST | No | Yes, for anything that costs money or creates something | Each call may create another thing |
| PATCH | No | Yes when it is relative ("add 10") | balance += 10 twice is not once |
The answers a server gives to a key.
| Situation | Response | Rule |
|---|---|---|
| Key unseen | Run, store, answer normally (201, 200, ...) | Claim before work |
| Key seen, same fingerprint, completed | Same status and body, header Idempotent-Replayed: true | Replay, never rerun |
| Key seen, same fingerprint, still running | 409 Conflict (or wait) | One runner at a time |
| Key seen, different fingerprint | 422 Unprocessable Content | Key reuse is a client bug |
| Key missing on an endpoint that requires it | 400 Bad Request | Per the IETF draft |
First run ended in 5xx | Release the claim (this page) or replay the 5xx (Stripe API v1) | Pick one, document it |
| Key older than the TTL | Treated as unseen | TTL 24 h to 7 days or more |
Why it exists
A distributed call has three outcomes, not two. The request can fail before the work, succeed with the answer arriving, or succeed with the answer lost. Only the third one is dangerous, and from the client's side it looks exactly like the first.
Client Server
1 POST /charges (amount 2000) ----> receives, charges the card
2 writes the charge row
3 ... waits ... <-X-- 202/201 lost (connection reset, load balancer timeout, phone in a tunnel)
4 timeout after 5 s
5 "did it work?" -> unknown. Retry = maybe a second charge. Do not retry = maybe no charge.| Without a key | With a key |
|---|---|
| The client must choose between double charge and lost order | The client can always retry; the server decides |
| Retry logic is dangerous, so people disable it | Retries can be automatic in SDKs |
| Support tickets: "I was charged twice" | The duplicate is answered from the stored record |
| Reconciliation jobs hunt duplicates afterwards | Duplicates cannot be created |
| Cost: none on the server | Cost: a table, a lock, a TTL, replay code |
Everyday picture: a restaurant order slip with a number. If you shout "one pizza, number 17" three times because the waiter looks away, the kitchen sees number 17 once. Without the number, three shouts are three pizzas.
Three common misunderstandings, up front
- "Retries are safe because my database has a unique constraint on the order." A constraint on the business object only helps when the business has a natural key. A charge does not: two charges of 20.00 for the same customer are legitimate. The key is a statement of intent, not a property of the data.
- "Idempotency means the server ignores the second request." It means the second request has no additional effect and, in a good design, returns the same answer as the first one. Ignoring it with an error makes client code handle two paths.
- "Exactly-once delivery exists, so I do not need this." Networks give at-least-once at best (retries) or at-most-once (no retries). "Exactly once" is at-least-once plus an idempotent receiver. That receiver is what this page builds.
Where it comes from
HTTP itself defined the problem. RFC 9110, section 9.2.2, defines an idempotent method as one where "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request", and lists PUT, DELETE and the safe methods as idempotent. POST and PATCH are not, and those are the methods that create things and move money.
Payment companies solved it first with a header. Brandur Leach, writing for Stripe in 2017, describes the mechanism: "When performing a request, a client generates a unique ID to identify just that operation and sends it up to the server along with the normal payload." The same post names the failure case in one line: "The call could succeed, but the connection break before the server can tell its client about it."
Amazon arrived at the same place from the infrastructure side. The Builders' Library article on idempotent APIs explains why a hash of the parameters is not enough ("two exact duplicate requests from the same caller" can be legitimate) and states the preferred design: "a unique caller-provided client request identifier" in the API contract. EC2 calls it ClientToken.
The IETF HTTP API working group is standardising the header: draft-ietf-httpapi-idempotency-key-header-09 (published 21 November 2026, still an Internet-Draft, "work in progress"). Its authors say it is inspired by "Idempotency related patterns described in API documentation of PayPal and Stripe". Treat the draft as the vocabulary and the vendor docs as the behaviour.
| Year | Event | Source |
|---|---|---|
| 2017 | Stripe publishes the idempotency-key design | Stripe blog |
| Before this article | AWS builds ClientToken into EC2 (RunInstances); date not stated in the article | Builders' Library |
| 2022 | RFC 9110 consolidates HTTP semantics, including idempotent methods | RFC 9110 |
| 2024 | RFC 9562 (UUIDs, including v4 random and v7 time-ordered) | RFC 9562 |
| 2026 | IETF draft -09 of the Idempotency-Key header | IETF datatracker |
The concept catalogue
Network ambiguity and why POST needs a key Must-know
In plain words: when a request times out the client does not know whether the server did the work. A key lets the client ask again without risk.
Common misunderstanding: "A timeout means it failed, so I can simply send it again." A timeout means you stopped waiting. The server may be halfway through, finished, or never have received it. Only the server can say which.
Definition: network ambiguity is the state of a client that has sent a mutating request and has neither a success nor a definitive failure. An operation is safe to retry only if repeating it has the same effect as doing it once; POST and PATCH do not have that property unless the server adds it with a key.
Failure mode Server did the work? Client sees Safe to retry without a key?
1 connect fails (no route) no connection error yes
2 server rejects (400/401/409) no status code yes, after fixing
3 server dies mid-request maybe partly reset / timeout unknown
4 response lost after commit yes timeout NO: duplicate
5 proxy times out, server goes on yes (later) 504 NO: duplicate, and the first may still run
6 client crashes, restarts unknown nothing NO: user taps "Pay" againReal scenario: a mobile checkout where the user taps Pay twice; a payment SDK that retries on 504 from a load balancer; a webhook sender that re-sends because your 200 took 31 seconds; an SMS gateway that bills per message.
| Source of the duplicate | Who retries | Key helps? |
|---|---|---|
| User double-click or double-tap | Human | Yes, if the form reuses one key per intent |
| SDK or HTTP client automatic retry | Library | Yes, the SDK reuses its key |
Load balancer or gateway retry (NGINX proxy_next_upstream, Envoy retry policy) | Infrastructure | Yes; also a reason to mark POSTs non-retryable at the proxy |
| Queue redelivery to an HTTP callback | Broker | Yes, key = message ID |
| Job re-run after a worker crash | Scheduler | Yes, key = job ID |
Fix / how to use it: require the key on every endpoint that creates money, goods or messages; generate it where the intent is created (the form, the cart), not where the HTTP call is made; code samples are in Go and Laravel.
The Idempotency-Key header Must-know
In plain words: one request header carries the key. The server uses it to recognise retries.
Common misunderstanding: "It is an official HTTP standard." It is a widely used convention (Stripe, Adyen, Dwolla, WorldPay and others, per the draft's implementation list) and an IETF Internet-Draft. Drafts expire and change; PayPal uses PayPal-Request-Id, Square uses a body field idempotency_key, AWS uses ClientToken.
Definition: the draft defines Idempotency-Key as an Item Structured Header Field whose value "MUST be a String" (RFC 9651), for example Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324" (note the quotes). The key "MUST be unique and MUST NOT be reused with another request with a different request payload." Vendors such as Stripe and Adyen accept the bare value without quotes; a server that wants to be draft-compliant should accept both.
| Draft rule | Status code | Body |
|---|---|---|
| Header missing on an operation that requires it | 400 Bad Request | Problem Details (RFC 9457) with a link to the docs |
| Key reused with a different payload | 422 Unprocessable Content | Problem Details |
| Retry while the original is still processing | 409 Conflict | Problem Details |
| Original completed | A response "consistent with the request being completed" | The original outcome |
Any other 4xx/5xx | Follow the resource's documentation |
POST /v1/charges HTTP/1.1
Host: api.example.test
Authorization: Bearer <token>
Content-Type: application/json
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"
{"customer":"cus_7","amount":2000,"currency":"usd"}Real scenario: a public payments API that publishes: "POST endpoints require Idempotency-Key; keys live 24 hours; reuse with a different body returns 422".
| Decision | Choice that follows the draft | Why |
|---|---|---|
| Where the key goes | Request header | Not part of the payload, so the fingerprint stays stable |
| Document it | Yes: format, TTL, status codes | The draft says resources SHOULD document the behaviour and expiry |
| Without a key | 400 on required endpoints | Silent "best effort" invites double charges |
| Idempotent methods | Ignore the header on GET/PUT/DELETE | Stripe: "Don’t send idempotency keys in GET and DELETE requests because it has no effect." |
Fix / how to use it: read Go middleware (Required: true) or the Laravel EnsureIdempotency middleware; both return 400 for a missing or malformed key before any storage call.
Key scope Must-know
In plain words: a key only means something inside one owner. Client A's K and client B's K are two different keys.
Common misunderstanding: "The key is globally unique, so the table can use it alone as the primary key." If two clients can collide, one can read the other's stored response, which may contain card or customer data. The draft calls this a "data leak" and recommends a "unique composite key as the idempotent cache lookup key", combining the client's key "with other client specific attributes known only to the resource".
Definition: the lookup key is (scope, key), where scope is the authenticated principal (API client, tenant, user), optionally plus the endpoint. Stripe stores keys per account; Adyen's docs say "Keys are stored at a company account level"; EC2 keys are per caller.
T1 Client A: POST /charges Idempotency-Key: 111 -> claim (A, 111), charge 20
T2 Client B: POST /charges Idempotency-Key: 111 -> claim (B, 111), charge 50 (different scope: runs)
T3 Client A: retries with 111, same body -> replay of A's response
T4 Client B guesses A's key from a log -> (B, key) lookup only; A's response is not reachable| Scope choice | Pros | Cons |
|---|---|---|
| Per authenticated client / account | Natural isolation; matches Stripe and Adyen | Anonymous endpoints need another anchor (session, IP + device) |
| Per client + endpoint | Same key may be reused on /charges and /refunds | More rows; clients may be surprised |
| Global | Simple | Cross-tenant leaks and collisions; rejected by the draft |
| Per region | Matches regional stores | Adyen: "idempotency keys will not be checked for duplication in other regions" |
Real scenario: a marketplace where each seller has API credentials; two sellers use a naive counter as the key (1, 2, 3) and would collide without scope.
Fix / how to use it: the Go Options.Scope callback and the Laravel $request->user()->getAuthIdentifier() supply the scope; the SQL primary key is (scope, key).
Key format and entropy Important
In plain words: a key should be long, random and boring: a UUID is fine.
Common misunderstanding: "I will use the order ID as the key, so it is unguessable and deduplicates automatically." An order ID is guessable and is not the same thing as "this payment attempt". Reusing it for a retry of a different amount is exactly the bug the 422 rule exists to catch. A derived key is valid only when one business action maps to one call.
Definition: Stripe: "we suggest using V4 UUIDs, or another random string with enough entropy to avoid collisions. Idempotency keys are up to 255 characters long. Avoid using sensitive data (for example, email addresses or personal identifiers) as idempotency keys." Adyen: maximum 64 characters, UUID recommended. EC2: "a unique, case-sensitive string of up to 64 ASCII characters".
| Format | Bits of randomness | Sortable by time | Notes |
|---|---|---|---|
| UUIDv4 (RFC 9562) | 122 | No | Default choice; RFC 9562 defines v4 as random |
| UUIDv7 (RFC 9562) | about 74 random + 48-bit time | Yes | Time-ordered; easier index locality in the store |
| ULID | 80 random + 48-bit time | Yes (Crockford base32) | 128-bit compatible with UUID, "Lexicographically sortable" per the ULID spec |
Derived (order-1001-charge-1) | Low | Depends | Fine when the business action is unique; predictable, so scope must protect it |
| Random string, 32+ chars | 128+ | No | The draft's example: clkyoesmbgybucifusbbtdsbohtyuuwz |
| Auto-increment counter | Almost none | Yes | Never: guessable, collides between clients |
| Server-side validation | Why |
|---|---|
Fixed format and length (this page: 16 to 255 of A-Za-z0-9_.:-) | The draft: "Always validate the key as per its published specification before processing any request" |
| Reject before any lookup | Prevents injection into the cache or database key |
| Never log a key next to a secret; logging the key itself is fine | Keys are not secrets but must not be sensitive data |
Real scenario: a mobile app creates uuid4() when the "Pay" screen opens and stores it in the form state; a tap retried after a crash reuses the stored key.
Fix / how to use it: idem.ValidKey in Go and the IdempotencyKeyRequest Form Request in Laravel share the same regular expression, so both services accept the same keys.
Storage: the record and its states Must-know
In plain words: the server keeps one small row per key: who, what request, how far it got and what it answered.
Common misunderstanding: "I will store only the key and a 'done' flag." Without the stored response the server cannot answer the retry the way the first request was answered, and without the fingerprint it cannot catch key reuse.
Definition: the record has six parts.
| Field | Purpose | Example |
|---|---|---|
scope, key | Lookup (primary key) | client-7, order-1001-charge |
fingerprint | Detect reuse with a different request | sha256 of method, path, body |
status | in_progress or completed | completed |
owner / lease (locked_until) | Who is running it; when a crashed holder may be replaced | token, now + 60 s |
| stored response | Status code, a few headers, body | 201, Content-Type, {"id":"ch_1"} |
expires_at | Replay window | now + 24 h |
state machine of one key
Begin (atomic insert) Complete (same tx as effect)
(none) ───────────────────────▶ in_progress ───────────────────────────────▶ completed ──▶ (deleted at expires_at)
│ ▲
Abandon (5xx, panic) │ │ lease expired: same fingerprint takes over
▼ │
(none)| Store | Atomic claim | Durable | Extra |
|---|---|---|---|
| PostgreSQL / MySQL table | PRIMARY KEY (scope, key) + INSERT ... ON CONFLICT DO NOTHING (PostgreSQL), INSERT IGNORE or catch error 1062 (MySQL/InnoDB) | Yes, same transaction as the business write | Can join the effect's transaction |
| Redis | SET key value NX PX ttl | Depends on AOF/replication; a failover can lose it | Fast; separate system from the business data |
| DynamoDB | Conditional put (attribute_not_exists) | Yes | TTL attribute for cleanup |
| In-memory map | Mutex | No | Tests only |
| Size limits and TTL | Value | Source |
|---|---|---|
| Stripe key length | up to 255 characters | Stripe API reference |
| Adyen key length | up to 64 characters | Adyen docs |
| EC2 client token | up to 64 ASCII characters | AWS EC2 docs |
| Stripe API v1 key pruning | after at least 24 hours | Stripe API reference |
| Adyen validity | 7 to 14 days after first submission | Adyen docs |
| Stored body | Cap it (this page: 1 MiB request, stores the response as is) | Design choice |
Real scenario: a table with a few hundred bytes per key and a 24-hour TTL holds about 1,000,000 keys per ~500 MB at 500 bytes per row; at 1,000 POSTs per second that is 86,400,000 rows per day. Size it before launch (see Cleanup).
Fix / how to use it: the schema is in SQL; Go PGStore and RedisStore; Laravel migration create_idempotency_keys_table.
Fingerprint and mismatched payload Must-know
In plain words: the server remembers a hash of what was asked. If the same key comes back with a different request, something is wrong on the client.
Common misunderstanding: "If the key matches I should just return the old response." Doing so hides a bug: the client believes it charged 50 and the server charged 20. Stripe errors "if they’re not the same"; AWS returns a "validation error indicating a parameter mismatch" because "it is safest to assume that the customer intended a different outcome".
Definition: a fingerprint is a hash computed from the parts of the request that define intent: method, path with query, and the body (or selected fields). The draft: "If the fingerprint does not match, the resource fails the request ... and does not return the result of the original request." A server that skips fingerprints "cannot detect a key reused with a different payload, and handles such a request as a duplicate."
1 POST /charges K {"amount":2000} -> claim (c1, K, fp1), charge 2000, store 201
2 POST /charges K {"amount":2000} -> fp1 == fp1 -> replay 201
3 POST /charges K {"amount":9999} -> fp2 != fp1 -> 422, handler NOT called
4 POST /refunds K {"amount":2000} -> path differs -> fp3 != fp1 -> 422| Fingerprint input | Detects | Risk |
|---|---|---|
| Whole body hash | Any change | Re-serialisation (key order, spaces) looks like a change; safe but noisy |
| Canonical JSON hash | Semantic change | Needs a canonicaliser; bugs there hide real changes |
| Selected fields (amount, currency, customer) | Business-relevant change | Changes outside those fields are treated as the same request (the draft says so) |
| Method + path + body | Key reuse across endpoints | Add the tenant too if the path has none |
| Headers (Accept-Language, User-Agent) | Nothing useful | Retries legitimately differ; do not include |
| Status code used for mismatch | Who | Note |
|---|---|---|
422 Unprocessable Content | IETF draft, this page | RFC 9110 section 15.5.21 |
400 Bad Request | Some APIs | Acceptable if documented |
409 with code 704 / 422 | Adyen (duplicate while in progress) | "request already processed or in progress" |
Validation error IdempotentParameterMismatch | EC2 | Same key, parameters differ (Region and Availability Zone ignored) |
Real scenario: a client library bug regenerates the amount on retry (a currency rate refresh); the mismatch returns 422 instead of charging twice at two different amounts.
Fix / how to use it: idem.Fingerprint (length-prefixed SHA-256) and the Laravel hash('sha256', method + path + content); compare with hash_equals.
The concurrent-duplicate problem Must-know
In plain words: the retry can arrive while the first request is still running. The server needs one winner and a rule for the loser.
Common misunderstanding: "I check whether the key exists, then insert it." That is a race: two requests both see "not found". The check and the claim must be one atomic operation: a unique-constraint insert, SET NX, a conditional put, or a row lock.
Definition: the claim is the first write; the database or Redis decides the winner. The loser either returns 409 Conflict (draft; Stripe v1 does not save a result for "the request conflicts with another request that’s executing concurrently") or waits for the winner and replays.
T1 (request A) T2 (request B, 5 ms later, same key)
1 INSERT (c1,K,in_progress) -> 1 row (winner)
2 INSERT ... ON CONFLICT DO NOTHING -> 0 rows (loser)
3 charge card ... (800 ms) SELECT status -> in_progress => 409 + Retry-After: 1
4 UPDATE ... completed, store 201
5 (client retries after 1 s) -> replay 201, Idempotent-Replayed: true| Mechanism | Atomicity comes from | Loser behaviour | Product |
|---|---|---|---|
| Unique insert | Primary key / unique index | ON CONFLICT DO NOTHING returns 0 rows | PostgreSQL |
| Unique insert, catch the error | Unique index | Error 1062 (MySQL/InnoDB), SQLSTATE 23505 (PostgreSQL) | MySQL, PostgreSQL |
SELECT ... FOR UPDATE | Row lock held until commit | Blocks until the winner commits, then reads completed and replays | PostgreSQL, InnoDB |
SET key v NX PX ms | Single-threaded command | nil reply; read the key to see who holds it | Redis |
| Conditional put | attribute_not_exists(pk) | ConditionalCheckFailedException | DynamoDB |
Cache::lock | Backend atomic add (Redis, database, memcached) | get() returns false | Laravel |
Advisory lock (pg_advisory_xact_lock) | Lock manager | Blocks or pg_try_advisory_xact_lock returns false | PostgreSQL |
| Loser policy | Client effort | Server effort | Used by |
|---|---|---|---|
409 + Retry-After | Retry later | Trivial | IETF draft, this page |
| Block until winner completes, then replay | None | Holds a connection and a lock | Some internal APIs |
transient-error: true header | Retry same key | Marks the case explicitly | Adyen |
Real scenario: a double-click sends two POSTs 30 ms apart through two app servers; both reach the database at the same moment.
Fix / how to use it: SQL claim statement; Go PGStore.Begin, RedisStore.Begin (a test fires 32 concurrent claims and expects exactly one Started); Laravel Cache::lock plus a unique constraint. Lock limits (leases, fencing) are covered in Distributed Locking.
Partial failure: a crash between the effect and the record Must-know
In plain words: the dangerous moment is after the charge succeeded but before "completed" was written. If the process dies there, the retry sees "in progress" and nobody knows what happened.
Common misunderstanding: "I wrap everything in a try/catch and write the record in finally." A crash (kill -9, OOM, power loss) never runs finally. The record must not depend on the process surviving.
Definition: a recovery point problem. There are three honest answers:
- Put the side effect and the record in one database transaction: both commit or neither does. This works when the side effect is a write to the same database.
- Make the side effect idempotent itself, by passing a derived key to the provider (Stripe, Adyen) so a re-run changes nothing.
- Use an outbox: write the effect and an event row in one transaction, and let a relay deliver it at-least-once to an idempotent receiver (Transactional Outbox).
Design A (two steps) Design B (one transaction)
1 INSERT key in_progress 1 INSERT key in_progress (own tx, short)
2 call provider: charge (OK) 2 BEGIN
3 *** crash *** 3 INSERT order, ledger rows
4 retry: key in_progress, lease running 4 UPDATE key completed + response
5 after lease: take over, charge AGAIN 5 COMMIT <- crash before: nothing; after: replay| Side effect | Can share the key's transaction? | Strategy |
|---|---|---|
| Rows in the same database | Yes | Same transaction (Go CompleteWith(tx)) |
| Call to a payment provider | No (external) | Derived provider key; record the provider ID afterwards |
| Message to a broker | No | Outbox row in the same transaction |
| Email or SMS | No | Idempotent at the sender, or accept a rare duplicate and log it |
| Write to another microservice's database | No | That service has its own key; saga or outbox |
| Recovery after a crash | Rule |
|---|---|
| Lease expired, same fingerprint | The next request takes the key over and re-runs; safe only if the effect is idempotent or transactional |
| Lease expired, different fingerprint | Do not take over: return 422 or 409 (this page's SQL requires equal fingerprints) |
| Holder returns late after takeover | Complete checks the owner token and fails with ErrLeaseLost |
| Effect done but unknown | Query the provider by the derived key before re-running (Stripe "retries failed or partially failed work to completion" in API v2) |
Real scenario: a transfer between two accounts in the same PostgreSQL database: debit, credit and the key's completed row in one transaction cannot be half done. A card capture through an external PSP cannot, so the derived provider key is the safety net.
Fix / how to use it: Go PGStore.CompleteWith(ctx, tx, ...); Laravel DB::transaction around the controller body plus the key update; outbox details in Transactional Outbox.
Response replay Important
In plain words: on a retry the server returns what it returned the first time.
Common misunderstanding: "Returning 409 Already exists on the retry is the same thing." The first caller got 201 with a body; the retry caller (the same SDK, ignoring the lost response) would now get an error and might treat the operation as failed. AWS calls the right behaviour a "semantically equivalent response" and notes that it lets SDKs retry "under the hood".
Definition: replay returns the stored status code, the stored body and the headers that matter (Content-Type, Location), plus a marker header Idempotent-Replayed: true. This header is a de-facto convention: it is not part of the IETF draft, and the Stripe and Adyen pages read for this chapter do not document it (Adyen echoes the idempotency-key header instead), so document it yourself. Per-request headers (Date, Set-Cookie, rate-limit counters) must not be replayed.
| Question | Recommended answer | Reason |
|---|---|---|
Replay 4xx? | Yes (400 for a validation error is deterministic) | Same request, same answer; client must fix it with a new key |
Replay 5xx? | This page: no, release the claim; Stripe API v1: yes, "including 500 errors" | A 5xx says "outcome unknown", not "outcome decided"; both are valid if documented |
| Replay after the resource was deleted? | Yes, EC2 does ("the least surprising approach") | The key promises the original answer |
| Body larger than a limit | Store a pointer (object storage) or refuse the key | Row bloat |
| Streaming responses | Do not support keys, or store only the final status | Cannot replay a stream |
Add Idempotent-Replayed: true? | Yes | Lets clients and logs distinguish a replay |
1 POST /charges K -> 201 {"id":"ch_1"} (X-Request-Id: req-A)
2 POST /charges K -> 201 {"id":"ch_1"} Idempotent-Replayed: true (X-Request-Id: req-B)Real scenario: a client SDK retried after a read timeout and received a replayed 201; its logs show one logical operation and the server logs show one effect plus one replay.
Fix / how to use it: Go middleware Replay branch; Laravel response($record->response_body, $record->response_code, ...)->header('Idempotent-Replayed', 'true').
Downstream propagation and provider idempotency keys Must-know
In plain words: if your service calls a payment provider on behalf of the client, the provider needs a key too, and it must be the same on every re-run.
Common misunderstanding: "Our idempotency covers it." Your key protects your API. When your handler is re-run (lease takeover, crash recovery), it calls Stripe or Adyen again. Without a stable provider key those are two charges.
Definition: propagate the client's key or, better, derive a stable key per downstream step: sha256(scope + ":" + clientKey + ":charge"). Do not pass the client's key straight through when one client request makes several downstream calls; each step needs its own key or they will collide.
Client K ──▶ Order service (scope c1, K)
├── step 1: Stripe POST /v1/payment_intents Idempotency-Key: derive(c1,K,"intent")
├── step 2: Stripe POST /v1/captures Idempotency-Key: derive(c1,K,"capture")
└── step 3: outbox row (message id = derive(c1,K,"event"))| Provider | How it takes the key | Retention | Notes |
|---|---|---|---|
| Stripe | Header Idempotency-Key | At least 24 h (v1) | Up to 255 chars; v1 saves status and body "after endpoint execution begins" |
| Adyen | Header idempotency-key | 7 to 14 days | Max 64 chars; response header echoes the key; transient-error: true marks retryable races |
| PayPal | Header PayPal-Request-Id | See PayPal docs (not fetched) | Named in the IETF draft's implementation list |
| Square | Body field idempotency_key | See Square docs | Unique string per call; mismatched changes return an error |
| AWS (EC2 and others) | Parameter ClientToken | Resource lifetime plus a margin (EC2) | Mismatch gives IdempotentParameterMismatch |
| Derived-key rule | Why |
|---|---|
| Include scope, client key and step name | Two steps of one request never share a key |
| Stable across re-runs | The whole point |
| Include an "attempt version" only if the business intends a new try | Otherwise a decline can never be retried |
| Stay within the provider's length limit (Adyen 64) | Hash it (hex sha256 truncated, or base32) |
Real scenario: a checkout service that takes the client key K, derives the Stripe key, crashes after Stripe answered, is re-run by the lease takeover and calls Stripe again with the same derived key: Stripe returns the first result, no second charge.
Fix / how to use it: pass the derived key through your HTTP client; see Payment Processing Architecture for the full flow and Service Communication for deadlines and retries.
Natural idempotency: PUT, upsert, conditional write Important
In plain words: some operations are safe to repeat by their own shape; they need no key table.
Common misunderstanding: "Always add a key table." A key table is infrastructure you must run and expire. If the operation can be expressed as "set this to that", the data already does the work.
Definition: natural idempotency means the operation names the final state, not a delta. PUT /users/7/email with the full value, INSERT ... ON CONFLICT (id) DO UPDATE, DELETE, and compare-and-set (UPDATE ... WHERE version = 3) are idempotent. balance = balance + 10 and "append a line item" are not.
| Pattern | Example | Idempotent because | Product detail |
|---|---|---|---|
| PUT replace | PUT /documents/42 with the full body | Same final state | RFC 9110: PUT is idempotent |
| Client-chosen ID | PUT /orders/{uuid} | Same ID = same resource | Client generates the UUID |
| Upsert | INSERT ... ON CONFLICT (id) DO UPDATE | Second run overwrites with the same values | PostgreSQL; MySQL ON DUPLICATE KEY UPDATE |
| Insert or get | INSERT ... ON CONFLICT DO SELECT (documented as "idempotent insert or get or create" in the PostgreSQL 19 documentation; on released versions use DO UPDATE ... RETURNING) | Returns the existing row | PostgreSQL |
| Conditional write | UPDATE accounts SET status='closed' WHERE id=7 AND status='open' | Second run matches 0 rows | Any SQL |
| Version check | UPDATE ... SET v = v + 1 WHERE id = 7 AND v = 3 | A retry fails the check | Optimistic locking |
| Absolute set | SET stock = 40 instead of stock = stock - 1 | Final state, not delta | Beware lost updates |
1 PUT /carts/9/items/sku-5 {"qty":2} -> cart has sku-5 x2 (200)
2 PUT /carts/9/items/sku-5 {"qty":2} -> cart has sku-5 x2 (200) same state
3 POST /carts/9/items {"sku":"sku-5","qty":2} twice -> sku-5 x4 NOT idempotent| Convert a non-idempotent call | Into |
|---|---|
POST /orders | PUT /orders/{client-uuid} |
POST /transfers | Transfer with a client-chosen ID as the primary key |
PATCH balance +10 | A ledger insert with a unique entry_id, balance derived |
Real scenario: "set the user's timezone", "mark the invoice paid by transaction T" (unique on T) need no separate key table.
Fix / how to use it: prefer natural idempotency when the domain allows; fall back to the key table for create-style and relative operations. Optimistic concurrency is in Optimistic vs Pessimistic Locking.
Idempotent consumers: queues and webhooks Important
In plain words: the same idea applies when the "client" is a broker: it delivers at least once, and the consumer must not do the work twice.
Common misunderstanding: "My queue is exactly-once, so the handler is safe." Brokers give at-least-once delivery (see Delivery Guarantees); Kafka's idempotent producer and transactions cover broker-side duplicates only. The handler still needs a key.
Definition: the key is the message ID (or a business ID inside the message); the "response" is usually just "done". The structure is the same: unique insert first, effect second, in one transaction (Idempotent Consumers & the Inbox Pattern).
| Input | Key | Where the dedup record lives |
|---|---|---|
| HTTP API client | Idempotency-Key header | idempotency_keys (this page) |
| Kafka / RabbitMQ / SQS message | Message ID or business event ID | Inbox table with the effect |
| Webhook from a PSP | Event ID in the payload (for example Stripe's evt_...) | Inbox table |
| Scheduled job | Job ID plus run date | Job table |
1 webhook evt_9 arrives -> INSERT inbox(evt_9) -> 1 row -> process, COMMIT
2 provider retries evt_9 -> INSERT inbox(evt_9) -> 0 rows -> ack, do nothingReal scenario: a payment-succeeded webhook retried three times because your endpoint returned 500 once; the order is marked paid once.
Fix / how to use it: same code shape as the API middleware, with the message ID as the key; read Idempotent Consumers & the Inbox Pattern.
Cleanup, TTL and retention Important
In plain words: keys cannot live forever, but they must live at least as long as any client might retry.
Common misunderstanding: "TTL of 5 minutes is plenty because retries are quick." Mobile clients queue requests offline and queues redeliver after hours. Too short a TTL turns a late retry into a new operation. AWS notes the opposite problem: "it’s impractical to retain that knowledge indefinitely" and a long retention can make a new identifier "collide with one used much earlier".
Definition: the TTL (replay window) is a documented promise: "within N hours of the first request, the same key returns the same result; afterwards it counts as a new request."
| TTL | When it fits | Used by |
|---|---|---|
| 24 hours | Online payments with SDK retries | Stripe v1 prunes keys "after they’re at least 24 hours old" |
| 7 to 14 days | Longer retry windows, async partners | Adyen: "valid for a period of 7 to 14 days" |
| Resource lifetime + margin | Resource creation | EC2 RunInstances |
| 30 days or more | Banking batch flows | Design choice; mind storage |
| Cleanup technique | How | Cost |
|---|---|---|
Redis PX / EXPIRE | Automatic | None |
| DynamoDB TTL attribute | Automatic, eventually | None |
DELETE ... WHERE expires_at < now() LIMIT 1000 in a loop | Batch, off-peak | Index on expires_at |
Partition by day and DROP PARTITION | Instant | Partitioning setup (Partitioning & Sharding in PostgreSQL) |
Laravel Prunable + model:prune | Scheduled | Chunked deletes |
| Edge case | Rule |
|---|---|
| Row expired while a request still runs | Complete only if owner matches and row exists; otherwise ErrLeaseLost |
| Retry after expiry | Runs as new: say so in the docs |
| Clock skew between app servers | Use the database now() (the SQL here does) |
Real scenario: at 1,000 POSTs per second with a 24-hour TTL the table holds about 86 million rows; a nightly DELETE of that size bloats the table, so partition by day instead.
Fix / how to use it: SQL cleanup statement; Laravel prunable(); Redis TTL set in Complete.
Observability Good to know
In plain words: measure how many requests are first runs, replays, conflicts and mismatches; each number tells a story.
Common misunderstanding: "If it works, there is nothing to watch." A rising conflict rate means clients retry too aggressively; a rising mismatch rate means a client bug; zero replays on a flaky network means keys are not reused.
Definition: emit a counter per outcome, log the key (not the body), and put the key into trace attributes (Observability).
| Metric | Meaning | Alert when |
|---|---|---|
idempotency_started_total | First runs | Baseline |
idempotency_replayed_total | Retries answered from the store | Sudden spike (network or deploy issue) |
idempotency_conflict_total (409) | Duplicates during a run | High ratio: retry storm or slow handler |
idempotency_mismatch_total (422) | Key reuse with another body | Any sustained rate: client bug |
idempotency_missing_total (400) | No key on a required endpoint | New client version regression |
idempotency_store_errors_total (503) | Store unavailable | Any (fail closed means errors) |
Rows past expires_at | Cleanup lag | Growing |
| In-progress older than the lease | Crashed holders | Non-zero for long |
| Log field | Why |
|---|---|
idempotency_key, scope | Join first run, replays, support tickets |
outcome (started, replay, busy, mismatch) | One query answers "was it a retry?" |
request_id | Different per attempt |
Real scenario: a mobile release regenerates keys per retry; the replay rate drops to zero and double-charge tickets arrive.
Fix / how to use it: wrap Begin in the middleware with a counter by Outcome; log the same outcome in Laravel.
How the products do it Important
In plain words: every serious payment API has a key; the details differ in where the key goes, how long it lives and what a failure replays.
Common misunderstanding: "They all work like Stripe." They differ on 5xx replay, TTL, header or body field, and mismatch status.
Definition: the table lists documented behaviour only.
| Product | Key location | Length | TTL | Concurrent duplicate | Different payload | Failures |
|---|---|---|---|---|---|---|
| Stripe API v1 | Header Idempotency-Key | up to 255 | Pruned after at least 24 h | No saved result for a conflicting concurrent request; retry | Error | Replays the first result "including 500 errors" |
| Stripe API v2 | Same | Same | Not stated on the page | Same | Same | Retries "failed or partially failed work to completion when possible" |
| Adyen | Header idempotency-key | max 64 | 7 to 14 days | 422 or 409, code 704, header transient-error: true | Not detailed on the page | Store outage: 503 code 703 |
| Square | Body idempotency_key | unique string | See Square docs | See Square docs | Error indicating prior use | Same key, same response |
| PayPal | Header PayPal-Request-Id | See PayPal docs | See PayPal docs | See PayPal docs | See PayPal docs | Listed in the IETF draft |
| AWS EC2 | Parameter ClientToken | up to 64 ASCII | Resource lifetime + margin | Same token, retry | IdempotentParameterMismatch | Semantically equivalent response |
| IETF draft | Header Idempotency-Key | Not fixed | Resource documents it | 409 | 422 | Follow the resource docs |
| Operational detail | Stripe | Adyen | AWS |
|---|---|---|---|
| GET/DELETE | Do not send keys | PUT/GET/DELETE idempotent by definition | Many actions idempotent by default (for example TerminateInstances) |
| SDK support | Ruby library retries with the key, backoff and jitter | Use exponential backoff | SDK and CLI generate and reuse tokens |
| Security | Do not use sensitive data as keys | Use UUIDv4; "prevent two API credentials under the same account from accessing each others responses" | Idempotent session keyed by caller and token |
Real scenario: choosing a PSP: if you need replay of declined transactions, check whether it stores 4xx; if you need 14-day retries, check Adyen's window.
Fix / how to use it: build your own API to the draft; call providers with the keys they document; read their pages before relying on a number.
Mechanics
The exact request flow
1 validate Idempotency-Key format (400) before any storage access
2 resolve scope from authentication (401)
3 read body (cap size, 413), compute fingerprint
4 Begin(scope, key, fp):
insert row (scope,key) status in_progress, owner token, lease -> Started
conflict: same fp, completed -> Replay
conflict: same fp, in_progress, lease valid -> Busy (409)
conflict: same fp, in_progress, lease expired -> take over (Started)
conflict: different fp -> Mismatch (422)
5 Started: run handler; record status code and body
6 2xx/3xx/4xx -> Complete (owner must match); 5xx/panic -> Abandon
7 Replay: write stored status, headers, body + Idempotent-Replayed: trueStatus codes and what the client does
| Code | Meaning here | Client action |
|---|---|---|
200, 201 (first) | Done | Use it |
200, 201 + Idempotent-Replayed: true | Replay of the first answer | Use it; it is the same operation |
400 | Key missing or malformed | Fix the request; new key not needed |
401 | No scope (unauthenticated) | Authenticate |
409 | Same key still running | Wait (Retry-After) and retry with the same key |
413 | Body above the cap | Shrink |
422 | Key reused with a different request | Use a new key for the new intent |
429 | Rate limit before the key layer | Back off (Rate Limiting) |
500, 502, 503, 504 | Outcome unknown or store down | Retry with the same key, with backoff and jitter |
Lease arithmetic
The lease is how long a crashed holder blocks a retry. Choose it above the slowest legitimate handler: p99.9 of the handler plus the downstream timeouts.
| Parameter | Value in the code | Reason |
|---|---|---|
Lease (Config.Lease) | 60 s | Longer than a 30 s provider timeout plus margin |
Replay TTL (Config.TTL) | 24 h | Stripe's minimum pruning age |
Redis lock PX | the lease in ms | Auto-expires if the holder dies |
| Max body | 1 MiB | Bounded memory |
| Client retry interval | 1 s, 2 s, 4 s with jitter | Longer than the Retry-After hint |
If the handler can outlive the lease, a second request takes over while the first still runs: two runs. Either raise the lease, renew it, or make the effect idempotent (derived provider key).
Error messages you will see
| Where | Text or code | Meaning |
|---|---|---|
| PostgreSQL | ERROR: duplicate key value violates unique constraint "idempotency_keys_pkey", SQLSTATE 23505 | Lost the claim race (when not using ON CONFLICT) |
| MySQL / InnoDB | ERROR 1062 (23000): Duplicate entry | Same |
| Redis | (nil) reply to SET ... NX | Key exists |
| DynamoDB | ConditionalCheckFailedException | Key exists |
| Laravel | Illuminate\Database\UniqueConstraintViolationException | Unique constraint lost the race |
| Adyen | 704: "request already processed or in progress"; 703: "required resource temporarily unavailable" | Duplicate in flight; store down |
| EC2 | IdempotentParameterMismatch | Same token, different parameters |
| Go | idem.ErrLeaseLost | Holder was replaced; do not store |
Redis SET options used
| Option | Effect (from the Redis SET page) |
|---|---|
NX | "Only set the key if it does not already exist." |
PX milliseconds | Expiry in milliseconds |
EX seconds | Expiry in seconds |
GET | Return the old value (not used here) |
XX | Only set if exists (renew a lease) |
Go
The module is academy/api-idempotency. Package idem has the Store contract, a fingerprint, an HTTP middleware and three stores (memory, PostgreSQL through database/sql, Redis through go-redis). The tests run one contract suite against the memory store, a real Redis protocol implementation (miniredis) and, when IDEM_PG_DSN is set, PostgreSQL.
Before
A check-then-insert "dedup": it reads the flag, does the slow work, then writes the flag. Twenty concurrent retries all see "not seen".
// Before: check-then-insert. Two retries that arrive together both see
// "not exists" and both charge. Bad design, not broken code.
package before
import "sync"
type Charger struct {
mu sync.Mutex
seen map[string]bool
Charges int
}
func NewCharger() *Charger { return &Charger{seen: map[string]bool{}} }
// Charge reads the flag, does the slow work, then writes the flag.
func (c *Charger) Charge(key string, slow func()) {
c.mu.Lock()
exists := c.seen[key]
c.mu.Unlock()
if exists {
return
}
slow() // the card network call
c.mu.Lock()
c.seen[key] = true
c.Charges++
c.mu.Unlock()
}After
The store contract and shared types. Begin is the only place where duplicates are told apart; Complete and Abandon check the owner token so a replaced holder cannot overwrite the new run.
// Package idem implements server-side idempotency keys for non-idempotent
// HTTP methods: claim the key atomically, run the handler once, store the
// response, replay it for retries.
package idem
import (
"context"
"net/http"
"time"
)
// Status is the lifecycle state of a key.
type Status string
const (
InProgress Status = "in_progress"
Completed Status = "completed"
)
// Record is what the store keeps per (scope, key).
type Record struct {
Fingerprint string
Status Status
Code int
Header http.Header
Body []byte
}
// Outcome tells the middleware what Begin decided.
type Outcome int
const (
// Started: this caller owns the key and must run the handler.
Started Outcome = iota
// Replay: the key completed earlier with the same fingerprint.
Replay
// Busy: another request holds the key right now (409).
Busy
// Mismatch: the key exists with a different fingerprint (422).
Mismatch
)
// BeginResult is the answer of Store.Begin.
type BeginResult struct {
Outcome Outcome
Owner string // lease token, set when Outcome == Started
Record Record // set when Outcome == Replay
}
// Store is the storage contract. Every method must be atomic: Begin is the
// only place where two concurrent duplicates are told apart.
type Store interface {
// Begin atomically claims (scope, key) or reports why it cannot.
Begin(ctx context.Context, scope, key, fingerprint string) (BeginResult, error)
// Complete stores the response, but only if owner still holds the lease.
Complete(ctx context.Context, scope, key, owner string, rec Record) error
// Abandon releases the claim without storing a response (5xx, panic).
Abandon(ctx context.Context, scope, key, owner string) error
}
// Config holds the knobs shared by the stores.
type Config struct {
TTL time.Duration // how long a completed response is replayable
Lease time.Duration // how long an in-progress claim blocks duplicates
Now func() time.Time
}
func (c Config) now() time.Time {
if c.Now != nil {
return c.Now()
}
return time.Now()
}
// DefaultConfig returns 24 h replay and a 60 s in-progress lease.
func DefaultConfig() Config {
return Config{TTL: 24 * time.Hour, Lease: 60 * time.Second}
}Fingerprint and key validation.
package idem
import (
"crypto/sha256"
"encoding/hex"
"regexp"
)
// keyPattern is the published key format: 16 to 255 characters from a safe
// alphabet. Validating before any lookup blocks injection and log forging.
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{16,255}$`)
// ValidKey reports whether k matches the published key format.
func ValidKey(k string) bool { return keyPattern.MatchString(k) }
// Fingerprint hashes what makes two requests "the same request": method,
// path (with query) and body. Length prefixes stop "ab"+"c" colliding with
// "a"+"bc". It does not canonicalise JSON: a client that re-serialises the
// same payload with different key order gets a mismatch, which is the safe
// failure.
func Fingerprint(method, pathAndQuery string, body []byte) string {
h := sha256.New()
for _, part := range [][]byte{[]byte(method), []byte(pathAndQuery), body} {
var n [8]byte
l := uint64(len(part))
for i := 0; i < 8; i++ {
n[i] = byte(l >> (8 * i))
}
h.Write(n[:])
h.Write(part)
}
return hex.EncodeToString(h.Sum(nil))
}The HTTP middleware. Validates the key before storage, buffers the body, maps outcomes to 409, 422, replay and 400, abandons on 5xx or panic, fails closed with 503 if the store is down.
package idem
import (
"bytes"
"io"
"net/http"
"strconv"
)
// Options configures Middleware.
type Options struct {
Store Store
// Scope returns who owns the key, for example the authenticated client
// ID. An empty scope means "not authenticated": the request is rejected.
Scope func(*http.Request) string
// Required makes a missing Idempotency-Key a 400 instead of pass-through.
Required bool
// MaxBody caps what is buffered for fingerprinting and replay.
MaxBody int64
}
// Middleware wraps next. Only POST and PATCH are guarded; GET, PUT and
// DELETE are idempotent by definition (RFC 9110, section 9.2.2).
func Middleware(o Options) func(http.Handler) http.Handler {
if o.MaxBody == 0 {
o.MaxBody = 1 << 20
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost && r.Method != http.MethodPatch {
next.ServeHTTP(w, r)
return
}
key := r.Header.Get("Idempotency-Key")
if key == "" {
if o.Required {
problem(w, http.StatusBadRequest, "Idempotency-Key is missing")
return
}
next.ServeHTTP(w, r)
return
}
if !ValidKey(key) {
problem(w, http.StatusBadRequest, "Idempotency-Key has an invalid format")
return
}
scope := o.Scope(r)
if scope == "" {
problem(w, http.StatusUnauthorized, "authentication required")
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, o.MaxBody+1))
if err != nil || int64(len(body)) > o.MaxBody {
problem(w, http.StatusRequestEntityTooLarge, "request body too large")
return
}
r.Body = io.NopCloser(bytes.NewReader(body))
fp := Fingerprint(r.Method, r.URL.RequestURI(), body)
res, err := o.Store.Begin(r.Context(), scope, key, fp)
if err != nil {
// Fail closed: without the store we cannot promise "once".
problem(w, http.StatusServiceUnavailable, "idempotency store unavailable")
return
}
switch res.Outcome {
case Replay:
for k, vs := range res.Record.Header {
for _, v := range vs {
w.Header().Add(k, v)
}
}
w.Header().Set("Idempotent-Replayed", "true")
w.WriteHeader(res.Record.Code)
_, _ = w.Write(res.Record.Body)
case Busy:
w.Header().Set("Retry-After", "1")
problem(w, http.StatusConflict, "a request with this Idempotency-Key is in progress")
case Mismatch:
problem(w, http.StatusUnprocessableEntity, "Idempotency-Key was already used with a different request")
case Started:
run(o, next, w, r, scope, key, res.Owner)
}
})
}
}
func run(o Options, next http.Handler, w http.ResponseWriter, r *http.Request, scope, key, owner string) {
rec := &recorder{ResponseWriter: w, code: http.StatusOK}
done := false
defer func() {
if !done { // handler panicked: free the key so a retry can run
_ = o.Store.Abandon(r.Context(), scope, key, owner)
}
}()
next.ServeHTTP(rec, r)
done = true
if rec.code >= 500 {
// A 5xx means "unknown outcome": do not cache it, let the retry run.
_ = o.Store.Abandon(r.Context(), scope, key, owner)
return
}
stored := Record{Status: Completed, Code: rec.code, Header: rec.kept(), Body: rec.buf.Bytes()}
_ = o.Store.Complete(r.Context(), scope, key, owner, stored)
}
type recorder struct {
http.ResponseWriter
code int
buf bytes.Buffer
}
func (r *recorder) WriteHeader(c int) { r.code = c; r.ResponseWriter.WriteHeader(c) }
func (r *recorder) Write(b []byte) (int, error) {
r.buf.Write(b)
return r.ResponseWriter.Write(b)
}
// kept returns the headers worth replaying; hop-by-hop and per-request
// headers (Date, Set-Cookie) are deliberately left out.
func (r *recorder) kept() http.Header {
h := http.Header{}
for _, name := range []string{"Content-Type", "Location"} {
if v := r.Header().Get(name); v != "" {
h.Set(name, v)
}
}
return h
}
func problem(w http.ResponseWriter, code int, title string) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(code)
_, _ = w.Write([]byte(`{"status":` + strconv.Itoa(code) + `,"title":"` + title + `"}`))
}PostgreSQL store. One INSERT ... ON CONFLICT DO UPDATE ... WHERE statement claims a new key or takes over an expired lease; CompleteWith takes a *sql.Tx so the response is stored in the same transaction as the business rows.
package idem
import (
"context"
"database/sql"
"encoding/json"
"net/http"
)
// PGStore keeps keys in the idempotency_keys table (see sql/schema.sql).
// The primary key (scope, key) is the lock; time is taken from the database
// clock (now()) so application servers with skewed clocks agree.
type PGStore struct {
DB *sql.DB
Cfg Config
}
// Execer is satisfied by *sql.DB and *sql.Tx, so Complete can run inside the
// same transaction as the business write.
type Execer interface {
ExecContext(ctx context.Context, q string, args ...any) (sql.Result, error)
}
const pgClaim = `
INSERT INTO idempotency_keys (scope, key, fingerprint, status, owner, locked_until, expires_at)
VALUES ($1, $2, $3, 'in_progress', $4, now() + make_interval(secs => $5), now() + make_interval(secs => $6))
ON CONFLICT (scope, key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint, status = 'in_progress', owner = EXCLUDED.owner,
locked_until = EXCLUDED.locked_until, expires_at = EXCLUDED.expires_at,
response_code = NULL, response_headers = NULL, response_body = NULL
WHERE idempotency_keys.expires_at <= now()
OR (idempotency_keys.status = 'in_progress'
AND idempotency_keys.locked_until <= now()
AND idempotency_keys.fingerprint = EXCLUDED.fingerprint)
RETURNING owner`
const pgRead = `
SELECT fingerprint, status, COALESCE(response_code, 0), response_headers, response_body
FROM idempotency_keys WHERE scope = $1 AND key = $2`
const pgComplete = `
UPDATE idempotency_keys
SET status = 'completed', response_code = $4, response_headers = $5, response_body = $6,
locked_until = NULL, expires_at = now() + make_interval(secs => $7)
WHERE scope = $1 AND key = $2 AND owner = $3 AND status = 'in_progress'`
const pgAbandon = `
DELETE FROM idempotency_keys
WHERE scope = $1 AND key = $2 AND owner = $3 AND status = 'in_progress'`
func (s *PGStore) Begin(ctx context.Context, scope, key, fp string) (BeginResult, error) {
owner := token()
// Two attempts: the row can be deleted between the claim and the read.
for i := 0; i < 2; i++ {
var got string
err := s.DB.QueryRowContext(ctx, pgClaim, scope, key, fp, owner,
s.Cfg.Lease.Seconds(), s.Cfg.TTL.Seconds()).Scan(&got)
if err == nil {
return BeginResult{Outcome: Started, Owner: owner}, nil
}
if err != sql.ErrNoRows {
return BeginResult{}, err
}
var (
have, status string
code int
hdr, body []byte
)
err = s.DB.QueryRowContext(ctx, pgRead, scope, key).Scan(&have, &status, &code, &hdr, &body)
if err == sql.ErrNoRows {
continue
}
if err != nil {
return BeginResult{}, err
}
switch {
case have != fp:
return BeginResult{Outcome: Mismatch}, nil
case Status(status) == Completed:
h := http.Header{}
_ = json.Unmarshal(hdr, &h)
return BeginResult{Outcome: Replay, Record: Record{Fingerprint: have, Status: Completed, Code: code, Header: h, Body: body}}, nil
default:
return BeginResult{Outcome: Busy}, nil
}
}
return BeginResult{Outcome: Busy}, nil
}
func (s *PGStore) Complete(ctx context.Context, scope, key, owner string, rec Record) error {
return s.CompleteWith(ctx, s.DB, scope, key, owner, rec)
}
// CompleteWith stores the response through ex. Pass the *sql.Tx that also
// wrote the business rows: the effect and its idempotency record then commit
// or roll back together, and there is no crash window between them.
func (s *PGStore) CompleteWith(ctx context.Context, ex Execer, scope, key, owner string, rec Record) error {
hdr, err := json.Marshal(rec.Header)
if err != nil {
return err
}
res, err := ex.ExecContext(ctx, pgComplete, scope, key, owner, rec.Code, hdr, rec.Body, s.Cfg.TTL.Seconds())
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrLeaseLost
}
return nil
}
func (s *PGStore) Abandon(ctx context.Context, scope, key, owner string) error {
_, err := s.DB.ExecContext(ctx, pgAbandon, scope, key, owner)
return err
}Redis store. A lock key (SET NX PX) for the lease and a result key for the replay, in one hash slot; completion and release are Lua scripts that compare the owner token first.
package idem
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"strings"
"github.com/redis/go-redis/v9"
)
// RedisStore uses two keys per idempotency key, both in one hash slot:
//
// idem:{h}:lock "owner|fingerprint" SET NX PX lease (in progress)
// idem:{h}:res JSON record SET PX ttl (completed)
//
// Redis is fast but its durability is weaker than a SQL table: after a
// failover without the write, a completed key can vanish and a retry runs
// the work again. Use it where the side effect is itself idempotent or the
// gap is accepted.
type RedisStore struct {
RDB redis.UniversalClient
Cfg Config
}
var completeScript = redis.NewScript(`
local v = redis.call('GET', KEYS[1])
if v and string.sub(v, 1, #ARGV[1]) == ARGV[1] then
redis.call('SET', KEYS[2], ARGV[2], 'PX', ARGV[3])
redis.call('DEL', KEYS[1])
return 1
end
return 0`)
var releaseScript = redis.NewScript(`
local v = redis.call('GET', KEYS[1])
if v and string.sub(v, 1, #ARGV[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0`)
type stored struct {
Fingerprint string `json:"fp"`
Code int `json:"code"`
Header http.Header `json:"header"`
Body []byte `json:"body"`
}
func keys(scope, key string) (lock, res string) {
sum := sha256.Sum256([]byte(scope + "\x00" + key))
h := hex.EncodeToString(sum[:])
return "idem:{" + h + "}:lock", "idem:{" + h + "}:res"
}
func (s *RedisStore) Begin(ctx context.Context, scope, key, fp string) (BeginResult, error) {
lock, res := keys(scope, key)
if r, done, err := s.replay(ctx, res, fp); err != nil || done {
return r, err
}
owner := token()
ok, err := s.RDB.SetNX(ctx, lock, owner+"|"+fp, s.Cfg.Lease).Result()
if err != nil {
return BeginResult{}, err
}
if !ok {
v, err := s.RDB.Get(ctx, lock).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return BeginResult{}, err
}
if i := strings.IndexByte(v, '|'); i >= 0 && v[i+1:] != fp {
return BeginResult{Outcome: Mismatch}, nil
}
return BeginResult{Outcome: Busy}, nil
}
// The previous holder may have completed between our two reads.
if r, done, err := s.replay(ctx, res, fp); err != nil || done {
_, _ = releaseScript.Run(ctx, s.RDB, []string{lock}, owner+"|").Result()
return r, err
}
return BeginResult{Outcome: Started, Owner: owner}, nil
}
func (s *RedisStore) replay(ctx context.Context, res, fp string) (BeginResult, bool, error) {
raw, err := s.RDB.Get(ctx, res).Bytes()
if errors.Is(err, redis.Nil) {
return BeginResult{}, false, nil
}
if err != nil {
return BeginResult{}, true, err
}
var st stored
if err := json.Unmarshal(raw, &st); err != nil {
return BeginResult{}, true, err
}
if st.Fingerprint != fp {
return BeginResult{Outcome: Mismatch}, true, nil
}
return BeginResult{Outcome: Replay, Record: Record{Fingerprint: fp, Status: Completed, Code: st.Code, Header: st.Header, Body: st.Body}}, true, nil
}
func (s *RedisStore) Complete(ctx context.Context, scope, key, owner string, rec Record) error {
lock, res := keys(scope, key)
// The fingerprint was written into the lock value; read it back.
v, err := s.RDB.Get(ctx, lock).Result()
if errors.Is(err, redis.Nil) {
return ErrLeaseLost
}
if err != nil {
return err
}
fp := v[strings.IndexByte(v, '|')+1:]
raw, err := json.Marshal(stored{Fingerprint: fp, Code: rec.Code, Header: rec.Header, Body: rec.Body})
if err != nil {
return err
}
n, err := completeScript.Run(ctx, s.RDB, []string{lock, res}, owner+"|", raw, s.Cfg.TTL.Milliseconds()).Int()
if err != nil {
return err
}
if n == 0 {
return ErrLeaseLost
}
return nil
}
func (s *RedisStore) Abandon(ctx context.Context, scope, key, owner string) error {
lock, _ := keys(scope, key)
_, err := releaseScript.Run(ctx, s.RDB, []string{lock}, owner+"|").Result()
return err
}In-memory store (the reference implementation, used by the demo and middleware tests):
package idem
import (
"context"
"crypto/rand"
"encoding/hex"
"sync"
"time"
)
// MemStore is the reference implementation of the Store contract: one mutex
// plays the role of the database's unique index. Use it in tests and demos.
type MemStore struct {
cfg Config
mu sync.Mutex
m map[string]*entry
}
type entry struct {
rec Record
owner string
expires time.Time // lease end while in progress, replay end once completed
}
// NewMemStore returns an empty in-memory store.
func NewMemStore(cfg Config) *MemStore { return &MemStore{cfg: cfg, m: map[string]*entry{}} }
func token() string {
var b [16]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}
func (s *MemStore) Begin(_ context.Context, scope, key, fp string) (BeginResult, error) {
s.mu.Lock()
defer s.mu.Unlock()
id, now := scope+"\x00"+key, s.cfg.now()
e, ok := s.m[id]
if ok && !now.Before(e.expires) { // expired lease or expired replay
delete(s.m, id)
ok = false
}
if !ok {
owner := token()
s.m[id] = &entry{rec: Record{Fingerprint: fp, Status: InProgress}, owner: owner, expires: now.Add(s.cfg.Lease)}
return BeginResult{Outcome: Started, Owner: owner}, nil
}
if e.rec.Fingerprint != fp {
return BeginResult{Outcome: Mismatch}, nil
}
if e.rec.Status == Completed {
return BeginResult{Outcome: Replay, Record: e.rec}, nil
}
return BeginResult{Outcome: Busy}, nil
}
func (s *MemStore) Complete(_ context.Context, scope, key, owner string, rec Record) error {
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.m[scope+"\x00"+key]
if !ok || e.owner != owner {
return ErrLeaseLost
}
rec.Fingerprint = e.rec.Fingerprint
e.rec, e.expires = rec, s.cfg.now().Add(s.cfg.TTL)
return nil
}
func (s *MemStore) Abandon(_ context.Context, scope, key, owner string) error {
s.mu.Lock()
defer s.mu.Unlock()
if e, ok := s.m[scope+"\x00"+key]; ok && e.owner == owner && e.rec.Status == InProgress {
delete(s.m, scope+"\x00"+key)
}
return nil
}package idem
import "errors"
// ErrLeaseLost means the caller no longer owns the key: its lease expired
// and another request took over. The caller must not store a response.
var ErrLeaseLost = errors.New("idem: lease lost")Tests. The store contract (replay, busy, mismatch, scope isolation, owner check, abandon, lease takeover, 32 concurrent claims with exactly one winner) and the middleware behaviours (replay without rerun, 422, 400, 5xx not cached, panic frees the key, per-client isolation, 25 concurrent duplicates give one 201 and 24 409).
package idem
import (
"context"
"database/sql"
"net/http"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
_ "github.com/jackc/pgx/v5/stdlib"
)
// storeContract is the behaviour every Store must have. It runs against the
// in-memory store, Redis (miniredis) and, when IDEM_PG_DSN is set, PostgreSQL.
func storeContract(t *testing.T, s Store, advance func(time.Duration)) {
ctx := context.Background()
fp := Fingerprint("POST", "/charges", []byte(`{"amount":2000}`))
first, err := s.Begin(ctx, "c1", "key-0123456789abcdef", fp)
if err != nil || first.Outcome != Started || first.Owner == "" {
t.Fatalf("first Begin = %+v, %v; want Started", first, err)
}
if r, _ := s.Begin(ctx, "c1", "key-0123456789abcdef", fp); r.Outcome != Busy {
t.Fatalf("duplicate while in progress = %v; want Busy", r.Outcome)
}
other := Fingerprint("POST", "/charges", []byte(`{"amount":9999}`))
if r, _ := s.Begin(ctx, "c1", "key-0123456789abcdef", other); r.Outcome != Mismatch {
t.Fatalf("different payload = %v; want Mismatch", r.Outcome)
}
if r, _ := s.Begin(ctx, "c2", "key-0123456789abcdef", fp); r.Outcome != Started {
t.Fatalf("same key, other scope = %v; want Started (scopes are isolated)", r.Outcome)
}
if err := s.Complete(ctx, "c1", "key-0123456789abcdef", "not-the-owner", Record{Code: 201}); err == nil {
t.Fatal("Complete by a non-owner must fail")
}
rec := Record{Status: Completed, Code: 201, Header: http.Header{"Content-Type": {"application/json"}}, Body: []byte(`{"id":"ch_1"}`)}
if err := s.Complete(ctx, "c1", "key-0123456789abcdef", first.Owner, rec); err != nil {
t.Fatalf("Complete: %v", err)
}
r, _ := s.Begin(ctx, "c1", "key-0123456789abcdef", fp)
if r.Outcome != Replay || r.Record.Code != 201 || string(r.Record.Body) != `{"id":"ch_1"}` {
t.Fatalf("after Complete = %+v; want Replay of the stored response", r)
}
// Abandon frees the key for a clean retry.
a, _ := s.Begin(ctx, "c1", "abandon-0123456789abc", fp)
_ = s.Abandon(ctx, "c1", "abandon-0123456789abc", a.Owner)
if r, _ := s.Begin(ctx, "c1", "abandon-0123456789abc", fp); r.Outcome != Started {
t.Fatalf("after Abandon = %v; want Started", r.Outcome)
}
// A crashed holder: the lease expires and the same request takes over.
c, _ := s.Begin(ctx, "c1", "crash-0123456789abcd", fp)
advance(2 * time.Minute)
d, _ := s.Begin(ctx, "c1", "crash-0123456789abcd", fp)
if d.Outcome != Started || d.Owner == c.Owner {
t.Fatalf("after lease expiry = %+v; want a new Started owner", d)
}
if err := s.Complete(ctx, "c1", "crash-0123456789abcd", c.Owner, rec); err == nil {
t.Fatal("the crashed holder must not be able to complete after takeover")
}
// Exactly one winner among many concurrent claims.
var started atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 32; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if r, err := s.Begin(ctx, "c1", "race-0123456789abcdef", fp); err == nil && r.Outcome == Started {
started.Add(1)
}
}()
}
wg.Wait()
if started.Load() != 1 {
t.Fatalf("%d concurrent claims started; want exactly 1", started.Load())
}
}
func TestMemStoreContract(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
var mu sync.Mutex
cfg := DefaultConfig()
cfg.Now = func() time.Time { mu.Lock(); defer mu.Unlock(); return now }
storeContract(t, NewMemStore(cfg), func(d time.Duration) { mu.Lock(); now = now.Add(d); mu.Unlock() })
}
func TestRedisStoreContract(t *testing.T) {
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
s := &RedisStore{RDB: rdb, Cfg: DefaultConfig()}
storeContract(t, s, func(d time.Duration) { mr.FastForward(d) })
}
func TestPGStoreContract(t *testing.T) {
dsn := os.Getenv("IDEM_PG_DSN")
if dsn == "" {
t.Skip("set IDEM_PG_DSN (and load sql/schema.sql) to run against PostgreSQL")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
cfg := Config{TTL: time.Hour, Lease: 1 * time.Second}
s := &PGStore{DB: db, Cfg: cfg}
// PostgreSQL uses the database clock, so "advance" really sleeps.
storeContract(t, s, func(d time.Duration) { time.Sleep(1200 * time.Millisecond) })
}package idem
import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func newHandler(calls *atomic.Int32, code int, delay time.Duration) http.Handler {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
time.Sleep(delay)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Set-Cookie", "session=secret")
w.WriteHeader(code)
_, _ = w.Write([]byte(`{"ok":true}`))
})
return Middleware(Options{
Store: NewMemStore(DefaultConfig()),
Scope: func(r *http.Request) string { return r.Header.Get("X-Client") },
Required: true,
})(h)
}
func post(h http.Handler, key, client, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/charges", strings.NewReader(body))
if key != "" {
req.Header.Set("Idempotency-Key", key)
}
req.Header.Set("X-Client", client)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
return rr
}
const k1 = "order-1001-charge-attempt"
func TestReplayReturnsStoredResponseWithoutRerunning(t *testing.T) {
var calls atomic.Int32
h := newHandler(&calls, http.StatusCreated, 0)
first := post(h, k1, "c1", `{"amount":2000}`)
second := post(h, k1, "c1", `{"amount":2000}`)
if calls.Load() != 1 {
t.Fatalf("handler ran %d times; want 1", calls.Load())
}
if second.Code != first.Code || second.Body.String() != first.Body.String() {
t.Fatalf("replay differs: %d %q vs %d %q", second.Code, second.Body, first.Code, first.Body)
}
if second.Header().Get("Idempotent-Replayed") != "true" || first.Header().Get("Idempotent-Replayed") != "" {
t.Fatal("only the replay carries Idempotent-Replayed: true")
}
if second.Header().Get("Set-Cookie") != "" {
t.Fatal("per-request headers such as Set-Cookie must not be replayed")
}
}
func TestMismatchedPayloadIs422AndDoesNotRun(t *testing.T) {
var calls atomic.Int32
h := newHandler(&calls, http.StatusCreated, 0)
post(h, k1, "c1", `{"amount":2000}`)
r := post(h, k1, "c1", `{"amount":9999}`)
if r.Code != http.StatusUnprocessableEntity || calls.Load() != 1 {
t.Fatalf("got %d with %d calls; want 422 and 1 call", r.Code, calls.Load())
}
}
func TestMissingAndInvalidKey(t *testing.T) {
var calls atomic.Int32
h := newHandler(&calls, http.StatusCreated, 0)
if r := post(h, "", "c1", `{}`); r.Code != http.StatusBadRequest {
t.Fatalf("missing key = %d; want 400", r.Code)
}
if r := post(h, "short", "c1", `{}`); r.Code != http.StatusBadRequest {
t.Fatalf("short key = %d; want 400", r.Code)
}
if r := post(h, "bad key with spaces and \x01 control", "c1", `{}`); r.Code != http.StatusBadRequest {
t.Fatalf("bad characters = %d; want 400", r.Code)
}
if calls.Load() != 0 {
t.Fatal("handler must not run for a rejected key")
}
}
func TestFiveHundredIsNotCachedSoRetryRuns(t *testing.T) {
var calls atomic.Int32
h := newHandler(&calls, http.StatusInternalServerError, 0)
post(h, k1, "c1", `{}`)
post(h, k1, "c1", `{}`)
if calls.Load() != 2 {
t.Fatalf("handler ran %d times; want 2 (5xx is abandoned, not stored)", calls.Load())
}
}
func TestPanicFreesTheKey(t *testing.T) {
var calls atomic.Int32
h := Middleware(Options{
Store: NewMemStore(DefaultConfig()), Required: true,
Scope: func(r *http.Request) string { return "c1" },
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 {
panic("boom")
}
w.WriteHeader(http.StatusCreated)
}))
func() {
defer func() { _ = recover() }()
post(h, k1, "c1", `{}`)
}()
if r := post(h, k1, "c1", `{}`); r.Code != http.StatusCreated {
t.Fatalf("retry after panic = %d; want 201", r.Code)
}
}
func TestSameKeyDifferentClientsDoNotCollide(t *testing.T) {
var calls atomic.Int32
h := newHandler(&calls, http.StatusCreated, 0)
post(h, k1, "c1", `{}`)
r := post(h, k1, "c2", `{}`)
if calls.Load() != 2 || r.Header().Get("Idempotent-Replayed") != "" {
t.Fatal("client c2 must not see client c1's response")
}
}
func TestConcurrentDuplicatesRunOnce(t *testing.T) {
var calls atomic.Int32
h := newHandler(&calls, http.StatusCreated, 30*time.Millisecond)
var wg sync.WaitGroup
var created, conflict atomic.Int32
for i := 0; i < 25; i++ {
wg.Add(1)
go func() {
defer wg.Done()
switch post(h, k1, "c1", `{"amount":2000}`).Code {
case http.StatusCreated:
created.Add(1)
case http.StatusConflict:
conflict.Add(1)
}
}()
}
wg.Wait()
if calls.Load() != 1 || created.Load() != 1 || conflict.Load() != 24 {
t.Fatalf("calls=%d created=%d conflict=%d; want 1, 1, 24", calls.Load(), created.Load(), conflict.Load())
}
}
func TestGetIsNotGuarded(t *testing.T) {
var calls atomic.Int32
h := newHandler(&calls, http.StatusOK, 0)
for i := 0; i < 2; i++ {
req := httptest.NewRequest(http.MethodGet, "/charges/1", nil)
h.ServeHTTP(httptest.NewRecorder(), req)
}
if calls.Load() != 2 {
t.Fatal("GET passes straight through")
}
}
func TestFingerprintBoundaries(t *testing.T) {
if Fingerprint("POST", "/a", []byte("bc")) == Fingerprint("POST", "/ab", []byte("c")) {
t.Fatal("length prefixes must stop field-boundary collisions")
}
}Demo program (runs in a single process; output in the lab):
// demo fires N concurrent retries of one POST at a naive handler and at the
// idempotent middleware and prints how many charges each performed.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"time"
"academy/api-idempotency/before"
"academy/api-idempotency/idem"
)
func main() {
const retries = 20
naive := before.NewCharger()
var wg sync.WaitGroup
for i := 0; i < retries; i++ {
wg.Add(1)
go func() {
defer wg.Done()
naive.Charge("k", func() { time.Sleep(20 * time.Millisecond) })
}()
}
wg.Wait()
fmt.Printf("naive check-then-insert: %d concurrent retries -> %d charges\n", retries, naive.Charges)
var charges atomic.Int32
h := idem.Middleware(idem.Options{
Store: idem.NewMemStore(idem.DefaultConfig()),
Scope: func(r *http.Request) string { return r.Header.Get("X-Client") },
Required: true,
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
charges.Add(1)
time.Sleep(20 * time.Millisecond)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"charge":"ch_1"}`))
}))
var mu sync.Mutex
codes := map[int]int{}
replayed := 0
for i := 0; i < retries; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req := httptest.NewRequest(http.MethodPost, "/charges", strings.NewReader(`{"amount":2000}`))
req.Header.Set("Idempotency-Key", "order-1001-charge-attempt")
req.Header.Set("X-Client", "client-7")
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
mu.Lock()
codes[rr.Code]++
if rr.Header().Get("Idempotent-Replayed") == "true" {
replayed++
}
mu.Unlock()
}()
}
wg.Wait()
fmt.Printf("idempotent middleware: %d concurrent retries -> %d charges, statuses %v\n", retries, charges.Load(), codes)
// A retry after the first request finished is replayed, not re-run.
req := httptest.NewRequest(http.MethodPost, "/charges", strings.NewReader(`{"amount":2000}`))
req.Header.Set("Idempotency-Key", "order-1001-charge-attempt")
req.Header.Set("X-Client", "client-7")
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
fmt.Printf("late retry: status %d, Idempotent-Replayed=%s, body=%s, charges still %d\n",
rr.Code, rr.Header().Get("Idempotent-Replayed"), rr.Body.String(), charges.Load())
}The Go angle
net/httpgives youhttp.Handler, so the middleware is a plainfunc(http.Handler) http.Handler; wrap only POST and PATCH routes.database/sqlis driver-agnostic: thePGStorecompiles without a driver and the test importspgxonly to run against a real PostgreSQL.*sql.Txand*sql.DBboth satisfyExecer, which is what lets the response be stored inside the business transaction.context.Contextcarries the request deadline intoBegin,Completeand the handler; make the lease longer than the deadline you give the handler.go-redisv9SetNXandScript.Runmap toSET NX PXandEVAL;miniredislets the Redis path be tested without a server.- Run the tests with
-race: the concurrent-duplicate tests are exactly where data races hide. - Never ignore the error of
Completein production; this sample drops it to keep the middleware short, and the response was already sent. Log it and alert onErrLeaseLost.
Laravel
Laravel 13 has the pieces: middleware (handle(Request $request, Closure $next)), Form Requests, Eloquent firstOrCreate, a unique index in a migration, Cache::lock for atomic locks, and Prunable models for cleanup. None of this is an idempotency package; the files below are about 150 lines in total.
Before
A controller that creates a charge on every POST: a retry creates another one.
public function store(Request $request)
{
$charge = Charge::create($request->only('customer_id', 'amount'));
$this->psp->capture($charge); // no key, no record: a retry charges again
return response()->json($charge, 201);
}After
Migration with the unique constraint that is the real lock:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('idempotency_keys', function (Blueprint $table) {
$table->id();
$table->string('scope'); // authenticated client or tenant
$table->string('key', 255); // Idempotency-Key header value
$table->char('fingerprint', 64); // sha256 of method + path + body
$table->string('status', 16); // in_progress | completed
$table->timestamp('locked_until')->nullable();
$table->unsignedSmallInteger('response_code')->nullable();
$table->json('response_headers')->nullable();
$table->longText('response_body')->nullable();
$table->timestamp('expires_at')->index(); // replay window; pruned after this
$table->timestamps();
// The unique constraint is the real lock; Cache::lock only narrows contention.
$table->unique(['scope', 'key']);
});
}
public function down(): void
{
Schema::dropIfExists('idempotency_keys');
}
};Model with Prunable for cleanup:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Database\Eloquent\Builder;
#[Fillable(['scope', 'key', 'fingerprint', 'status', 'locked_until', 'response_code',
'response_headers', 'response_body', 'expires_at'])]
class IdempotencyKey extends Model
{
use Prunable;
protected function casts(): array
{
return [
'locked_until' => 'datetime',
'expires_at' => 'datetime',
'response_headers' => 'array',
];
}
/** Rows past their replay window; run with `php artisan model:prune`. */
public function prunable(): Builder
{
return static::where('expires_at', '<', now());
}
}Form Request that validates the header and answers 400 as the draft asks:
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
/**
* Validates only the Idempotency-Key header. Resolved from the container
* inside the middleware, so an invalid key is rejected before any lookup.
*/
class IdempotencyKeyRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
protected function prepareForValidation(): void
{
// Headers are not part of the validated input; copy the one we need.
$this->merge(['idempotency_key' => $this->header('Idempotency-Key')]);
}
public function rules(): array
{
return [
// Same published format as the Go service: 16-255 safe characters.
'idempotency_key' => ['required', 'string', 'regex:/^[A-Za-z0-9_.:-]{16,255}$/'],
];
}
public function idempotencyKey(): string
{
return $this->validated('idempotency_key');
}
/** The draft asks for 400 (not Laravel's default 422) on a missing or malformed key. */
protected function failedValidation(Validator $validator): void
{
throw new HttpResponseException(response()->json([
'status' => 400,
'title' => 'Idempotency-Key is missing or has an invalid format',
], 400, ['Content-Type' => 'application/problem+json']));
}
}Middleware: Cache::lock narrows contention, firstOrCreate plus the unique index guarantees one winner, wasRecentlyCreated tells first run from retry, and the stored response is replayed with Idempotent-Replayed: true:
<?php
namespace App\Http\Middleware;
use App\Http\Requests\IdempotencyKeyRequest;
use App\Models\IdempotencyKey;
use Closure;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
class EnsureIdempotency
{
private const REPLAY_HOURS = 24;
private const LEASE_SECONDS = 60;
public function handle(Request $request, Closure $next): Response
{
if (! in_array($request->method(), ['POST', 'PATCH'], true)) {
return $next($request);
}
// Validates the header (400 on failure) before anything touches storage.
$key = app(IdempotencyKeyRequest::class)->idempotencyKey();
$scope = (string) ($request->user()?->getAuthIdentifier() ?? '');
if ($scope === '') {
return response()->json(['status' => 401, 'title' => 'authentication required'], 401);
}
$fingerprint = hash('sha256', $request->method()."\n".$request->getRequestUri()."\n".$request->getContent());
// The lock keeps duplicates from racing into the database; the unique
// constraint below is still what guarantees a single winner.
$lock = Cache::lock("idem:{$scope}:{$key}", self::LEASE_SECONDS);
if (! $lock->get()) {
return $this->problem(409, 'A request with this Idempotency-Key is in progress')
->header('Retry-After', '1');
}
try {
try {
$record = IdempotencyKey::firstOrCreate(
['scope' => $scope, 'key' => $key],
[
'fingerprint' => $fingerprint,
'status' => 'in_progress',
'locked_until' => now()->addSeconds(self::LEASE_SECONDS),
'expires_at' => now()->addHours(self::REPLAY_HOURS),
],
);
} catch (UniqueConstraintViolationException) {
return $this->problem(409, 'A request with this Idempotency-Key is in progress');
}
if (! $record->wasRecentlyCreated) {
if (! hash_equals($record->fingerprint, $fingerprint)) {
return $this->problem(422, 'Idempotency-Key was already used with a different request');
}
if ($record->status === 'completed') {
return response($record->response_body, $record->response_code, $record->response_headers ?? [])
->header('Idempotent-Replayed', 'true');
}
// in_progress but we hold the lock: the previous holder died. Take over.
$record->forceFill(['locked_until' => now()->addSeconds(self::LEASE_SECONDS)])->save();
}
try {
$response = $next($request);
} catch (Throwable $e) {
$record->delete(); // unknown outcome: free the key for a clean retry
throw $e;
}
if ($response->getStatusCode() >= 500) {
$record->delete(); // do not cache 5xx
return $response;
}
$record->forceFill([
'status' => 'completed',
'response_code' => $response->getStatusCode(),
'response_headers' => array_filter([
'Content-Type' => $response->headers->get('Content-Type'),
'Location' => $response->headers->get('Location'),
]),
'response_body' => $response->getContent(),
'locked_until' => null,
])->save();
return $response;
} finally {
$lock->release();
}
}
private function problem(int $status, string $title): Response
{
return response()->json(['status' => $status, 'title' => $title], $status, ['Content-Type' => 'application/problem+json']);
}
}Route and schedule:
<?php
use App\Http\Controllers\ChargeController;
use App\Http\Middleware\EnsureIdempotency;
use Illuminate\Support\Facades\Route;
// routes/api.php: guard only the money-moving endpoints.
Route::middleware(['auth:sanctum', EnsureIdempotency::class])
->post('/charges', [ChargeController::class, 'store']);
// routes/console.php: prune expired keys every hour (also: php artisan model:prune).
// Schedule::command('model:prune', ['--model' => [\App\Models\IdempotencyKey::class]])->hourly();The Laravel angle
Cache::lock('name', $seconds)->get()returnsfalseinstead of blocking;->block($seconds)waits. Laravel's docs: "Atomic locks allow for the manipulation of distributed locks without worrying about race conditions." The lock needs a cache driver with atomic operations (Redis, database and others); it is not a substitute for the unique constraint, because a lease can expire.firstOrCreate"will attempt to locate a database record using the given column / value pairs" and inserts otherwise. It is a select followed by an insert, so two concurrent calls can both insert; the unique index makes the loser throwUniqueConstraintViolationException, which the middleware turns into409.wasRecentlyCreated(documented next tofirstOrCreate) is how the middleware knows whether the row is new.- A Form Request resolved from the container validates itself. Calling
app(IdempotencyKeyRequest::class)inside middleware runs validation early; overridingfailedValidationchanges Laravel's default422into the draft's400. - Put the controller's database writes and the key update in one
DB::transactionwhen the effect is local; with an external provider, pass a derived provider key. - Queue jobs: use
ShouldBeUnique/job IDs or the inbox pattern (Idempotent Consumers & the Inbox Pattern). - Octane keeps the app in memory: never store per-request state in static properties inside the middleware.
SQL schema and statements
-- Idempotency store for PostgreSQL. One row per (scope, key).
CREATE TABLE idempotency_keys (
scope text NOT NULL, -- authenticated client or tenant
key text NOT NULL, -- the Idempotency-Key header value
fingerprint char(64) NOT NULL, -- sha256 hex of method + path + body
status text NOT NULL CHECK (status IN ('in_progress', 'completed')),
owner text NOT NULL, -- lease token of the request that runs the work
locked_until timestamptz, -- lease end while in_progress
response_code int,
response_headers jsonb,
response_body bytea,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL, -- replay window; cleanup deletes after this
PRIMARY KEY (scope, key) -- the unique constraint IS the lock
);
-- The cleanup job scans by expiry; keep it cheap.
CREATE INDEX idempotency_keys_expires_at_idx ON idempotency_keys (expires_at);
-- 1. Claim (atomic): 1 row returned = this request owns the key.
INSERT INTO idempotency_keys (scope, key, fingerprint, status, owner, locked_until, expires_at)
VALUES ($1, $2, $3, 'in_progress', $4, now() + make_interval(secs => $5), now() + make_interval(secs => $6))
ON CONFLICT (scope, key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint, status = 'in_progress', owner = EXCLUDED.owner,
locked_until = EXCLUDED.locked_until, expires_at = EXCLUDED.expires_at,
response_code = NULL, response_headers = NULL, response_body = NULL
WHERE idempotency_keys.expires_at <= now()
OR (idempotency_keys.status = 'in_progress'
AND idempotency_keys.locked_until <= now()
AND idempotency_keys.fingerprint = EXCLUDED.fingerprint)
RETURNING owner;
-- 2. 0 rows returned: read the existing row to choose replay / 409 / 422.
SELECT fingerprint, status, response_code, response_headers, response_body
FROM idempotency_keys WHERE scope = $1 AND key = $2;
-- 3. Complete (same transaction as the business write when possible).
UPDATE idempotency_keys
SET status = 'completed', response_code = $4, response_headers = $5, response_body = $6,
locked_until = NULL, expires_at = now() + make_interval(secs => $7)
WHERE scope = $1 AND key = $2 AND owner = $3 AND status = 'in_progress';
-- 4. Cleanup (run in batches, see the cleanup section).
DELETE FROM idempotency_keys
WHERE ctid IN (SELECT ctid FROM idempotency_keys WHERE expires_at < now() LIMIT 1000);-- The decisive statement in one place: claim or learn who owns the key.
INSERT INTO idempotency_keys (scope, key, fingerprint, status, owner, expires_at)
VALUES ('client-7', 'order-1001-charge', 'sha256-of-request', 'in_progress', 'owner-1', now() + interval '24 hours')
ON CONFLICT (scope, key) DO NOTHING;
-- 1 row inserted: you own it. 0 rows: read the row and choose replay, 409 or 422.
-- Pessimistic variant: wait for the winner instead of returning 409.
BEGIN;
SELECT status, response_code, response_body FROM idempotency_keys
WHERE scope = 'client-7' AND key = 'order-1001-charge' FOR UPDATE;
-- Blocks until the winner commits; then status = 'completed' and you replay.
COMMIT;Solving the classic problems
Double charge after a timeout
| Solution | How | Advantage | Cost / limit |
|---|---|---|---|
| Idempotency key table | Claim, run, store, replay | Works for any effect | Table, TTL, lock |
| Natural key on the effect | Unique (customer, order_id, kind) | No extra table | Only when the business has a natural key |
| Provider idempotency key | Derived key to Stripe/Adyen | Covers re-runs | Provider TTL |
| Reconciliation job | Compare ledger and PSP daily | Catches leaks | Detects, does not prevent |
| Retry only on connect errors | No retries after bytes were sent | Zero server work | Users see failures |
1 POST /charges K -> claim, PSP charge OK, response lost
2 client retries K -> replay 201, no second charge
3 (provider key) crash after PSP: lease takeover re-runs; PSP sees same derived key -> same resultThe mobile app that retries on reconnect
Create the key when the user taps "Pay" and persist it with the pending order; reuse it for every attempt until the order reaches a final state; create a new key only for a new intent. Combine with exponential backoff and jitter (Timeouts, Retries & Jitter).
| Mistake | Effect |
|---|---|
| New key per HTTP attempt | Double charges |
| Same key for a changed cart | 422 (correct) |
| Key stored only in memory | App restart loses it |
Crashed holder and stuck in_progress
| Symptom | Cause | Fix |
|---|---|---|
Retries get 409 forever | Lease never expires (no locked_until) | Lease with takeover on same fingerprint |
| Two charges after a long handler | Handler outlived the lease | Raise lease, derived provider key |
| Takeover re-runs partial effect | Effect not idempotent | Same-transaction effect or provider key |
Webhook duplicates
Use the event ID as the key in an inbox table; acknowledge with 200 only after the effect and the inbox row commit together (Idempotent Consumers & the Inbox Pattern).
Key reused for a different request
Return 422 with a Problem Details body (RFC 9457) that links to your docs; never replay the old response for a changed payload.
Multi-region and cache loss
| Situation | Behaviour |
|---|---|
| Per-region store (Adyen) | Keys are not checked across regions; pin a client to one region |
| Redis failover loses the key | A retry re-runs; use a derived provider key or a SQL store |
| Replica lag reads | Claim on the primary only; never read keys from a replica (Replication, Read Replicas & Failover) |
Testing idempotency
| Test | What it proves |
|---|---|
| Same key, same body twice | Handler ran once; second response equals first plus Idempotent-Replayed |
| Same key, different body | 422, handler not called |
| 25 concurrent duplicates | One 201, 24 409 (see TestConcurrentDuplicatesRunOnce) |
5xx then retry | Handler runs again |
| Panic then retry | Key freed |
| Two clients, same key | Independent |
| Expired lease takeover | New owner; old owner's Complete fails |
| Kill the process between effect and record (chaos) | One effect after recovery |
Run the Go tests with go test ./... -race -count=1.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Payments, transfers, orders | SQL key table in the same database | Same-transaction effect, derived provider key | Durable and atomic |
| Create-by-ID APIs | PUT /things/{uuid} | Unique primary key | No key table |
| High-volume, cheap, repeatable effect | Redis SET NX PX | Idempotent effect | Speed over durability |
| Message handlers | Inbox table | Message ID | Same pattern |
| Public API | Required key, documented TTL | Problem Details errors | Predictable for clients |
| Internal call between services | Pass the key through | Deadline and retry budget | One decision per arrow |
| PATCH with deltas | Key or convert to absolute set | Version column | Deltas are not idempotent |
| Policy choice | Option A | Option B | This page |
|---|---|---|---|
| Concurrent duplicate | 409 | Wait and replay | 409 + Retry-After |
5xx | Replay | Release claim | Release claim |
| Key required | Always | Optional | Required on money endpoints |
| Store failure | Fail open | Fail closed (503) | Fail closed |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One application, one PostgreSQL. The key table lives next to the business tables; the side effect and the completed update share one transaction, so there is no crash window. A unique index plus INSERT ... ON CONFLICT is the whole concurrency story.
1 POST /orders K -> BEGIN; claim K; INSERT order; UPDATE key completed; COMMIT
2 retry K -> SELECT key -> completed -> replayModular monolith: boundaries without the network
Modules call each other in process. Put the key check at the edge (the HTTP layer) so internal calls need none; internal retries between modules are not possible without a network. If modules own separate schemas in one database, keep the key table in a shared "platform" schema and keep the effect transaction spanning them.
| Where the key is checked | Who is protected |
|---|---|
| HTTP middleware | The client's retries |
| Module API | Not needed in-process |
| Background job inside a module | Job ID as key |
Microservices: every arrow is a decision
The client talks to an Order service, which calls Payment, which calls a PSP, and publishes an event consumed by Shipping.
1 Client --K--> Order service scope c1, store (c1,K); effect + outbox row in one tx
2 Order --derive(c1,K,"pay")--> Payment service (its own key table, scope "order-service")
3 Payment --derive(...,"psp")--> Stripe (provider key)
4 Order outbox --msg id--> broker --> Shipping inbox (PK = msg id)| Hop | Key | Store |
|---|---|---|
| Client to API | Client's Idempotency-Key | API's key table |
| Service to service | Derived per step (never the same key for two different calls) | Callee's key table |
| Service to provider | Derived provider key | Provider |
| Service to broker | Message ID = event ID | Outbox, then consumer inbox |
Details: Service Communication, Transactional Outbox, Saga Pattern.
Distributed data: replicas, caches, regions
| Layer | Hazard | Rule |
|---|---|---|
| Read replicas | A replica may not have the key yet | Claim and read the key on the primary |
| Redis cache of keys | Failover can lose the lock or the result | Prefer SQL for money; accept the gap elsewhere |
| Multi-region | Keys are per region (Adyen) | Route a client to one region, or use a globally consistent store (Spanner, CockroachDB, DynamoDB global tables with care) |
| Active-active | Two regions both see "unseen" | Single home region per key owner |
| CDN or API gateway cache | Must not cache POSTs | No Cache-Control on mutating responses |
Scaling path: 1x, 10x, 100x
| Scale | Write rate of keys | Design |
|---|---|---|
| 1x (about 10 POST/s) | Trivial | PostgreSQL table, DELETE nightly |
| 10x (about 100 POST/s) | 8.6 M rows/day at 24 h TTL | Index on expires_at, batched deletes |
| 100x (about 1,000 POST/s) | 86 M rows/day | Partition by day, drop old partitions; or Redis with a SQL record for the money path |
| Beyond | Hot keys by client | Shard the key table by scope hash (Sharding at System Level) |
Lab: twenty retries, one charge
Single-process, so it was run on the host. Setup and the demo:
cd docs/snippets/system-design/api-idempotency/go
go run ./cmd/demoActual output (run on the host):
naive check-then-insert: 20 concurrent retries -> 20 charges
idempotent middleware: 20 concurrent retries -> 1 charges, statuses map[201:1 409:19]
late retry: status 201, Idempotent-Replayed=true, body={"charge":"ch_1"}, charges still 1- Claim race. Experiment: run the demo. What to look for: 20 charges for the naive version, one for the middleware, 19
409s. - Replay. The last line is a retry after completion: same
201, same body,Idempotent-Replayed=true, still one charge. - Tests.
go test ./... -race -count=1runs the contract suite on the memory store and on Redis throughminiredis; the PostgreSQL case is skipped unlessIDEM_PG_DSNis set.
PostgreSQL experiment (expected, not run): two psql sessions.
-- session 1 -- session 2
1 \i sql/schema.sql
2 INSERT INTO idempotency_keys (scope,key,fingerprint,status,owner,expires_at)
VALUES ('c1','K','fp','in_progress','o1',now()+interval '1 day')
ON CONFLICT (scope,key) DO NOTHING; -- INSERT 0 1
3 same INSERT ... DO NOTHING; -- INSERT 0 0
4 SELECT status FROM idempotency_keys WHERE scope='c1' AND key='K'; -- in_progress
5 UPDATE idempotency_keys SET status='completed', response_code=201 WHERE scope='c1' AND key='K' AND owner='o1'; -- UPDATE 1
6 SELECT status, response_code ...; -- completed, 201Redis experiment (expected, not run):
1 redis-cli SET idem:{h}:lock "o1|fp" NX PX 60000 -> OK
2 redis-cli SET idem:{h}:lock "o2|fp" NX PX 60000 -> (nil)
3 redis-cli PTTL idem:{h}:lock -> about 59990Laravel experiment (expected, not run): php artisan migrate, then send the same POST /api/charges twice with curl -H "Idempotency-Key: order-1001-charge-attempt"; the second response carries Idempotent-Replayed: true; changing the body returns 422. This Laravel experiment is expected output, not run.
Common misconceptions
| Belief | Reality |
|---|---|
| "POST is not retryable" | It is, once you add a key |
| "A unique constraint on the order is enough" | Charges and messages have no natural key; the key states intent |
| "check exists, then insert" | A race; claim atomically |
| "Idempotent means the second call returns an error" | It means no extra effect and the same answer |
| "The key can be the order ID" | Only if one order maps to exactly one call; otherwise use a UUID |
"Redis SET NX is a perfect lock" | Leases expire and failovers lose keys; keep a durable record for money |
| "5 minutes of TTL is enough" | Retries come from offline queues and brokers after hours |
| "Hash the body and skip the key" | AWS: two identical requests can be legitimately distinct |
| "Exactly-once delivery exists" | At-least-once plus idempotent receiver |
| "A replayed 500 is fine" | Stripe v1 does it; this page releases the claim; either way, document it |
| "Idempotency keys are secrets" | They are identifiers; just do not put sensitive data in them |
| "PUT never needs care" | PUT is idempotent by definition but your handler may add side effects (emails) |
Cheat sheet
| Topic | Remember |
|---|---|
| Header | Idempotency-Key, IETF draft -09, a String value |
| Key | UUIDv4 or random 128 bits; max 255 (Stripe), 64 (Adyen, EC2) |
| Scope | (client, key); never global |
| Claim | One atomic write: unique insert, SET NX PX, conditional put |
| Record | scope, key, fingerprint, status, owner/lease, response, expiry |
| Duplicate while running | 409 Conflict + Retry-After |
| Same key, new body | 422; never replay the old answer |
| Missing key | 400 on required endpoints |
| Replay | Stored status and body + Idempotent-Replayed: true |
| 5xx | Release the claim (or replay, if documented) |
| Crash window | Same transaction, derived provider key, or outbox |
| Downstream | Derive a stable key per step |
| TTL | 24 h minimum; 7 days for async partners |
| Cleanup | Index on expires_at, batch or partition |
| Metrics | started, replayed, conflict, mismatch, missing, store errors |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A client times out on POST /charges. List three possible server states and say which can produce a double charge on a naive retry. Must-know
Answer
Answer: Request never arrived (safe), server failed before the effect (safe), server completed the effect and the response was lost (double charge). A timeout cannot tell them apart.
2 — Why is "SELECT then INSERT" not a valid claim? Must-know
Answer
Answer: Two requests can both see "not found" between the SELECT and the INSERT. The claim must be one atomic operation: a unique-index insert (ON CONFLICT DO NOTHING), SET NX PX, or a conditional put.
3 — What status do the IETF draft's three error scenarios use? Good to know
Answer
Answer: Missing key: 400. Reuse with a different payload: 422. Retry while the original is still processing: 409.
4 — Why scope the key per client? Important
Answer
Answer: Two clients can generate the same string; without scope one client could read the other's stored response (data leak) or block the other's request.
5 — A crash happens between the PSP charge and the completed update. What three techniques prevent a second charge? Important
Answer
Answer: Do the effect and the record in one transaction (if the effect is a local write), pass a stable derived key to the provider so a re-run is a no-op, or use an outbox so the external call is made after the commit by an idempotent relay.
6 — Should a 500 be replayed on a retry? Important
Answer
Answer: Either choice is valid if documented. Stripe API v1 replays the saved result "including 500 errors". This page's code abandons the claim so a clean retry can run, because a 5xx means "outcome unknown".
7 — What is the lease for, and what happens if the handler outlives it? Important
Answer
Answer: It lets a request take over a key whose holder crashed. If a live handler outlives it, a second request may take over and run the work again; raise the lease or make the effect idempotent. The old holder's Complete fails with ErrLeaseLost.
8 — How long should keys be kept? Must-know
Answer
Answer: Longer than any client's retry window: Stripe prunes after at least 24 hours, Adyen keeps 7 to 14 days, EC2 ties it to the resource lifetime plus a margin. Document the TTL.
9 — When do you not need a key table? Good to know
Answer
Answer: When the operation names a final state: PUT with a client-chosen ID, upsert, conditional write, version check, absolute set.
10 — How does the same idea apply to a Kafka consumer? Important
Answer
Answer: The message ID is the key; an inbox table with a primary key on it is the claim; the effect and the inbox row commit in one transaction (Idempotent Consumers & the Inbox Pattern).
Glossary
| Term | Meaning |
|---|---|
| Idempotency | Repeating an operation has the same effect as doing it once |
| Idempotency key | Client-chosen ID for one intended operation, sent on every attempt |
Idempotency-Key header | The request header that carries the key (IETF draft) |
| At-least-once | Delivery or retries that may duplicate but never lose |
| Retry | Sending the same request again after an unclear failure |
| Double charge | The harm a duplicate non-idempotent POST can cause |
| Network ambiguity | Not knowing whether the server did the work |
| UUIDv4 | Random 122-bit identifier (RFC 9562) |
| ULID | 128-bit time-sortable identifier, Crockford base32 |
| Key scope | The owner within which a key is unique, usually the client |
| Request fingerprint | Hash of the parts of a request that define its intent |
| Hash | Fixed-size digest, here SHA-256 |
| Stored response | Status, headers and body saved for replay |
| In-progress | State of a claimed key whose work has not finished |
| Completed | State of a key whose response is stored |
| TTL | Time a record lives before cleanup |
| Concurrent duplicate | A retry that arrives while the original still runs |
| Unique constraint | Database rule that makes the claim atomic |
SET NX PX | Redis set-if-absent with a millisecond expiry |
| Lock | Mutual exclusion; here a short lease, not the source of truth |
| Lease | Time-limited ownership that expires if the holder dies |
409 Conflict | Same key still running |
422 | Same key, different request |
| Mismatched payload | Same key with another fingerprint |
| Replay | Answering a retry from the stored response |
Idempotent-Replayed | Header marking a replayed response |
| Side effect | Any change outside the response: a charge, a row, an email |
| Transaction | Atomic unit that commits or rolls back as a whole |
| Outbox | Table written in the effect's transaction, relayed to a broker |
| Downstream propagation | Passing a stable key to the service or provider you call |
| Provider idempotency key | Key accepted by Stripe, Adyen and similar APIs |
| Stripe | Payment provider; header Idempotency-Key, 24 h pruning in API v1 |
| Adyen | Payment provider; header idempotency-key, 7 to 14 days |
| Client token | AWS name for the idempotency key (ClientToken) |
| Natural idempotency | Operation that is idempotent by its shape |
| PUT | HTTP method that replaces a resource; idempotent |
| Upsert | Insert or update by key; ON CONFLICT DO UPDATE |
| Conditional write | Write that applies only if a predicate holds |
| Idempotent consumer | Message handler that tolerates redelivery |
| Inbox | Table of processed message IDs |
| Cleanup | Deleting records past their TTL |
firstOrCreate | Eloquent method: find by attributes or insert |
Cache::lock | Laravel atomic lock facade |
FOR UPDATE | SQL row lock until the transaction ends |
References
- IETF, The Idempotency-Key HTTP Header Field, draft-ietf-httpapi-idempotency-key-header-09, Internet-Draft, 21 November 2026 (work in progress)
- Stripe, Idempotent requests, API reference
- Brandur Leach, Designing robust and predictable APIs with idempotency, Stripe blog, 22 February 2017
- Adyen, API idempotency
- Square, Idempotency
- AWS Builders' Library, Making retries safe with idempotent APIs
- AWS, Idempotency in Amazon EC2
- AWS SDKs and Tools, Retry behavior
- IETF, RFC 9110: HTTP Semantics, section 9.2.2 Idempotent Methods
- IETF, RFC 9562: Universally Unique IDentifiers (UUIDs)
- IETF, RFC 9457: Problem Details for HTTP APIs
- ULID, Specification
- PostgreSQL, INSERT (ON CONFLICT), Constraints, SELECT (FOR UPDATE), Explicit locking
- Redis, SET
- Laravel 13, Middleware, Cache (atomic locks), Eloquent (firstOrCreate, pruning), Validation (Form Requests)
- Sibling chapters: REST API Design, Timeouts, Retries & Jitter, Payment Processing Architecture, Idempotent Consumers & the Inbox Pattern, Transactional Outbox