Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why a timeout is not an answerWhy it exists
The IETF draft, Stripe's post, AWS's articleWhere it comes from
Why POST needs a key and GET does notNetwork ambiguity
The header, its syntax and error codesThe Idempotency-Key header
Who may reuse which keyKey scope
UUIDv4, ULID, derived keys, entropyKey format
The table or Redis recordStorage
Same key, different bodyFingerprint and 422
Two copies of one request at onceConcurrent duplicates
Crash between the charge and the recordPartial failure
Replaying the first answerResponse replay
Provider keys, derived keys, outboxDownstream propagation
PUT, upsert, conditional writeNatural idempotency
Queues and webhooksIdempotent consumers
TTL and cleanupCleanup
Metrics and logsObservability
What Stripe, Adyen, Square, PayPal and AWS doProducts
Exact numbers, codes and knobsMechanics
Working codeGo, Laravel
Classic failures and fixesSolving the classic problems
Which store, which policyChoosing
Monolith to distributed systemIn architecture
Hands-on experimentsLab
Beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The idea in six steps.

StepWhat happensWho does it
1The client creates a key (UUIDv4) for one intended operationClient
2It sends Idempotency-Key: K with every attempt of that operationClient
3The server atomically claims (scope, K) with status in_progress and stores a fingerprint of the requestServer
4It runs the side effect once and stores the response with status completedServer
5A retry with the same key and the same body gets the stored response plus Idempotent-Replayed: trueServer
6A different body with the same key gets 422; a copy that arrives while the first runs gets 409Server

Which requests need a key.

MethodIdempotent by definition (RFC 9110)?Needs a key?Why
GET, HEAD, OPTIONSYes (and safe)NoNo side effect
PUTYesNo, usuallyReplaces the whole resource; second call changes nothing
DELETEYesNoSecond call finds nothing to delete (response may differ, state does not)
POSTNoYes, for anything that costs money or creates somethingEach call may create another thing
PATCHNoYes when it is relative ("add 10")balance += 10 twice is not once

The answers a server gives to a key.

SituationResponseRule
Key unseenRun, store, answer normally (201, 200, ...)Claim before work
Key seen, same fingerprint, completedSame status and body, header Idempotent-Replayed: trueReplay, never rerun
Key seen, same fingerprint, still running409 Conflict (or wait)One runner at a time
Key seen, different fingerprint422 Unprocessable ContentKey reuse is a client bug
Key missing on an endpoint that requires it400 Bad RequestPer the IETF draft
First run ended in 5xxRelease the claim (this page) or replay the 5xx (Stripe API v1)Pick one, document it
Key older than the TTLTreated as unseenTTL 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 keyWith a key
The client must choose between double charge and lost orderThe client can always retry; the server decides
Retry logic is dangerous, so people disable itRetries can be automatic in SDKs
Support tickets: "I was charged twice"The duplicate is answered from the stored record
Reconciliation jobs hunt duplicates afterwardsDuplicates cannot be created
Cost: none on the serverCost: a table, a lock, a TTL, replay code
ClientAPI server + store1. POST /charges Idempotency-Key: Kclaim K, charge card, store 201201 Created (lost)2. client timeout, outcome unknown3. retry: POST /charges Idempotency-Key: K (same body)K found, same fingerprint, completed4. 201 Created + Idempotent-Replayed: trueOne charge; the client learns the original result.

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 ​

  1. "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.
  2. "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.
  3. "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.

YearEventSource
2017Stripe publishes the idempotency-key designStripe blog
Before this articleAWS builds ClientToken into EC2 (RunInstances); date not stated in the articleBuilders' Library
2022RFC 9110 consolidates HTTP semantics, including idempotent methodsRFC 9110
2024RFC 9562 (UUIDs, including v4 random and v7 time-ordered)RFC 9562
2026IETF draft -09 of the Idempotency-Key headerIETF 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" again

