Systemsfor Aravinda
0 / 78 core
Week 12 · Production stories

Stripe idempotency

1 hours · core path

Read first: Idempotency and the exactly-once myth, Transactions and isolation

In one sitting

Stripe accepts an Idempotency-Key on mutating POST requests and stores the outcome so a retry does not charge twice. The key lasts on the order of 24 hours, records a fingerprint of the parameters, and is locked so concurrent retries cannot both run. Recovery points wrap foreign side effects so a crash resumes instead of repeating a charge.

A payment request will time out. The client cannot tell “the charge failed” from “the charge succeeded and the response was lost,” so it retries. If you run the charge on both attempts, you take the money twice. Stripe’s API accepts an Idempotency-Key on mutating POST requests so the retry can return the first outcome. The header is the easy half. The server has to remember the outcome, notice when the same key arrives with a different body, stop two workers from running the key at once, and remember how far it got in any call it cannot undo.

The problem

POST is not naturally idempotent. A second identical request is a second operation unless you impose a rule. The rule on this course is an idempotency key: the client generates it, a UUID is the usual advice, and the server stores the key with the result. Doing the operation twice has the same effect as doing it once, because the second time is a lookup.

Networks force the issue. The server can commit the charge and lose the TCP connection before the bytes of the response arrive. The client’s timeout fires. A careful client retries with the same key. A careless server treats that as a new POST and charges again. An aggressive client retries while the first attempt is still running, and now two workers both see “no result stored yet.”

There is a worse cousin. A bug reuses a key for a different request, different amount or different customer, and the server returns the first request’s stored response. The client believes the second operation succeeded. Or the server runs the second operation under the first key and overwrites the record of what actually happened. The key alone does not say “same request.” It says “same string.” Something has to check that the parameters match.

Foreign calls make rollback the wrong tool. A transaction on your database can undo a row you inserted. A charge that has already reached another system cannot be undone by aborting that transaction. An email you have already handed to a mailer cannot be pulled back by rolling the row back. The handler needs a way to remember “I was about to do this” and “I finished this,” so a retry continues instead of repeating.

Keys are a short-term tool. The published guidance keeps them on the order of 24 hours, not as a permanent archive of every operation you ever ran. A retry the same afternoon is the problem the key exists for. A retry next month is outside what the guidance promises.

The design

Store the outcome. The client sends the key on the mutating POST. The first attempt runs the operation and stores the key with the outcome. A retry that presents the same key gets the stored outcome and does not run the charge again. That is the whole contract a caller should be able to rely on inside the window. API design is where this belongs: the method is not naturally safe to repeat, so the safety is imposed with a client-generated key rather than implied by the verb.

Fingerprint the parameters. With the key, store a fingerprint of the parameters. On a retry, compare. The same key with a different request is an error. You do not return the old outcome as if it belonged to the new body, and you do not execute the new body under the old key. The fingerprint is what makes “same key” mean “same request” rather than “same string, trust me.”

Lock concurrent retries. Two workers can pass the “nothing stored yet” check at the same time if all you do is read and then insert. Both will charge. Concurrent retries with the same key must lock so two workers do not both run. One worker holds the lock and performs the operation. The other does not. When the outcome is stored, a later retry is the lookup path from the first rule. On a small system the lock is a row lock on the idempotency record in the database you already have.

Recovery points. Split the work into what a local transaction can undo and what it cannot. Database writes sit in a transaction. If the process dies before that transaction commits, the database rolls them back and a retry starts clean. A charge, or a receipt email, sits outside that protection. Brandur Leach’s writeup of the pattern separates those foreign side effects with recovery points. You record that you are about to make the call. Then you make it. Then you record that you did, including whatever you need in order to return the outcome later. A retry reads the point it reached and continues. It does not start over and charge again.

Walk a charge and then a receipt. This is the pattern, not a pasted request.

1. In a local transaction, store the key, take the lock,
   check the fingerprint.
   Crash here: the transaction rolls back. Nothing outside ran.
   Retry from the start.

2. Record the recovery point "about to charge."
   Commit that record.

3. Call the card network.

4. Record "charge done," with the outcome you must be able to return.
   Commit that record.

5. Record "about to send the receipt."
6. Send the receipt.
7. Record "receipt done," and store the response the client should see.

If you die after step 4, the retry sees a finished charge and moves on to the receipt. It does not charge again. If you die during step 3, the retry still sees “about to charge.” That record is the difference between a clean restart and a lie. You know the call may have happened. Continuing from that point means you do not blindly issue a second charge. Starting the handler from scratch, ignoring the point, is how the duplicate happens. The same sandwich wraps the email, because a second receipt is the same class of bug at a smaller price.

The outbox lesson is the same crack in a different costume. A database commit and a call to another system are not one transaction. You record intent where a rollback still exists, then you do the thing you cannot roll back, then you record the result. Recovery points are that discipline applied to a request the client will retry.

The window. On the order of 24 hours in the published guidance. Put the day in seconds so the retry math has a denominator. A client timeout of 10 seconds and two retries are assumptions, not a published client.

published window     on the order of 24 hours
24 × 3,600           = 86,400 seconds in that day
course shortcut      about 10^5 seconds

assumed client timeout     10 seconds
assumed extra retries       2
if attempts run back to back, 3 × 10 = 30 seconds
30 / 86,400 is a small slice of the window

