A customer presses Pay. Your server asks Stripe to charge the card, and the connection times out. Did the charge happen? You cannot know. If you do nothing, you may have lost a sale. If you send the request again, you may charge the customer twice. Stripe's answer is the idempotency key: a unique value the client attaches to a request so that the server can recognise a retry and return the original result without doing the work again.
It is one HTTP header, but behind it sits a careful piece of distributed systems design, and it comes up in system design interviews for anything that touches money.
The problem: a timeout tells you nothing
Stripe's engineering blog breaks a single API call into three places where it can fail.
- The connection fails. The client never reaches the server. Nothing happened, so trying again is safe.
- The operation fails part-way. The server received the request and started work, then something broke. The work is in limbo.
- The response fails. The server finished the operation, but the connection dropped before the reply got back.
From the client's side, cases two and three look exactly the same as a slow version of case one: silence. As the blog points out, a distributed system can be as small as two computers exchanging messages, and that is all you need for this ambiguity to appear.
Some operations are naturally safe to repeat. Setting a DNS record to a value, or deleting a resource, gives the same end state however many times you do it. In HTTP, PUT and DELETE are defined to behave this way. Creating a charge is different. It is a POST that makes a new thing each time, so two successful requests mean two charges.

The idea: name the operation, not the request
The fix is to let the client give each operation an identity. Before the first attempt, the client generates a unique value and sends it in the Idempotency-Key header:
curl https://api.stripe.com/v1/charges \
-u sk_test_your_key: \
-H "Idempotency-Key: 5f3c9a1e-7b2d-4c58-9e0a-1d2f3a4b5c6d" \
-d amount=2000 \
-d currency=usd \
-d customer=cus_example
If the attempt fails for any reason, the client sends the same request again with the same key. The key says: this is not a new charge, it is the one I asked for a moment ago. The server now has enough information to treat the three failure cases correctly:
- Connection failed the first time: the server has never seen the key. It processes the request normally.
- Response was lost: the server has seen the key and has a result. It returns that result and does nothing else.
- Operation failed part-way: the server has seen the key but has no final result. This is the hard case, and it gets its own section below.
What Stripe's API does with a key
Stripe's API reference spells out the contract for its v1 API.
| Rule | Detail from Stripe's documentation |
|---|---|
| Which requests | All POST requests accept a key. GET and DELETE are idempotent by definition, so a key on them has no effect. |
| What a key looks like | Any string up to 255 characters. Stripe suggests a V4 UUID or another random string with enough entropy, and warns against using personal data such as an email address. |
| What is saved | The status code and body of the first request made with that key, once the endpoint has started executing. |
| What a retry gets | The saved response, including a saved 500 error. A replayed response carries the header Idempotent-Replayed: true. |
| Same key, different parameters | An error. The server compares the incoming parameters with the original ones to catch accidental reuse. |
| Same key, first request still running | A 409 Conflict. The client should wait and retry with the same key. |
| What is not saved | Requests that fail validation, or that conflict with a concurrent request, never start executing, so no result is stored and they can be retried. |
| How long | Keys are kept for at least 24 hours and may be removed after that. A key reused after removal is treated as a new request. |
Two of these rules surprise people.
The first is that errors are saved too. If the first attempt produced a 500, a retry with the same key returns the same 500. That sounds unhelpful, but it follows from the promise. A 500 means the outcome is unknown: side effects may have happened. Running the operation again under the same key could double it. Stripe's guidance is to treat a 500 as indeterminate and reconcile, by retrieving the object or listening for webhook events, before starting a fresh operation under a new key.
The second is the 24-hour window. An idempotency key is not a permanent record of the request. It is a guard for the period in which a retry is plausible. Stripe's documentation says to stop retrying an unresolved request when that window ends and to reconcile the outcome another way.
Stripe has said its newer v2 API behaves differently: retries do not repeat successful work, failed or partially failed work is retried to completion where possible, and the window is 30 days.
The hard case: failing in the middle
Returning a stored response is the easy half. The difficult half is a request that dies between steps. Stripe's blog covers this briefly: if the work happened inside an ACID database transaction that rolled back, a full retry is safe; otherwise the server has to recover its state and continue.
Stripe has not published the internals of how its own servers do this. The best public description of the technique is a long article that Brandur Leach, the author of the Stripe blog post, published on his personal site later in 2017. It builds a "Stripe-like" implementation in Postgres for a fictional ride-sharing app called Rocket Rides. What follows is that reference design, not a description of Stripe's production code.
The example request has to create a ride, write an audit record, charge the rider through Stripe, save the charge ID and send a receipt. The central distinction is between two kinds of work:
- Local changes live in your own database. A transaction can make any group of them atomic: all of them commit or none do.
- Foreign state mutations change another system: creating a charge at a payment provider, sending an email, publishing to a queue. Once made, they cannot be rolled back by your database.
A database transaction cannot stretch across a network call to someone else's system. So the request is cut into atomic phases. Each phase is a set of local changes committed in one transaction, and the phases are separated by the foreign calls. The rule is to commit what you know before you touch the outside world.
Each phase ends by writing a recovery point onto the idempotency key's row, in the same transaction as the phase's own work. In the example there are four: started, ride_created, charge_created and finished. Because the recovery point commits together with the work, the two can never disagree.
When a retry arrives, the server looks up the key, reads the recovery point and jumps straight to the next phase. Work that already committed is not repeated.
There is one gap left. Suppose the server crashes after the payment provider accepted the charge but before the next transaction recorded it. On retry the recovery point still says ride_created, so the server will call the provider again. The article's answer is to make that call idempotent too, by sending the provider an idempotency key derived from the local key's ID. The second call then returns the first charge. Idempotency has to hold at every hop, not only at the front door.
Guarding against two requests at once
A retry can arrive while the first attempt is still running, for example when an impatient client times out early. The reference design handles this in three layers:
- A unique index on
(user_id, idempotency_key)means only one request can insert the key. The key is scoped to the user, so two customers who happen to choose the same string do not collide. - A
locked_attimestamp on the row marks the key as in progress. A second request that finds a fresh lock gets a409 Conflict. A lock older than a timeout can be taken over, so a crashed worker does not block the key for ever. - Each phase runs in a
SERIALIZABLEtransaction, so if two requests still manage to race, Postgres aborts one of them.
The stored row also keeps the request's parameters. A request that reuses a key with different parameters is rejected, the same behaviour Stripe documents for its own API.
Tidying up after failure
A client may give up and never retry, leaving a request stranded half-way. The article suggests background processes to deal with what is left behind:
- An enqueuer moves background jobs, such as the receipt email, from a staging table into the job queue. The job row is inserted in the same transaction as the phase that needs it, so a rolled-back phase never sends an email.
- A completer finds keys that were abandoned before reaching
finishedand pushes them through to the end. - A reaper deletes old keys. The article suggests about 72 hours, long enough to recover from a bad deploy over a weekend.
On the client side, Stripe's blog asks for good manners when retrying. Wait a little after the first failure and double the wait each time (exponential backoff), and add a random amount to each wait (jitter). Without jitter, every client that failed at the same moment retries at the same moment, and the recovering server is knocked over again: the thundering herd problem. Stripe's SDKs can generate keys and retry in this way automatically.
The computer science underneath
Idempotence. An operation is idempotent if doing it many times has the same effect as doing it once. x = 5 is idempotent; x = x + 5 is not. An idempotency key turns the second kind into the first by attaching a name to the operation and remembering the names already handled. Idempotency and delivery guarantees works through the same payment example and explains why "exactly once" is really at-least-once delivery plus an idempotent receiver.
The lost reply problem. A caller that gets no answer cannot distinguish a lost request, a crashed server and a lost reply. This was first studied for remote procedure calls, and what happens when the reply never comes covers the classic choices: at-least-once, at-most-once, and remembering what you answered. The stored response behind an idempotency key is that last idea, built into a public API.
Atomicity and its limits. A transaction gives all-or-nothing behaviour inside one database. ACID and isolation levels explains the guarantee, and why SERIALIZABLE is the level at which concurrent transactions behave as if they ran one after another. Atomic phases are what you do when a single operation has to cross the edge of the database: keep each local step atomic and record progress between them.
Retries done properly. A retry policy needs a timeout, a backoff schedule, jitter and a limit, and it is only safe when the operation is idempotent. Retries, timeouts and circuit breakers covers the mechanics, and API design covers which HTTP methods are idempotent by definition and which need help.
What an interviewer could ask from this
A payment request times out. What should the client do? Retry with the same idempotency key and the same parameters, using exponential backoff with jitter. Never generate a new key for a retry of the same operation, because that makes it a new charge.
Who should generate the key, the client or the server? The client. The key has to exist before the first attempt, and it has to survive the case where the server's reply is lost. Only the client knows that two attempts are the same operation.
What happens if the same key arrives with a different amount? It is rejected. The server keeps the original parameters and compares them, so a key cannot silently be reused for a different operation.
Two requests with the same key arrive at the same instant. How do you stop both from charging?
A unique constraint on the key so only one insert wins, a lock on the row while work is in progress, and a 409 Conflict to the loser, which retries later and gets the stored result.
Why can a transaction not cover the whole request? The charge happens in another company's system. Your database cannot roll that back. So you commit local progress first, make the external call with its own idempotency key, and commit the result afterwards.
Takeaways
- A timeout does not tell you whether the operation happened. Design every write API on the assumption that clients will retry.
- An idempotency key names the operation. The server stores the first result under that name and replays it for every retry.
- Keys are scoped and temporary: compared against the original parameters, limited to a window (at least 24 hours on Stripe's v1 API), and not a permanent archive.
- Inside the server, split work into atomic phases around external calls and record a recovery point with each commit, so a retry resumes and does not restart.
- Idempotency must hold at every hop. If your server retries a call to another service, that call needs a key as well.