Real 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 duplicateWho retriesKey helps?
User double-click or double-tapHumanYes, if the form reuses one key per intent
SDK or HTTP client automatic retryLibraryYes, the SDK reuses its key
Load balancer or gateway retry (NGINX proxy_next_upstream, Envoy retry policy)InfrastructureYes; also a reason to mark POSTs non-retryable at the proxy
Queue redelivery to an HTTP callbackBrokerYes, key = message ID
Job re-run after a worker crashSchedulerYes, 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.

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 ruleStatus codeBody
Header missing on an operation that requires it400 Bad RequestProblem Details (RFC 9457) with a link to the docs
Key reused with a different payload422 Unprocessable ContentProblem Details
Retry while the original is still processing409 ConflictProblem Details
Original completedA response "consistent with the request being completed"The original outcome
Any other 4xx/5xxFollow 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".

DecisionChoice that follows the draftWhy
Where the key goesRequest headerNot part of the payload, so the fingerprint stays stable
Document itYes: format, TTL, status codesThe draft says resources SHOULD document the behaviour and expiry
Without a key400 on required endpointsSilent "best effort" invites double charges
Idempotent methodsIgnore the header on GET/PUT/DELETEStripe: "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 choiceProsCons
Per authenticated client / accountNatural isolation; matches Stripe and AdyenAnonymous endpoints need another anchor (session, IP + device)
Per client + endpointSame key may be reused on /charges and /refundsMore rows; clients may be surprised
GlobalSimpleCross-tenant leaks and collisions; rejected by the draft
Per regionMatches regional storesAdyen: "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".

FormatBits of randomnessSortable by timeNotes
UUIDv4 (RFC 9562)122NoDefault choice; RFC 9562 defines v4 as random
UUIDv7 (RFC 9562)about 74 random + 48-bit timeYesTime-ordered; easier index locality in the store
ULID80 random + 48-bit timeYes (Crockford base32)128-bit compatible with UUID, "Lexicographically sortable" per the ULID spec
Derived (order-1001-charge-1)LowDependsFine when the business action is unique; predictable, so scope must protect it
Random string, 32+ chars128+NoThe draft's example: clkyoesmbgybucifusbbtdsbohtyuuwz
Auto-increment counterAlmost noneYesNever: guessable, collides between clients
Server-side validationWhy
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 lookupPrevents injection into the cache or database key
Never log a key next to a secret; logging the key itself is fineKeys 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.

FieldPurposeExample
scope, keyLookup (primary key)client-7, order-1001-charge
fingerprintDetect reuse with a different requestsha256 of method, path, body
statusin_progress or completedcompleted
owner / lease (locked_until)Who is running it; when a crashed holder may be replacedtoken, now + 60 s
stored responseStatus code, a few headers, body201, Content-Type, {"id":"ch_1"}
expires_atReplay windownow + 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)
StoreAtomic claimDurableExtra
PostgreSQL / MySQL tablePRIMARY KEY (scope, key) + INSERT ... ON CONFLICT DO NOTHING (PostgreSQL), INSERT IGNORE or catch error 1062 (MySQL/InnoDB)Yes, same transaction as the business writeCan join the effect's transaction
RedisSET key value NX PX ttlDepends on AOF/replication; a failover can lose itFast; separate system from the business data
DynamoDBConditional put (attribute_not_exists)YesTTL attribute for cleanup
In-memory mapMutexNoTests only
Size limits and TTLValueSource
Stripe key lengthup to 255 charactersStripe API reference
Adyen key lengthup to 64 charactersAdyen docs
EC2 client tokenup to 64 ASCII charactersAWS EC2 docs
Stripe API v1 key pruningafter at least 24 hoursStripe API reference
Adyen validity7 to 14 days after first submissionAdyen docs
Stored bodyCap 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 inputDetectsRisk
Whole body hashAny changeRe-serialisation (key order, spaces) looks like a change; safe but noisy
Canonical JSON hashSemantic changeNeeds a canonicaliser; bugs there hide real changes
Selected fields (amount, currency, customer)Business-relevant changeChanges outside those fields are treated as the same request (the draft says so)
Method + path + bodyKey reuse across endpointsAdd the tenant too if the path has none
Headers (Accept-Language, User-Agent)Nothing usefulRetries legitimately differ; do not include
Status code used for mismatchWhoNote
422 Unprocessable ContentIETF draft, this pageRFC 9110 section 15.5.21
400 Bad RequestSome APIsAcceptable if documented
409 with code 704 / 422Adyen (duplicate while in progress)"request already processed or in progress"
Validation error IdempotentParameterMismatchEC2Same 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
MechanismAtomicity comes fromLoser behaviourProduct
Unique insertPrimary key / unique indexON CONFLICT DO NOTHING returns 0 rowsPostgreSQL
Unique insert, catch the errorUnique indexError 1062 (MySQL/InnoDB), SQLSTATE 23505 (PostgreSQL)MySQL, PostgreSQL
SELECT ... FOR UPDATERow lock held until commitBlocks until the winner commits, then reads completed and replaysPostgreSQL, InnoDB
SET key v NX PX msSingle-threaded commandnil reply; read the key to see who holds itRedis
Conditional putattribute_not_exists(pk)ConditionalCheckFailedExceptionDynamoDB
Cache::lockBackend atomic add (Redis, database, memcached)get() returns falseLaravel
Advisory lock (pg_advisory_xact_lock)Lock managerBlocks or pg_try_advisory_xact_lock returns falsePostgreSQL
Loser policyClient effortServer effortUsed by
409 + Retry-AfterRetry laterTrivialIETF draft, this page
Block until winner completes, then replayNoneHolds a connection and a lockSome internal APIs
transient-error: true headerRetry same keyMarks the case explicitlyAdyen

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:

  1. 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.
  2. Make the side effect idempotent itself, by passing a derived key to the provider (Stripe, Adyen) so a re-run changes nothing.
  3. 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
