Click once, charge twice
The same key that stops a double charge can also ship the wrong order.
Contents7 sections
The checkout below sends an idempotency key with every request. It is a unique ID that lets the server spot a retry and return its first answer instead of charging again. Tap Pay, tap Try again when it fails, and count the charges on the bank statement.
How many times does one tap on Pay charge the card?
Scripted simulation, no real payments1 × Mug, $20
Network
- No requests yet
Bank statement
- No charges
A new key on every retry
In the first setting, the fetch wrapper (the function that sends each request and retries it) makes a fresh key for every attempt. The server charges request 1 but the response is lost. When you tap Try again, the request goes out with a key the server has never seen. The server charges again.
// api.ts
async function post(url: string, body: any) {
for (let i = 0; ; i++) {
// Bug: a new key on every attempt
const key = crypto.randomUUID();
try {
return await fetch(url, {
method: 'POST',
headers: {
'Idempotency-Key': key,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(8000),
});
} catch (e) {
if (i >= 2) throw e;
}
}
}
The fix is to move crypto.randomUUID() out of the loop. Create the key on the first tap, and reuse it until the server gives a final answer. The second setting in the figure does this and the bank shows 1 charge. But stay in that setting and try one more thing.
The same key on a new cart
Hit the error, tap Back, add the hat and pay $35. Now look at the bank.
In a single-page app (SPA), tapping Back only changes the screen, so the old key is still in memory. The server sees that key and replays the answer it stored for the $20 mug. But the phone builds its “Paid” screen from the cart it sent, so it says $35. The hat is never charged and it never ships.
The key has to live exactly as long as one purchase. Shorter and you charge twice. Longer and the next order gets the last order’s answer.
Which layers can send a payment again?
Every copy of the payment so far came from you tapping. But between the phone and the bank there are at least 7 places that can send a payment again.
| Who sends the copy | Which key it carries |
|---|---|
| The user, tapping Pay again | A new one, unless the app kept the key |
| Your fetch wrapper, after a timeout | A new one, if the key is made inside the loop |
| Chromium, when a reused connection drops | Yours |
| Workbox (a library that stores failed requests in the browser), up to 7 days later | Yours |
| stripe-node (Stripe’s Node.js client), on your server | Its own |
Go’s net/http, on a reused connection |
Yours |
nginx (a reverse proxy), only with non_idempotent set |
Yours |
Most of these copies carry your key. They are safe if the server locks the key first, so 2 copies that arrive together can’t both run. The problem is a copy with a new key, because the server sees a new payment. Only the first 2 rows can make one, the user and your fetch wrapper. And stripe-node can’t help there. Its key only covers retries between your server and Stripe, so 2 payments from the phone become 2 separate calls to Stripe.
When should the key be created?
The figure below tests 6 moments for creating the key against 8 scripted scenarios.
Which of 8 scenarios go wrong, for each moment the key is created?
Scripted model of 8 scenarios, not a real serverin an SPA, until a full reloadA common tutorial pattern
Server settings
3 of 8 OK. It fails on reload, Back, 2 tabs and the day-3 replay, and it loses tomorrow’s purchase.
key lived too briefly key lived too long
Open a row to see its script.
2 taps 150 ms apart, with 1.5 s of processing.
Attempt 1 is processed but its response is lost, so it hits the 8 s timeout. The phone is offline for the wrapper’s 2 retries. Try again happens 5 s later, online.
Attempt 1 is processed. The reused connection resets before any headers arrive, and the browser resends the same request 0.3 s after the original, while the original still has about 1.2 s to run. With a key per attempt, the server answers the copy with a 409, the phone shows an error, and Try again makes a new key. If the server made the copy wait instead, this row would be OK for a key per attempt.
Processing takes 4 s. The user reloads at 2 s and pays again at 6 s.
Double charge. The key lived too briefly, so a copy of one purchase was charged as a second one.
As the timeout row, then Back at 10 s, add a hat, and pay at 15 s.
Wrong order. The phone shows success for a cart the server never charged.
2 tabs on the same cart. Tab A pays, with 6 s of processing. Tab B pays 3 s later.
Double charge. The key lived too briefly, so a copy of one purchase was charged as a second one.
Attempt 1 is processed, and the connection drops at 3 s. The phone is offline for 3 days. The service worker queues every failed attempt and replays them all on day 3.
Double charge. The server had already dropped the key when the replays arrived on day 3. If it keeps keys for 7 or 30 days, this row is OK.
A normal purchase, then the same mug 20 h later, in the same tab, without a reload.
Lost order. The customer meant to buy again, and the server treated it as a copy.
Rules every row follows
- The fetch wrapper has an 8 s timeout and 2 retries.
- A 409 reply means “still in progress”. Clients that hold a key retry a 409 with the same key after 1 s. The per-attempt UI treats any failed reply as an error.
- After the last scripted step, if the phone shows an error, the user taps Try again once. Row 7 is the exception, because the user has closed the app.
- The phone builds its “Paid” screen from its own cart, not from the server’s reply.
- The server locks the key first, returns 409 while a request with that key is still running, and replays the response once it’s finished.
- The app is a single-page app.
The figure opens on “per page load”, a pattern common in tutorials. In a multi-page app that worked, because the key died with the page. But in an SPA the page never reloads, so the key lives for the whole shopping session. That is the hat bug again.
Per intent does better. The key is created when the customer commits to this one purchase. It is saved, and every retry of that purchase reuses it. I wrote the same rule down this year, in a design note for a sales app that has to work offline on phones. There the phone keeps an outbox. Each write the user makes goes into it with its own client mutation ID, so the server can treat a retry as the same write.
Can the server catch a reused key?
Partly. The IETF’s draft for the Idempotency-Key header says a key reused with a different body should get a 422 error. To notice the difference, the server stores a hash of the body (a fingerprint) next to the key. Stripe does the same and rejects a reused key when the parameters differ.
Tick the 422 check in the figure’s server settings and pick “per submission”. Row 5 flips to double charge! The client took the 422 as a fresh start, made a new key and charged $35 on top of the $20. So before it sends anything new, the client has to ask what happened to the earlier payment.
The last option in the figure, checkout on the server, gets all 8 rows right because it stops depending on how long a key lives. Instead, the checkout itself becomes a record on the server.
Put the checkout on the server
A purchase lasts longer than one request, so give it its own row in the database.
POST /checkouts creates a draft
PUT /checkouts/:id changes its cart
POST /checkouts/:id/confirm draft, then paying, then paid
The database allows only one checkout per cart (a unique constraint). So a second tab gets the same checkout, and a replay that arrives late finds it already paid.
Stripe’s PaymentIntent works this way. It is Stripe’s record of one payment. Creating one charges nothing, so you can key it on the cart. The charge only happens at confirm, and that request gets its own short-lived key.
What the server does with the key
The client is only half of it. The server has to handle the key correctly too, and this handler gets it wrong in 4 places.
app.post('/pay', async (req, res) => {
const key = req.get('Idempotency-Key');
// (a) two copies can both miss
const seen = await db.findKey(key);
if (seen) return res.json(seen);
// (b) not in the transaction
await bank.charge(req.body.cents);
const order = await db.save(req.body);
// (c) crash before here: no record
await db.saveKey(key, order);
// (d) no fingerprint check
res.json(order);
});
The worst is (b). A database transaction is a group of writes that succeed or fail together, and the charge sits outside it. So a crash before (c) leaves the customer charged and the server with no record of it.
Brandur Leach’s 2017 design still fixes all 4. Lock the key before doing anything, which fixes (a). Reject a key whose parameters differ, which fixes (d). For (b) and (c), save a recovery point before each call to another system. Then a background job can pick up a request that was abandoned halfway and finish it.
Keep keys for longer than any client keeps retrying. Workbox can retry for 7 days, but Stripe may drop a key after 24 hours. Row 7 in the figure is that gap. The replay arrives on day 3, the key is gone and the mug is charged again.