- Payments
- Idempotency
- TypeScript
- Open source
Making a payment request safe to retry
Why a payment button can't just retry on a bad network, and how idempotency keys, a durable queue and one sender at a time make a retry safe.
8 min read
In short
- After a network error, an app cannot know whether the payment went through, so retrying blindly can charge twice.
- An idempotency key lets the server recognise a retry and return the first result instead of charging again.
- The client has to create the key once, save it before sending, and let only one sender use it.
- idempotent-queue does this in the browser, Node and React Native, and is tested with random crashes and lost responses.
Written for: Web and mobile developers who send payments from an app.
A user taps Pay. The spinner turns for ten seconds, and then the app shows a network error. Did the payment go through?
The honest answer is that the app does not know. There are three things that could have happened:
- The request never reached the server. Nothing was charged.
- The request reached the server, the card was charged, and the response was lost on the way back.
- The request reached the server and is still being processed.
From the phone, all three look the same: no response. If the app retries, case 2 charges the customer twice. If it does not retry, case 1 loses a payment the user meant to make. Showing an error and asking the user to tap again is the same retry, just slower.
I build payment software for a living, and this is the problem I kept running into. So I wrote idempotent-queue, a small open-source library for the browser and Node, and react-native-idempotent-queue for mobile apps. This post is about the ideas behind them, which matter more than the code.
The fix lives on the server: idempotency keys
The standard answer, used by Stripe, Adyen and many payment APIs, is an A unique id the client attaches to a request, so the server can recognise repeats of it and do the work only once.. The client makes up a unique key for each payment, once, and sends it in a header with every attempt:
POST /api/payments
Idempotency-Key: 6f1c2a4e-8d0b-4c1e-9a57-3b2f0d9e7c41The server stores the result of the first request it handles with a given key. When the same key comes in again, it does not do the work again. It returns the stored result. A retry stops being dangerous: it either does the work for the first time, or gets back the answer to the first time.
Try both ways yourself. Lose the first response, then retry with the same key, and then with a new key each time:
Try it: lose a response, then retry
- Tap Pay to start.
Card charged
0×
The client can still get it wrong
The server side is well understood. The client side is where I kept seeing mistakes, and each one quietly undoes the key:
- A new key on every attempt. If the key is generated inside the function that sends the request, every retry looks like a new payment.
- A key that only lives in memory. The user reloads the page, or the OS kills the app, and the key is gone. The next attempt gets a fresh key.
- Two senders. The user has two tabs open, or taps twice. Two copies of the same payment go out at the same time, and if they have different keys, the server has no way to know.
- Retries that make things worse. Every client retrying on a fixed timer, at the same moment, right after an outage.
How the queue works
You give it a send function and enqueue payloads. With the built-in fetch helper it looks like this:
import { createIdempotentQueue, fetchSender } from 'idempotent-queue';
type Payment = { amount: number; currency: string; to: string };
export const payments = createIdempotentQueue<Payment>({
send: fetchSender('/api/payments'),
});
payments.start();
// In the click handler
const item = await payments.enqueue({
payload: { amount: 2500, currency: 'EUR', to: 'acct_42' },
group: 'payments',
});Behind that small API are a few rules.
1. Save first, then send
enqueue only resolves after the item and its key are written to storage. Each attempt is also recorded in storage before the request goes out. If the tab closes one millisecond later, the payment and its key are still on disk. In the browser the default storage is The browser's built-in database. What a page stores there survives reloads and closing the tab..
2. One key for the whole life of the payment
The key is created when the item is enqueued, as a UUID v4 from crypto.randomUUID() where it exists, and it never changes. fetchSender sets the Idempotency-Key header from it on every attempt, and ignores a header with the same name in your own options, so nothing can override it by accident. If your payment already has a natural unique id, like an order id, you can pass that as the key instead.
Enqueuing a key that is already stored returns the existing item and creates nothing. Succeeded items are kept for 24 hours by default, so a double tap returns the finished payment instead of sending a second one.
3. One sender at a time
Every tab of the site shares the queue, but only one tab sends. At start(), each tab asks for a A browser feature that lets one tab hold a named lock while other tabs of the same site wait for it. (MDN). The browser gives it to one tab and makes the others wait. The others still see every item, because a tab that changes the queue tells the rest over a BroadcastChannel. Inside the sending tab, a key that is in flight is never started a second time, even after its attempt has timed out. Items in the same group go one at a time, in order, and a failed item holds back the rest of its group. A transfer should not be sent before the payment it depends on.
4. Pick up where a closed tab stopped
This is the case I cared most about. The sending tab closes in the middle of a request. The browser releases its lock, and the next tab in line gets it. That tab finds an item marked inflight that it is not sending, so it knows the attempt was cut off. It puts the item back to pending and sends it again, with the same key:
function recovered(item: QueueItem, t: number): QueueItem {
if (item.attempts >= policy.maxAttempts) {
return { ...item, status: 'failed', updatedAt: t, lastError: { kind: 'interrupted', /* … */ } };
}
return { ...item, status: 'pending', updatedAt: t, nextAttemptAt: t };
}The queue cannot know whether the cut-off request reached the server. It does not need to. If it did, the server replays the stored result. If it did not, this attempt is the real one.
5. Retry without making things worse
Not every error should be retried. The default rules: a network failure, a timeout, 408, 409, 425, 429 and any 5xx are retried. Any other 4xx is permanent, because sending the same bad request again will not fix it. 409 is on the retry list on purpose. It is what a server answers when the first request with this key is still running, which is exactly what happens after a tab closes mid-request. The retry later gets the stored result.
Retries wait using Waiting longer after each failure, for example 1 s, then 2 s, then 4 s, so retries do not pile up. with full A random amount added to each wait, so many clients that failed together do not all retry at the same moment.: after the n-th failure, a random delay between zero and min(maxDelay, base × 2^(n−1)). The randomness spreads clients out so they do not all hit the server at the same moment. A server's Retry-After header takes priority. While the device is offline, items wait and do not use up attempts.
export function backoffDelay(failures: number, policy: ResolvedRetryPolicy, random: () => number): number {
const ceiling = backoffCeiling(failures, policy);
let r = random();
if (!(r >= 0)) r = 0;
if (r >= 1) r = 1 - Number.EPSILON;
return Math.floor(r * ceiling);
}6. Storage that does not half-write
With several tabs, two of them can change the queue at the same moment. If both read the state, change it and write it back, one change is lost. So every change is one read-modify-write step. On IndexedDB that is a single readwrite transaction, which the browser runs one at a time across tabs and commits completely or not at all. The state is also written as a versioned, checksummed envelope to two alternating slots. If one copy is ever unreadable, the queue loads the other, keeps a copy of the bad data for inspection, and carries on instead of crashing.
What it does not promise
I put this section near the top of the README, because it matters most when money is involved.
- The client gives at-least-once delivery. The request keeps going out, with the same key, until it succeeds, fails permanently, or runs out of attempts. An exactly-once effect only happens if the server honours the key. Without that, a retry can still charge twice.
- Payloads are stored in plain text. IndexedDB is not encrypted. Never put card numbers or tokens in a payload. Send a reference, like a server-side payment intent id, or use a storage adapter that encrypts.
- Something has to be running. The queue sends while a page is open or the app is running. Pending items go out the next time
start()is called.
How I tested it
Unit tests are not enough for this kind of code. The bugs live in the gaps between events: a crash between a write and a send, two tabs starting at once, a response lost after the server already did the work. So most of the confidence comes from A test that generates hundreds of random inputs and checks that a rule holds for every one, instead of a few hand-picked examples. with fast-check.
The tests generate random sequences of enqueues, crashes, reloads, offline periods, lost requests and lost responses, against a fake server that deduplicates by key. A crash throws away a tab's memory, its unfinished writes and its locks. Then the tests check properties such as:
- every enqueued key ends up applied exactly once on the server, and its item ends
succeeded; - the same key is never in flight twice at the same time, even across two tabs that crash and reload;
- a permanent error is never retried, and a retryable one is tried at most
maxAttemptstimes.
To check the tests themselves, a script breaks the source in nine small, deliberate ways, such as skipping the recovery of a closed tab's item or releasing the sender lock too early. Each break made its property fail. The results are written up in the repo. Outside the test suite, version 0.1.0 was also checked with real tabs in Chromium, Firefox and WebKit, including closing the sending tab mid-request and seeing another tab finish it with the same key, applied once.
If you build the server side
The client is only half of it. A server that takes payment retries safely needs to:
- Require an
Idempotency-Keyon every request that moves money. - Store the key with the response of the first request, before or together with doing the work.
- Return the stored response for any repeat of the key, without doing the work again.
- Answer
409while the first request with a key is still running, and422if the key comes back with a different body.
With both halves in place, a flaky network turns into a slow payment instead of a lost or doubled one. Both libraries are MIT licensed and on npm: idempotent-queue for the web and Node, and react-native-idempotent-queue for React Native. Issues and questions are welcome on GitHub.

Written by
Moksh Upadhyay
Full-stack developer in Delhi, working on payments and stablecoins. I write about keeping money correct when networks, devices and users do something unexpected, and I maintain the open-source libraries these posts are about.