A. Effect, then record (two steps)B. Effect + record in one transactionClaim key (in_progress)Charge card / INSERT orderUPDATE key: completed + responsecrash here: effect done, no recordretry finds in_progress, runs the work againClaim key (in_progress)BEGININSERT order / ledger rowsUPDATE key: completed + responseCOMMIT (all or nothing)crash before COMMIT: nothing happenedcrash after: replay the stored response
Side effectCan share the key's transaction?Strategy
Rows in the same databaseYesSame transaction (Go CompleteWith(tx))
Call to a payment providerNo (external)Derived provider key; record the provider ID afterwards
Message to a brokerNoOutbox row in the same transaction
Email or SMSNoIdempotent at the sender, or accept a rare duplicate and log it
Write to another microservice's databaseNoThat service has its own key; saga or outbox
Recovery after a crashRule
Lease expired, same fingerprintThe next request takes the key over and re-runs; safe only if the effect is idempotent or transactional
Lease expired, different fingerprintDo not take over: return 422 or 409 (this page's SQL requires equal fingerprints)
Holder returns late after takeoverComplete checks the owner token and fails with ErrLeaseLost
Effect done but unknownQuery 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.

QuestionRecommended answerReason
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 limitStore a pointer (object storage) or refuse the keyRow bloat
Streaming responsesDo not support keys, or store only the final statusCannot replay a stream
Add Idempotent-Replayed: true?YesLets 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"))
Clientkey K (UUID)Order servicestores K, fingerprint,replays stored responsescope = client idOwn databaseorder + key row, one txPayment providerIdempotency-Key = derivedOutbox rowmessage id = event idStripe / Adyensame key, same resultConsumer inboxPK = message id123
ProviderHow it takes the keyRetentionNotes
StripeHeader Idempotency-KeyAt least 24 h (v1)Up to 255 chars; v1 saves status and body "after endpoint execution begins"
AdyenHeader idempotency-key7 to 14 daysMax 64 chars; response header echoes the key; transient-error: true marks retryable races
PayPalHeader PayPal-Request-IdSee PayPal docs (not fetched)Named in the IETF draft's implementation list
SquareBody field idempotency_keySee Square docsUnique string per call; mismatched changes return an error
AWS (EC2 and others)Parameter ClientTokenResource lifetime plus a margin (EC2)Mismatch gives IdempotentParameterMismatch
Derived-key ruleWhy
Include scope, client key and step nameTwo steps of one request never share a key
Stable across re-runsThe whole point
Include an "attempt version" only if the business intends a new tryOtherwise 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.

PatternExampleIdempotent becauseProduct detail
PUT replacePUT /documents/42 with the full bodySame final stateRFC 9110: PUT is idempotent
Client-chosen IDPUT /orders/{uuid}Same ID = same resourceClient generates the UUID
UpsertINSERT ... ON CONFLICT (id) DO UPDATESecond run overwrites with the same valuesPostgreSQL; MySQL ON DUPLICATE KEY UPDATE
Insert or getINSERT ... 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 rowPostgreSQL
Conditional writeUPDATE accounts SET status='closed' WHERE id=7 AND status='open'Second run matches 0 rowsAny SQL
Version checkUPDATE ... SET v = v + 1 WHERE id = 7 AND v = 3A retry fails the checkOptimistic locking
Absolute setSET stock = 40 instead of stock = stock - 1Final state, not deltaBeware 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 callInto
POST /ordersPUT /orders/{client-uuid}
POST /transfersTransfer with a client-chosen ID as the primary key
PATCH balance +10A 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).

