The mechanism
Stripe's 2017 engineering post on idempotency lists the three ways a remote call can fail: the connection can fail before reaching the server; the call "could fail midway while the server is fulfilling the operation, leaving the work in limbo"; or the call "could succeed, but the connection break before the server can tell its client about it." From the client's side, all three can look the same: an error or no answer. A client that never retries loses work in the first case. A client that does retry repeats work in the third. No protocol removes that choice, which is why the queues and webhook senders you are most likely to use promise at-least-once delivery:
- AWS Lambda: "Lambda event source mappings process each event at least once, and duplicate processing of records can occur." A batch that fails becomes visible again after the visibility timeout, "For this reason, your function code must be able to process the same message multiple times without unintended side effects."
- Stripe webhooks: "Webhook endpoints might occasionally receive the same event more than once."
- Amazon SQS FIFO queues advertise exactly-once processing, but what they actually remove is duplicate *sends*: retry
SendMessage"within the 5-minute deduplication interval" and no duplicate enters the queue. A consumer that charges the card and then crashes before deleting the message still sees the message again.
What you can have is an exactly-once effect: deliver at least once, and make the second, third and tenth delivery do nothing new. That takes two parts. The request needs a stable identity that survives retries, and the receiver must record that identity atomically with the effect. The AWS Builders' Library article on idempotent APIs says recording the client token and the mutation "must meet the properties for an atomic, consistent, isolated, and durable (ACID) operation". Record the key without the effect, and a crash loses the effect. Record the effect without the key, and the retry repeats it.
Steps as text
- Client → API: POST /charges, key K1
- API → Database: claim K1, in progress
- API → Database: charge row and K1 result, one commit
- API → Client: 200 OK, connection drops (the harmful step)
- After a pause: Client → API: retry POST, same key K1
- API → Database: look up K1
- Database → API: complete: stored 200 and body
- API → Client: 200 again, Idempotent-Replayed: true
Stripe's semantics, as documented
Stripe's API is the reference design most teams copy, so read its rules exactly. For API v1:
- The key goes in the
Idempotency-Keyheader, is "up to 255 characters long", and Stripe suggests "V4 UUIDs, or another random string with enough entropy". Don't put email addresses or other personal data in it. - Stripe "saves the status code and body of the first request made with a given idempotency key after endpoint execution begins. Retries with the same key return the saved response, including
500errors." A replay carries the headerIdempotent-Replayed: true. - If the parameters fail validation, or "the request conflicts with another request that's executing concurrently", nothing is saved and you can retry. The concurrent case returns a
409: "wait and retry with that key and the same parameters. A new key can start a second operation." - "The idempotency layer compares incoming parameters to those of the original request and errors if they're not the same to prevent accidental misuse."
- "Stripe retains keys for at least 24 hours and can remove them after that. Reusing a key after it's removed can execute a new request." So Stripe says to retry an unresolved operation only within the first 24 hours; after that, "don't retry with either the old key or a new one". Reconcile instead.
- A
500is "indeterminate: the operation might have produced side effects". Don't switch to a new key until you know what happened.
API v2 changes the rules. Replays are recognised for 30 days, not 24 hours, only for the same API and the same account or sandbox, and for DELETE as well as POST. A retry no longer returns the cached failure: "If the first request failed (or partially failed), the API re-executes the failed requests". If you send no key, Stripe generates a UUID for you, and a key you never stored can't be resent after your process restarts. Stripe's error-handling guide says that if your application retries "across separate SDK calls or process restarts, generate and persist a key for the operation and supply it to every attempt." The same guide suggests deriving the key "from a user-attached object, like the ID of a shopping cart", which makes a double-click and a retry the same operation.
The IETF Idempotency-Key header
The HTTP API working group is standardising the header. As of November 2026, the latest draft is draft-ietf-httpapi-idempotency-key-header-09. It is still an Internet-Draft, not an RFC. The value is a Structured Field String; the key "MUST NOT be reused with another request with a different request payload"; a server "MAY compute a fingerprint of the request payload" and store it with the key; and a server that expires keys "SHOULD define such expiration policy and publish it in the documentation". Its error codes are the useful part: 400 when a required key is missing, 422 when a key is reused with a different payload, and 409 when a request with the same key is still being processed.
Building it on your own API
The pattern is a key table, claimed before the work and completed in the same transaction as the work:
CREATE TABLE idempotency_keys (
account_id bigint NOT NULL,
key text NOT NULL,
fingerprint bytea NOT NULL, -- hash of method, path and body
status text NOT NULL, -- in_progress | complete
locked_until timestamptz,
response jsonb, -- status code and body to replay
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, key)
);
INSERT INTO idempotency_keys (account_id, key, fingerprint, status, locked_until)
VALUES ($1, $2, $3, 'in_progress', now() + interval '30 seconds')
ON CONFLICT DO NOTHING
RETURNING key; -- no row back: someone already has this key
-- take over a claim whose worker died
UPDATE idempotency_keys
SET locked_until = now() + interval '30 seconds'
WHERE account_id = $1 AND key = $2
AND status = 'in_progress' AND locked_until < now()
RETURNING key;The transaction that completes the work updates the row WHERE status = 'in_progress' and checks that one row changed, so a worker that lost its claim can't overwrite the result.
Steps as text
- INSERT the key: ON CONFLICT DO NOTHING returns no row
- Load the stored row: by account_id and key
- Compare fingerprint: different payload: 422
- Check status: in progress: 409, or take over if expired
- Replay: complete: return the stored response
Four details decide whether it holds up:
- Scope the key. The primary key includes the account. The IETF draft lets a resource define what makes a key unique; unless it does, two keys are the same only if their values match exactly, so two tenants that both send
order-1would collide. Stripe v2 scopes replays to the same account or sandbox for the same reason. - The in-progress row is a lock, and it can expire. Powertools for AWS Lambda, the AWS library that does this on DynamoDB, claims the record with a conditional
PutItem, and a second call while the first runs raisesIdempotencyAlreadyInProgressError, "a locking mechanism for correctness". Withregister_lambda_context, the record stores the invocation's remaining time, and a call after that deadline runs again "as if it was in theEXPIREDstate". Two gaps remain. Lambda stops the first run at its timeout, but a call it already sent downstream can still land; and with your ownlocked_untillease, a worker that is only slow (a GC pause, a long provider call) outlives its lease and both run. And the Powertools record is a separate DynamoDB write from your effect: if the effect commits and the function dies before the record is marked complete, the retry runs the effect again. So the final business write still needs its own guard: a unique constraint or aWHERE status = 'pending'condition. - Decide what to replay. Stripe v1 replays even a
500. Most in-house APIs do better to store only outcomes reached after the effect started, and to delete the claim when the request fails validation, which matches Stripe's "we don't save the idempotent result" rule for that case. - Effects outside your database can't join your transaction. A charge at a payment provider can't commit with your rows. Pass an idempotency key downstream that is derived from yours (for example
K1:charge), so a retry after a crash repeats the provider call safely, as long as it sends the same parameters inside the provider's key window (24 hours for Stripe v1), then record the provider's response. If the replayed response is a500, reconcile before doing anything else. Shopify's payments team describes the same structure, with recovery steps that "recreate the same state before continuing".
Webhook receivers and the outbox
A webhook receiver is the same problem from the other side. Stripe's guidance:
- Dedupe on the event id: log "the event IDs you've processed, and then not processing already-logged events." Sometimes "two separate Event objects are generated and sent"; for those, dedupe on
data.objectid plusevent.type. - Don't use
createdfor ordering or dedupe. Snapshot events record it "in seconds, so distinct events can share a timestamp", and Stripe "doesn't guarantee the delivery of events in the order that they're generated." - Return a
2xx"before any complex logic that might cause a timeout", and process from a queue. A slow handler that times out after doing the work is a guaranteed redelivery.
Returning 2xx early is safe only if the event is stored or enqueued durably first; a crash after the 200 otherwise loses it, because Stripe counts a 2xx as delivered. Whatever runs the effect, the handler or the queue worker behind it, does INSERT INTO processed_webhook_events (event_id) ... ON CONFLICT DO NOTHING in the same transaction as the effect. If no row is inserted, it commits nothing else and acknowledges the event.
The outbox solves the opposite direction, when your service must change its database and also tell others. AWS's prescriptive guidance calls this the dual write problem: if the update commits and the publish fails, "the downstream service will not be aware of the change"; if the publish goes out and the update fails, data "could get corrupted". The fix: write the event to an outbox table "in the same transaction", and let a separate process read committed rows and publish them. That relay can crash after sending and before deleting or marking the row, so it delivers at least once too. AWS's own guidance says to "make the consuming service idempotent by tracking the processed messages". In its sample, the relay sets the SQS FIFO MessageDeduplicationId to the outbox row id, which absorbs a resend within five minutes and nothing later. The same page offers change data capture as the other option: DynamoDB Streams publishes item-level changes, which "saves the overhead of creating another table to track the updates".
Worked numbers
Dedupe windows against redelivery windows. A duplicate gets through when it arrives after you have forgotten the original. Here is how long two common dedupe layers remember by default, against how long Stripe can keep sending the same event. Stripe's own memory of your API keys (24 hours for v1, 30 days for v2) is a separate window, for your requests to Stripe.
Data as text
| Window (hours) | |
|---|---|
| Dedupe: SQS FIFO | 0.083 |
| Dedupe: Powertools | 1 |
| Resend: auto retries | 72 |
| Resend: Dashboard | 360 |
| Resend: Stripe CLI | 720 |
In live mode Stripe retries a failed delivery "for up to three days with an exponential back off". An operator can press Resend in the Dashboard "for up to 15 days after the event creation", or use the CLI "for up to 30 days". Powertools expires idempotency records "after an hour (3600 seconds)" by default. A webhook handler built on that default, which processes an event, times out before answering and is retried two hours later, does the work twice. Keep processed event ids for at least 30 days. The storage is small (illustrative: 200,000 events a day for 30 days is 6 million rows; at about 100 bytes a row with index overhead, roughly 600 MB).
Lost responses at volume (illustrative). Inputs: 1,000,000 payment requests a day, and 0.02% of them commit on the server but lose the response to a timeout. That is 200 retries a day of work that already happened. Without a key, each is a second charge, about 73,000 a year. With a key and the table above, each is a replay.
What the table costs. Powertools documents "2 WCU per non-idempotent call" on DynamoDB, one PutItem to claim and one UpdateItem to complete. Shopify reported "a 50 percent decrease in INSERT statement duration" in one high-throughput system after switching its keys from random UUIDv4 to ULIDs, which "contain a 48-bit timestamp followed by 80 bits of random data" and so insert in roughly time order. Shopify keeps a key unique for as long as the request is retryable, "typically 24 hours or less".
How it fails
- Repeated card charges from a balance that couldn't be written (Twilio, 18 July 2013). The incident "affected 1.4% of Twilio's customers": 1.1% at first, then a recurrence that hit "another 0.3%". Twilio kept in-flight balances in a Redis cluster. A loss of network connectivity made every replica request a full resync at once, the overloaded primary was restarted with the wrong configuration, tried to recover "from a non-existent AOF file", dropped all balance data and came back read-only. With balances at zero, usage triggered auto-recharge, and "the recharge was attempted multiple times as a result of the account balance not being updated to reflect the payment." Some accounts were then suspended because the repeated billing had got the card deactivated. Twilio restored balances from a separate double-bookkeeping store, refunded the charges, and added the fail-safe that "if billing balances don't exist or cannot be written, the system will not suspend accounts or charge credit cards." The lesson for any recharge, renewal or retry loop: the record that a charge happened must be durable, and it must be checked in the same step as the charge. A cache that can't be written can't be the only thing that knows.
- Deduping on an identifier someone else could change (MtGox, February 2014). MtGox suspended bitcoin withdrawals on 7 February and announced on 28 February that it would file for bankruptcy. It blamed transaction malleability: a third party could change a withdrawal transaction's hash without invalidating it. As Decker and Wattenhofer read the 10 February press release, MtGox's custom client tracked "transaction validity only via its hash", so a withdrawal that confirmed under a new hash looked failed and could be credited back. Their measurements of the network from January 2013 onward do not support the claim as the cause of the loss: MtGox said it lost 850,000 bitcoins, and they found that "barely 386 bitcoins could have been stolen" that way. The design flaw still stands: track an operation by an id you assigned and stored before sending it, never by one the network or the other party can rewrite.
Traps without a published incident
- Reconciliation you didn't expect. After an incident, Stripe "attempts to reconcile failed operations and send webhook events for any objects created during reconciliation. The cached response doesn't change." You can hold a cached
500for a charge that exists. Put your own id in the object'smetadataso the webhook can be matched to your record. - Fingerprinting too little. Without a payload fingerprint, the same key with a different amount silently replays the first response. Powertools'
payload_validation_jmespathraisesIdempotencyValidationErrorfor exactly this.
Our episode Before You Replace the Engine, Rehearse the Failure walks through uncertain retries and outside effects that a rollback cannot undo.
Decision table
| Option | What it costs | Choose it when |
|---|---|---|
| Client idempotency key, key table in the same transaction | A table, a fingerprint, a retention job; clients must persist keys | Any POST that moves money, sends a message or creates an object a client may retry |
| Natural key plus unique constraint (one charge per order id) | Needs a business id that truly identifies the operation | The operation has one: an order, an invoice, a booking |
Conditional state transition (UPDATE ... WHERE status = 'pending') | A state column; callers handle zero rows updated | The effect is a state change on one row |
| Webhook event-id table | Rows kept for at least the sender's resend window (30 days for Stripe's CLI) | Every webhook receiver |
| Transactional outbox plus relay | A table, a relay process, at-least-once publishing | A database change must reliably produce an event |
| Change data capture instead of a relay | A CDC pipeline to run, events shaped by your schema | You already run CDC, or the source is DynamoDB with Streams |
| SQS FIFO deduplication id | FIFO throughput and ordering rules; a 5-minute window | Absorbing producer resends only; consumers still dedupe |
A check you can run this week
Run two queries against production replicas. First, look for effects that already happened twice:
SELECT order_id, count(*) AS charges, min(created_at), max(created_at)
FROM charges
WHERE status = 'succeeded'
AND created_at > now() - interval '90 days'
GROUP BY order_id
HAVING count(*) > 1
ORDER BY charges DESC;Second, compare your dedupe memory with the sender's redelivery window: read the retention your pruning job enforces, or SELECT now() - min(created_at) FROM processed_webhook_events; if one runs (on Powertools, read expires_after_seconds in your idempotency config). If it is under 30 days for Stripe events, or the table doesn't exist, a late resend from the CLI will be processed again (from the Dashboard too, if it is under 15 days).
Then ask one review question of the payment path: if the process dies after the provider call succeeds and before the response is written, what does the retry send, and with which key?
Sources
The primary sources this guide was checked against.
- Stripe API reference: Idempotent requests
- Stripe documentation: Advanced error handling (idempotency, 409 and 500 behaviour)
- Stripe documentation: API v2 overview (idempotency)
- Stripe documentation: Receive Stripe events in your webhook endpoint
- Stripe engineering blog: Designing robust and predictable APIs with idempotency (2017)
- IETF draft-ietf-httpapi-idempotency-key-header: The Idempotency-Key HTTP Header Field
- Amazon Builders' Library: Making retries safe with idempotent APIs
- AWS Lambda documentation: Using Lambda with Amazon SQS
- Amazon SQS documentation: Exactly-once processing in FIFO queues
- Powertools for AWS Lambda (Python): Idempotency utility
- AWS Prescriptive Guidance: Transactional outbox pattern
- Shopify Engineering: 10 tips for building resilient payment systems (2022)
- Twilio: Billing incident post-mortem (incident 18 July 2013)
- Decker and Wattenhofer: Bitcoin Transaction Malleability and MtGox (2014)
- PostgreSQL documentation: INSERT (ON CONFLICT)
Hear it discussed
Episodes of the show that work through this decision.