A retry storm that finishes in well under a minute is inside the tool’s lifetime. A job that picks the same key up two days later is not something the published window promises to dedupe. The permanent record of the payment has to live in your own payment row. The key is how you find the outcome while the client is still retrying.

flowchart TD
  client[Client retry with the same key]
  gate[Lock and parameter fingerprint]
  local[Local database transaction]
  intent[Record the foreign intent]
  call[Foreign side effect]
  saved[Record the outcome]
  client --> gate --> local --> intent --> call --> saved

The gate is where a different body becomes an error and where a second worker is kept from running. The local transaction is the part that can still roll back. The intent record is the last safe step before a call you cannot undo.

What they traded

Choice What you gain What you spend
Client-generated key on mutating POST A retry dedupes without the server inventing an identity after the fact The client must store the key until it knows the outcome
Store the key with the outcome The retry returns the same result and does not charge again You keep that state for the window, on the order of a day
Fingerprint of the parameters The same key with a different request is an error A client cannot repair a bad body by reusing the key
Lock so two workers cannot both run Concurrent retries do not double-charge The waiter does not run, and a lock you fail to release sticks the key
Recovery points around a charge or an email A crash resumes instead of repeating the foreign call Extra records around every call you cannot roll back
Local transaction for the local writes Rollback is real, up to the process boundary It stops being real the moment you call another system
A window on the order of 24 hours The table does not become a forever archive of request bodies A late retry is outside the promise, and the payment row must already hold the truth

The failure you are preventing is the timeout after a successful charge. The money moved. The response did not. Without a stored outcome, the client’s correct instinct, retry, is the bug. With a stored outcome and no fingerprint, a second request that reused the key by mistake looks successful and did something else, or did the first thing again under a new description. With a fingerprint and no lock, two workers both decide they are the first attempt. Each defense catches one bug. Leaving one out because “we have idempotency keys” leaves that bug in.

The recovery-point failure is a crash in the middle of step 3, followed by a retry that only knows how to start at step 1. The “about to charge” row is sitting there. The new attempt ignores it, calls the card network, and records a second success. The key then stores an outcome that is already a duplicate. Recovery points do nothing if the retry path does not read them. The implementation detail that matters is the resume, not the existence of a column you never consult.

Check the fingerprint before any side effect. If you charge and then notice the body does not match the stored key, you have already done the thing the error was supposed to prevent. If you take the lock, notice the body differs, and return an error without overwriting the first outcome, the original request’s result stays intact for the client that actually owns that key. Doing the irreversible call before you compare the fingerprint makes the error too late. Compare the body, then charge.

What to steal

Steal the whole small version, because the small version is the production version until you have more than one foreign call and more than one database. One table in the database that already holds the payment. A client-generated key, UUID if you do not have a better unique string. The stored response. A fingerprint of the parameters, checked before you charge. A lock on the row so two workers cannot both run. A recovery point written and committed before each call you cannot undo, and another written after. A payment design that says “idempotency key” and cannot walk those steps has named a header.

Keep the window short. On the order of 24 hours is the published guidance, and it is the right default for you too. The payment row is the archive. The key is the retry tool. A debugger who wants to inspect a request from last quarter should be reading the payment, not hoping you kept every body forever. Clients should stop automatic retries well inside the window and show a human an unknown outcome rather than mint a fresh key and charge again.

Leave the platform version alone. You do not need a standalone idempotency service, a cluster of locks, or a policy language for recovery points when you have one charge and one receipt. Write the steps in the handler. When a second foreign call appears, wrap it in the same sandwich instead of inventing a workflow engine. When the local work is still one database, a local transaction plus the recovery points is the design. A saga is what you add when you truly have several local transactions and compensations, not when you have one database and a card network.

If you remember one failure, remember the crash after “about to” and before “done.” The retry continues from that point so it does not repeat the charge. Everything else in the pattern exists to make that sentence true: the key identifies the attempt, the fingerprint identifies the body, the lock identifies the single worker, and the stored outcome is what the client finally gets back.

Check yourself

The client times out and retries a mutating POST with the same Idempotency-Key and the same parameters. What should the server do?

Return the stored outcome and do not charge again. The first attempt stored the key with the result for this reason. A second execution is a second charge. This holds inside the published window, which is on the order of 24 hours, not for a permanent archive of the request.

The same key arrives again with different parameters. Why is returning the stored outcome the wrong response?

The key is tied to a fingerprint of the parameters. A different request under the same key is an error. Returning the old outcome tells the client that the new parameters succeeded. Running the new parameters under the old key destroys the record of the original request. The fingerprint exists so those two mistakes are rejected instead.

Two workers accept the same key at the same time, before any outcome is stored. What has to happen so the customer is charged once?

They must lock so both workers do not run. A read of “no row yet” followed by two inserts is how both charges happen. One worker holds the lock and performs the operation. The other does not run it. After the outcome is stored, a later retry is a lookup.

The handler recorded that it was about to charge, then crashed during the call to the card network. Why is starting over from the first line the bug?

A local database transaction can roll back. The card network cannot. The recovery point means the foreign call may already have happened. A retry continues from that point instead of repeating the charge. Starting over issues a second charge and then stores an outcome that is already a duplicate. The same pattern wraps the next foreign call, such as the receipt email.

Based on: Stripe published guidance on the Idempotency-Key; Brandur Leach's writeup of idempotency keys and recovery points.