InputKeyWhere the dedup record lives
HTTP API clientIdempotency-Key headeridempotency_keys (this page)
Kafka / RabbitMQ / SQS messageMessage ID or business event IDInbox table with the effect
Webhook from a PSPEvent ID in the payload (for example Stripe's evt_...)Inbox table
Scheduled jobJob ID plus run dateJob 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 nothing

Real 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."

TTLWhen it fitsUsed by
24 hoursOnline payments with SDK retriesStripe v1 prunes keys "after they’re at least 24 hours old"
7 to 14 daysLonger retry windows, async partnersAdyen: "valid for a period of 7 to 14 days"
Resource lifetime + marginResource creationEC2 RunInstances
30 days or moreBanking batch flowsDesign choice; mind storage
Cleanup techniqueHowCost
Redis PX / EXPIREAutomaticNone
DynamoDB TTL attributeAutomatic, eventuallyNone
DELETE ... WHERE expires_at < now() LIMIT 1000 in a loopBatch, off-peakIndex on expires_at
Partition by day and DROP PARTITIONInstantPartitioning setup (Partitioning & Sharding in PostgreSQL)
Laravel Prunable + model:pruneScheduledChunked deletes
Edge caseRule
Row expired while a request still runsComplete only if owner matches and row exists; otherwise ErrLeaseLost
Retry after expiryRuns as new: say so in the docs
Clock skew between app serversUse 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).

MetricMeaningAlert when
idempotency_started_totalFirst runsBaseline
idempotency_replayed_totalRetries answered from the storeSudden spike (network or deploy issue)
idempotency_conflict_total (409)Duplicates during a runHigh ratio: retry storm or slow handler
idempotency_mismatch_total (422)Key reuse with another bodyAny sustained rate: client bug
idempotency_missing_total (400)No key on a required endpointNew client version regression
idempotency_store_errors_total (503)Store unavailableAny (fail closed means errors)
Rows past expires_atCleanup lagGrowing
In-progress older than the leaseCrashed holdersNon-zero for long
Log fieldWhy
idempotency_key, scopeJoin first run, replays, support tickets
outcome (started, replay, busy, mismatch)One query answers "was it a retry?"
request_idDifferent 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.

