Idempotency key: how to avoid charging twice | jonathanjuliani.dev
Technical·Nov 6, 2026 · 7 min
Idempotency key: how to avoid charging twice
A double click, the network drops after the charge: how an idempotency key (one per attempt) and a pending order prevent a duplicate payment. With code.
Jonathan Juliani
A customer clicked or tapped "Pay" twice and the network drops halfway through. How many times did you charge them? If the answer is "it depends", your checkout needs an idempotency key, not a disabled button.
And the worst case here isn't even the error. It's the success the customer never saw: the server charged, the response got lost, the screen kept spinning, and someone tried again. Two charges. We'll look at three ways to prevent that, and what each one costs, with a code sample on GitHub, a self-service snack-bar kiosk. All the code is there to read, follow, test, and understand.
What we'll get:
Why only locking the button, and a BEGIN/COMMIT on the charge, aren't enough
How an idempotency key and an order with status pending_payment, written before the charge, helps you solve it
How we can resume when the response got lost: look up by the key, not by the id
Which path we can pick for which case
Prerequisites: you've written an HTTP API and know what a transaction in the database is. The example uses Fastify, SQLite (better-sqlite3), and React to keep it simple, but the idea holds in any stack.
Idempotency in one sentence (and where the analogy breaks)
An idempotent operation is one you can repeat without changing the result after the first time. Trying to keep it simple, think of an elevator button: you press it ten times out of impatience and in the end you still get one elevator for that floor, because the elevator system remembers there's already a request open for that floor. Pressing it 10 times does not bring you 10 elevators.
Subscribe to the newsletter
Get new posts and videos by email as soon as they are out.
Where the analogy breaks: the elevator knows it's "the same request" because it's the same button or floor. You get the idea. In an API, two identical POST /orders calls might be two real snacks or one retry. The server can't guess. So the client generates an idempotency key per checkout attempt and sends the same key on every retry. A new key is a new order; a repeated key means "tell me what happened on this order."
Three ways to prevent a double charge: the tradeoffs
Option
Fixes
Where it breaks
Cost
A. Lock the button on the client
The double tap
A retry after a lost response gets a new key
Almost nothing
B. A BEGIN/COMMIT around the charge
Nothing that matters in these cases
The gateway isn't in that COMMIT; a retry mid-charge finds no order
Looks cheap, ends expensive, and doesn't solve the problem
C. Idempotency key + a pending order before the charge
Double tap, retries, lost responses
A payment that never answers stays pending (needs reconciliation)
One UNIQUE column, a hash, a lookup endpoint
Option A: lock the button
Everyone starts here (me included). Pay has a payLock ref, because two taps 30ms apart arrive before React re-renders:
So if the button is locked, where does the second charge come from? The network. If the POST landed, the card was charged, and the response died on the Wi-Fi, the button unlocks and the next tap, with a new key, is a new order. A lock is UX; idempotency is a contract with the server.
Option B: a BEGIN/COMMIT around the charge
That was my first idea, written plainly in my plan. Writing the decision out in full killed it: the gateway isn't part of your BEGIN/COMMIT, and if nothing is written until the payment returns, a mid-payment retry finds no order and charges again. Look at the diagram:
1The customer taps Pay. The first request reaches the API.
2The API calls the gateway before writing anything.
3The network is slow. The kiosk tries again.
4The retry looks for the order. Nothing is written yet.
5The database says there is no order.Reply
6With no order, the retry becomes a new order. Second charge.Failed
The decision is recorded in the sample's docs, D5, on purpose: the wrong idea explains the right one better than any diagram.
Option C: idempotency key + a pending order before the charge
Three parts. The key lives on the orders table with UNIQUE. In plain words: UNIQUE does not allow inserting two orders with the same key, so "two orders with one key" is a database guarantee, not just an if in the code:
code
-- apps/api/src/db/schema.sql (excerpt)idempotency_key TEXT NOT NULL UNIQUE,request_hash TEXT NOT NULL,status TEXT NOT NULL CHECK (status IN ('pending_payment', 'paid', 'payment_failed')),
Next to it goes a request_hash of the order (items, sorted options, method, only the card's last 4), to catch a bug that reuses a key for a different cart. And the order is this: write pending_payment, charge, write the outcome.
In this code sample, from findByKey to insertPending there is no await. better-sqlite3 is synchronous, so in our example project a second request with the same key can't land in between. The comment in the excerpt is from the file itself:
code
// apps/api/src/orders/routes.ts (excerpt)// From here to insertPending there is no await: better-sqlite3 is synchronous, so a concurrent// request with the same key cannot slip in between the lookup and the insert.const existing = orders.findByKey(idempotencyKey);if (existing) { if (existing.requestHash !== hash) return reply.status(422).send(/* ... */); return replay(db, reply, existing);}try { orders.insertPending({ id: orderId, idempotencyKey, requestHash: hash /* ... */ });} catch (error) { const raced = orders.findByKey(idempotencyKey); if (raced) return replay(db, reply, raced); throw error;}const result = await payments.charge(body.payment, priced.totalCents);
What about Postgres, which is async, so there is an await in between? Then what holds now is the UNIQUE plus the catch: if a second request arrives, it fails on the index, so the code re-reads by key and returns what the first one stored. The synchronous code is just the happy path; the index is the guarantee against a double charge.
The same retry, now using option C. Look at the diagram:
1The customer taps Pay. The request carries key K in the Idempotency-Key header.
2Before charging, the API writes the order as pending.
3Only now does the API call the gateway.
4The network is slow. The kiosk tries again, with the same key.
5The API finds the pending order and answers 202. No new charge.Reply
6When the gateway approves, the API stores the status and the exact response. The next retry gets that response back.
If the POST came back as a network error, the temptation is to ask "what's the status of order X?", but order X's id comes in the response, and the response is what got lost. So what do you do?
What the client/frontend always has in this case is the idempotency key, because it created it before sending the request. So in our example kiosk, GET /orders?idempotencyKey= every 1.5s is the call that asks the API with the idempotency key:
found paid or payment_failed: show what the server stored.
404: the request never landed; nobody was charged. If the page still holds the original body, re-send with the same key; otherwise (after a reload) go back to Pay with the cart intact. Who decides that is the product. In the example it's defined by afterNotFound (pay.ts#L13-L22).
30s with no final answer: show a code for the counter. Never charge again.
Look at the full flow:
1The POST came back as a network error. The order id would have been in the response, so the kiosk uses the one thing it has: the key.
2Found the paid order: show the pickup number the server stored.
3Found the stored decline: show it. Another card becomes a new attempt, with a new key.
4404: the request never landed and nobody was charged. If the page still holds the original body, re-send with the same key; after a reload, go back to Pay.
5Thirty seconds with no final answer: show a code for the counter and never start a new charge.
That's what separates "it failed" from "I don't know if it worked." Most checkouts treat both the same, and that's where the double charge lives.
Which to pick for which scenario (and the edge cases)
An internal form where nobody pays for anything: A is enough. Don't overbuild.
Anything that charges, sends an email, or creates an external resource: C, always. A alone doesn't cover the network.
One key guarding several operations (order, refund, coupon): a separate idempotency_keys table. Here the key is one-to-one with the order, so it lives on the order.
B: never as the only protection. The COMMIT keeps your database consistent, not the gateway.
Three edge cases that catch everyone:
A declined charge is final for the key. Another card is another attempt, with a new key (reduce.ts#L222-L238). The key identifies the intent, not the cart.
In this sample, the 409 for a price change writes nothing, so "Pay new total" reuses the key without a 422. The server reprices every order and, if the total changed, answers 409 before writing any row.
The card number never goes into sessionStorage. So after a reload, resuming is a lookup by key, never a re-send.
To run the example: docker compose up, /ops → Next payment → "No response, then approved", and pay.
The server destroys the socket after the commit (D13); simulating the failure before the commit proves nothing.
The tests are in orders.test.ts and checkout.spec.ts.
Reconciliation (K12). A payment that never answers stays pending_payment forever. That's a job for something running in the background. How about a job for that?
Key expiry. At scale you need a retention window longer than any retry.
A real gateway. With one, the provider's idempotency key should be the order id.
Quick reference
Concept
What to remember
Idempotency key
One per attempt, created on the client, re-sent on every retry
Button lock
Stops the double tap, not the lost response
BEGIN/COMMIT around the charge
Can't span the gateway
pending_payment before charging
A mid-payment retry gets 202
UNIQUE + hash
A database guarantee; a different body = 422
Lost response
Look up by key, not by id
Next steps
This is one of three posts on the same kiosk code sample. Another is about the other way to charge wrong, the price on screen and the price that leaves the card: server-side pricing and the 409. And another about when the API goes down mid-order: graceful degradation on the frontend.
Where in your system could a retry turn into a double charge? The job that reprocesses a queue, the webhook that arrives twice, the "resend" button? Tell me in the comments how you handled it (or didn't).
If I got something wrong, or you see a better way, say so and I'll update the post.