Algorithms · Safety nets

Idempotency keys

Idempotency keys: how Stripe avoids charging you twice. The network drops a reply. You retry. Did the payment happen once or twice?

The problem

You tap Pay on a shop's checkout page. The shop's server calls Stripe's API, Stripe charges the card, and the reply starts travelling back... and the network drops it. The shop never hears "success".

Now the shop is stuck with a question it cannot answer: did the charge happen or not? Networks fail in the middle all the time, and with money on the line, a wrong guess means either a lost sale or a customer billed twice.

The obvious way

The obvious fix is to try again until you get an answer. That works for reading a web page, but a payment is different. If the first charge went through and only the reply was lost, the retry is a brand-new request, and the server happily charges the card a second time. The more flaky the network, the more double charges.

The clever idea

Think of a coat check. You hand over a coat and get a numbered ticket. If you come back and say "ticket 17, please" twice, they don't give you two coats, they point at the same coat. Stripe's 2017 post on idempotency describes the same trick: the client attaches a unique idempotency key to the request, in an Idempotency-Key header.

The server does the work once and stores the result under that key. If the same key shows up again, it skips the work and returns the saved result. An operation that gives the same outcome no matter how many times you send it is called idempotent. Pair this with retries that wait longer each time (exponential backoff) plus a random wiggle (jitter), and a flaky network becomes safe for payments.

How the code does it

Both clients talk to identical shops where the server works first and then 30% of replies get lost. Client A's retry loop sees silence, can't tell what happened, and just sends again with no key, so every lost reply becomes another charge. That's where the 2s and 3s in the first bar chart come from.

Client B makes one key per order and reuses it on every retry. When a retry arrives, the server finds the key and replays the saved answer instead of charging. B's bars are all exactly 1, even though it hit the same lost replies. The growing wait only matters for being polite to a struggling server.

Trade-offs

Nothing is free. The server has to store a result for every key, and clients must generate a genuinely unique key per intent (reusing one key for two different payments would wrongly replay the first). You don't need this for requests that are already safe to repeat, like reading data, and backoff makes a client slower to finish when the network is bad.

Where else you’ll see it

Anywhere a repeat is costly: sending an order, booking a seat, submitting a form, or a message queue delivering the same job twice. The pattern is always the same: label the request, remember the answer, replay it.

Client B's first request charges the card, but the reply is lost. B retries with the same key. What does the server do?

  • Charges again, since it's a new request
  • Returns the saved result without charging again
  • Rejects the request and never answers
Show the answer

Returns the saved result without charging again. The server finds the key in its saved results (line 8) and replays the stored answer, so the card is charged only once.

Change it and see
  • Change 0.3 to 0.6
  • Remove the key: pass null in careful
  • Change 10 retries to 2
  • Change 100 to 1000

The code

javascript, with what each line means beside it. It compares the clever way with retrying blindly.

let seed = 42;Pick a starting number for fake dice
function rand() { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }Roll a repeatable pseudo-random number from 0 to 1
function makeShop() {Build a fresh pretend payment shop
const charges = new Array(20).fill(0);Track charges for each of 20 orders
const saved = {};Remember results by key
function server(order, key) {The server receives an order and maybe a key
if (key && saved[key]) return saved[key];If key was seen, replay saved answer
charges[order]++;Otherwise charge the card once more
if (key) saved[key] = "ok";If there is a key, save the answer
return "ok";Reply that it worked
}
function send(order, key) {Sending is the trip over the network
const reply = server(order, key);The server does its work first
return rand() < 0.3 ? null : reply;30% of the time, the reply gets lost
}
return { charges, send };Hand back charges and send
}
function blind(shop, order) {Client A retries without any key
for (let i = 0; i < 10; i++) {Try up to ten times
if (shop.send(order, null)) return;Stop once a reply arrives
}
}
function careful(shop, order) {Client B retries carefully
const key = "order-" + order;Make one key for this order
let waited = 0;Start with zero waiting time
for (let i = 0; i < 10; i++) {Try up to ten times
if (shop.send(order, key)) return waited;Stop once a reply arrives
waited += 100 * 2 ** i * (0.5 + rand() / 2);Otherwise wait longer, with random wiggle
}
return waited;Report total waiting time
}
const A = makeShop(), B = makeShop();Open one shop for each client
for (let o = 0; o < 20; o++) {Go through all twenty orders
blind(A, o);Client A pays the order
careful(B, o);Client B pays the same order
}
const total = (list) => list.reduce((a, b) => a + b, 0);Make a helper that adds up a list
show(A.charges, "A: blind retries, charges per order");Draw A's charges as bars
show(B.charges, "B: idempotency key, charges per order");Draw B's charges as bars
print("A charged", total(A.charges), "times. B charged", total(B.charges), "times. Orders: 20");Print both grand totals

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on safety nets