ProductKey locationLengthTTLConcurrent duplicateDifferent payloadFailures
Stripe API v1Header Idempotency-Keyup to 255Pruned after at least 24 hNo saved result for a conflicting concurrent request; retryErrorReplays the first result "including 500 errors"
Stripe API v2SameSameNot stated on the pageSameSameRetries "failed or partially failed work to completion when possible"
AdyenHeader idempotency-keymax 647 to 14 days422 or 409, code 704, header transient-error: trueNot detailed on the pageStore outage: 503 code 703
SquareBody idempotency_keyunique stringSee Square docsSee Square docsError indicating prior useSame key, same response
PayPalHeader PayPal-Request-IdSee PayPal docsSee PayPal docsSee PayPal docsSee PayPal docsListed in the IETF draft
AWS EC2Parameter ClientTokenup to 64 ASCIIResource lifetime + marginSame token, retryIdempotentParameterMismatchSemantically equivalent response
IETF draftHeader Idempotency-KeyNot fixedResource documents it409422Follow the resource docs
Operational detailStripeAdyenAWS
GET/DELETEDo not send keysPUT/GET/DELETE idempotent by definitionMany actions idempotent by default (for example TerminateInstances)
SDK supportRuby library retries with the key, backoff and jitterUse exponential backoffSDK and CLI generate and reuse tokens
SecurityDo not use sensitive data as keysUse 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 ​

Validate keyformat, scopeStore.Beginatomic claimStarted: run handler once2xx/4xx: Complete (store response); 5xx or panic: AbandonReplay: same key, same fingerprint, completedstored status + body + Idempotent-Replayed: trueBusy: key held by another request: 409 ConflictMismatch: same key, other payload -> 422Bad or missing key -> 400 (before any lookup)store down -> 503 (fail closed, never run unprotected)
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: true

Status codes and what the client does ​

CodeMeaning hereClient action
200, 201 (first)DoneUse it
200, 201 + Idempotent-Replayed: trueReplay of the first answerUse it; it is the same operation
400Key missing or malformedFix the request; new key not needed
401No scope (unauthenticated)Authenticate
409Same key still runningWait (Retry-After) and retry with the same key
413Body above the capShrink
422Key reused with a different requestUse a new key for the new intent
429Rate limit before the key layerBack off (Rate Limiting)
500, 502, 503, 504Outcome unknown or store downRetry 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.

ParameterValue in the codeReason
Lease (Config.Lease)60 sLonger than a 30 s provider timeout plus margin
Replay TTL (Config.TTL)24 hStripe's minimum pruning age
Redis lock PXthe lease in msAuto-expires if the holder dies
Max body1 MiBBounded memory
Client retry interval1 s, 2 s, 4 s with jitterLonger 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 ​

WhereText or codeMeaning
PostgreSQLERROR: duplicate key value violates unique constraint "idempotency_keys_pkey", SQLSTATE 23505Lost the claim race (when not using ON CONFLICT)
MySQL / InnoDBERROR 1062 (23000): Duplicate entrySame
Redis(nil) reply to SET ... NXKey exists
DynamoDBConditionalCheckFailedExceptionKey exists
LaravelIlluminate\Database\UniqueConstraintViolationExceptionUnique constraint lost the race
Adyen704: "request already processed or in progress"; 703: "required resource temporarily unavailable"Duplicate in flight; store down
EC2IdempotentParameterMismatchSame token, different parameters
Goidem.ErrLeaseLostHolder was replaced; do not store

Redis SET options used ​

OptionEffect (from the Redis SET page)
NX"Only set the key if it does not already exist."
PX millisecondsExpiry in milliseconds
EX secondsExpiry in seconds
GETReturn the old value (not used here)
XXOnly 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".

go
// 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.

go
// 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.

go
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.

go
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.

go
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.

go
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):

go
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
}
go
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).

go
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) })
}
go
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):

go
// 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/http gives you http.Handler, so the middleware is a plain func(http.Handler) http.Handler; wrap only POST and PATCH routes.
  • database/sql is driver-agnostic: the PGStore compiles without a driver and the test imports pgx only to run against a real PostgreSQL. *sql.Tx and *sql.DB both satisfy Execer, which is what lets the response be stored inside the business transaction.
  • context.Context carries the request deadline into Begin, Complete and the handler; make the lease longer than the deadline you give the handler.
  • go-redis v9 SetNX and Script.Run map to SET NX PX and EVAL; miniredis lets 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 Complete in production; this sample drops it to keep the middleware short, and the response was already sent. Log it and alert on ErrLeaseLost.

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.

php
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
<?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
<?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
<?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
<?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
<?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() returns false instead 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 throw UniqueConstraintViolationException, which the middleware turns into 409.
  • wasRecentlyCreated (documented next to firstOrCreate) 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; overriding failedValidation changes Laravel's default 422 into the draft's 400.
  • Put the controller's database writes and the key update in one DB::transaction when 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 ​

sql
-- 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);
sql
-- 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 ​

SolutionHowAdvantageCost / limit
Idempotency key tableClaim, run, store, replayWorks for any effectTable, TTL, lock
Natural key on the effectUnique (customer, order_id, kind)No extra tableOnly when the business has a natural key
Provider idempotency keyDerived key to Stripe/AdyenCovers re-runsProvider TTL
Reconciliation jobCompare ledger and PSP dailyCatches leaksDetects, does not prevent
Retry only on connect errorsNo retries after bytes were sentZero server workUsers 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 result

The 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).

MistakeEffect
New key per HTTP attemptDouble charges
Same key for a changed cart422 (correct)
Key stored only in memoryApp restart loses it

Crashed holder and stuck in_progress ​

SymptomCauseFix
Retries get 409 foreverLease never expires (no locked_until)Lease with takeover on same fingerprint
Two charges after a long handlerHandler outlived the leaseRaise lease, derived provider key
Takeover re-runs partial effectEffect not idempotentSame-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 ​

SituationBehaviour
Per-region store (Adyen)Keys are not checked across regions; pin a client to one region
Redis failover loses the keyA retry re-runs; use a derived provider key or a SQL store
Replica lag readsClaim on the primary only; never read keys from a replica (Replication, Read Replicas & Failover)

Testing idempotency ​

TestWhat it proves
Same key, same body twiceHandler ran once; second response equals first plus Idempotent-Replayed
Same key, different body422, handler not called
25 concurrent duplicatesOne 201, 24 409 (see TestConcurrentDuplicatesRunOnce)
5xx then retryHandler runs again
Panic then retryKey freed
Two clients, same keyIndependent
Expired lease takeoverNew 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 ​

SituationRecommendationExtra techniqueReason
Payments, transfers, ordersSQL key table in the same databaseSame-transaction effect, derived provider keyDurable and atomic
Create-by-ID APIsPUT /things/{uuid}Unique primary keyNo key table
High-volume, cheap, repeatable effectRedis SET NX PXIdempotent effectSpeed over durability
Message handlersInbox tableMessage IDSame pattern
Public APIRequired key, documented TTLProblem Details errorsPredictable for clients
Internal call between servicesPass the key throughDeadline and retry budgetOne decision per arrow
PATCH with deltasKey or convert to absolute setVersion columnDeltas are not idempotent
Policy choiceOption AOption BThis page
Concurrent duplicate409Wait and replay409 + Retry-After
5xxReplayRelease claimRelease claim
Key requiredAlwaysOptionalRequired on money endpoints
Store failureFail openFail 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 -> replay

Modular 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 checkedWho is protected
HTTP middlewareThe client's retries
Module APINot needed in-process
Background job inside a moduleJob 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)
HopKeyStore
Client to APIClient's Idempotency-KeyAPI's key table
Service to serviceDerived per step (never the same key for two different calls)Callee's key table
Service to providerDerived provider keyProvider
Service to brokerMessage ID = event IDOutbox, then consumer inbox

Details: Service Communication, Transactional Outbox, Saga Pattern.

Distributed data: replicas, caches, regions ​

LayerHazardRule
Read replicasA replica may not have the key yetClaim and read the key on the primary
Redis cache of keysFailover can lose the lock or the resultPrefer SQL for money; accept the gap elsewhere
Multi-regionKeys are per region (Adyen)Route a client to one region, or use a globally consistent store (Spanner, CockroachDB, DynamoDB global tables with care)
Active-activeTwo regions both see "unseen"Single home region per key owner
CDN or API gateway cacheMust not cache POSTsNo Cache-Control on mutating responses

Scaling path: 1x, 10x, 100x ​

ScaleWrite rate of keysDesign
1x (about 10 POST/s)TrivialPostgreSQL table, DELETE nightly
10x (about 100 POST/s)8.6 M rows/day at 24 h TTLIndex on expires_at, batched deletes
100x (about 1,000 POST/s)86 M rows/dayPartition by day, drop old partitions; or Redis with a SQL record for the money path
BeyondHot keys by clientShard 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/demo

Actual 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
  1. Claim race. Experiment: run the demo. What to look for: 20 charges for the naive version, one for the middleware, 19 409s.
  2. Replay. The last line is a retry after completion: same 201, same body, Idempotent-Replayed=true, still one charge.
  3. Tests. go test ./... -race -count=1 runs the contract suite on the memory store and on Redis through miniredis; the PostgreSQL case is skipped unless IDEM_PG_DSN is 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, 201

Redis 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 59990

Laravel 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 ​

BeliefReality
"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 ​

TopicRemember
HeaderIdempotency-Key, IETF draft -09, a String value
KeyUUIDv4 or random 128 bits; max 255 (Stripe), 64 (Adyen, EC2)
Scope(client, key); never global
ClaimOne atomic write: unique insert, SET NX PX, conditional put
Recordscope, key, fingerprint, status, owner/lease, response, expiry
Duplicate while running409 Conflict + Retry-After
Same key, new body422; never replay the old answer
Missing key400 on required endpoints
ReplayStored status and body + Idempotent-Replayed: true
5xxRelease the claim (or replay, if documented)
Crash windowSame transaction, derived provider key, or outbox
DownstreamDerive a stable key per step
TTL24 h minimum; 7 days for async partners
CleanupIndex on expires_at, batch or partition
Metricsstarted, replayed, conflict, mismatch, missing, store errors

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
IdempotencyRepeating an operation has the same effect as doing it once
Idempotency keyClient-chosen ID for one intended operation, sent on every attempt
Idempotency-Key headerThe request header that carries the key (IETF draft)
At-least-onceDelivery or retries that may duplicate but never lose
RetrySending the same request again after an unclear failure
Double chargeThe harm a duplicate non-idempotent POST can cause
Network ambiguityNot knowing whether the server did the work
UUIDv4Random 122-bit identifier (RFC 9562)
ULID128-bit time-sortable identifier, Crockford base32
Key scopeThe owner within which a key is unique, usually the client
Request fingerprintHash of the parts of a request that define its intent
HashFixed-size digest, here SHA-256
Stored responseStatus, headers and body saved for replay
In-progressState of a claimed key whose work has not finished
CompletedState of a key whose response is stored
TTLTime a record lives before cleanup
Concurrent duplicateA retry that arrives while the original still runs
Unique constraintDatabase rule that makes the claim atomic
SET NX PXRedis set-if-absent with a millisecond expiry
LockMutual exclusion; here a short lease, not the source of truth
LeaseTime-limited ownership that expires if the holder dies
409 ConflictSame key still running
422Same key, different request
Mismatched payloadSame key with another fingerprint
ReplayAnswering a retry from the stored response
Idempotent-ReplayedHeader marking a replayed response
Side effectAny change outside the response: a charge, a row, an email
TransactionAtomic unit that commits or rolls back as a whole
OutboxTable written in the effect's transaction, relayed to a broker
Downstream propagationPassing a stable key to the service or provider you call
Provider idempotency keyKey accepted by Stripe, Adyen and similar APIs
StripePayment provider; header Idempotency-Key, 24 h pruning in API v1
AdyenPayment provider; header idempotency-key, 7 to 14 days
Client tokenAWS name for the idempotency key (ClientToken)
Natural idempotencyOperation that is idempotent by its shape
PUTHTTP method that replaces a resource; idempotent
UpsertInsert or update by key; ON CONFLICT DO UPDATE
Conditional writeWrite that applies only if a predicate holds
Idempotent consumerMessage handler that tolerates redelivery
InboxTable of processed message IDs
CleanupDeleting records past their TTL
firstOrCreateEloquent method: find by attributes or insert
Cache::lockLaravel atomic lock facade
FOR UPDATESQL row lock until the transaction ends

References ​

Built by Morteza Negahi