How do you design payments so nobody is charged twice?
Idempotency keys on every money-moving request, an explicit state machine for each payment, a double-entry ledger that never updates balances in place, webhooks treated as the source of truth, and daily reconciliation against the provider. Each one closes a different way money goes wrong.
The verdict, as we’ll prove step by step: assume every network call can time out after it succeeded, and design so that retrying is always safe.
- Idempotency keys: the client sends a unique key with each payment attempt; the server stores the result under that key and returns the same result for any retry.
- A state machine per payment:
created → authorised → captured → refunded, with every transition checked and recorded. - A double-entry ledger: money moves as pairs of entries that sum to zero; balances are computed from entries, never updated in place.
- Webhooks as the source of truth for the provider’s side, handled idempotently.
- Reconciliation: every day, compare your records with the provider’s settlement reports, and alert on any difference.
Payments make a good mystery because the stakes make every idea honest. A customer looks at their statement and sees the same charge twice. Nobody clicked anything strange, no code obviously misbehaved, and yet the money left twice. None of the techniques that prevent this is exotic; each one closes a different way money goes wrong, and together they leave the culprit nowhere to hide.
Case file
The case The same charge appears twice on a statement Suspects The user, the provider, the checkout UI Culprit A lost response: the call succeeded but the caller never heard The fix Idempotency keys, a state machine, a double-entry ledger, webhooks, daily reconciliation
The case: how double charges happen #
Diagram source
sequenceDiagram
participant C as Checkout page
participant API as Your API
participant P as Payment provider
C->>API: POST /payments (amount 4,999)
API->>P: charge card
P-->>API: success… (response lost: timeout)
API-->>C: 504 Gateway Timeout
C->>API: user clicks "Pay" again
API->>P: charge card again
P-->>API: success
Note over C,P: Customer charged twice
Look closely at the diagram and the suspect is not the user, and not the provider. It’s the lost response. Every arrow can fail after the work was done, and the caller can’t tell “didn’t happen” from “happened, but I never heard”. The tempting fix, a smarter UI, is a false lead on its own. The real fix is the same at each hop: make the operation idempotent and pass an idempotency key along. One idea, applied consistently, handles the whole chain.
The first clue: idempotency keys #
Diagram source
sequenceDiagram
participant C as Checkout page
participant API as Your API
participant DB as Database
participant P as Payment provider
C->>API: POST /payments, Idempotency-Key: k-7f3a
API->>DB: INSERT idempotency (k-7f3a, status: started), unique key
API->>P: charge, Idempotency-Key: pay-k-7f3a
P-->>API: (timeout)
C->>API: retry, Idempotency-Key: k-7f3a
API->>DB: key exists, status started
API->>P: charge again, Idempotency-Key: pay-k-7f3a
P-->>API: same charge as before (provider deduplicates)
API->>DB: store result under k-7f3a
API-->>C: 201, payment captured (once)
Here’s the beautiful part: the retry doesn’t need to know whether the first attempt worked. The key carries that knowledge for it, from your client all the way to the provider. The rules that make it hold up:
- The client generates the key once per user intent (one checkout attempt), not per HTTP request.
- The server inserts the key with a unique constraint before doing anything, so two concurrent retries can’t both proceed.
- The server stores the response and returns it for later retries with the same key; a retry with the same key but a different body is rejected.
- The key is forwarded to the provider (most major providers, such as Stripe and Adyen, accept one), so the provider deduplicates too.
- Keys expire after a day or so.
The second clue: a state machine #
Keys stop the same request from running twice. But a payment also hears from webhooks, workers and admins, and those can collide too. So each payment gets a short list of moves it’s allowed to make:
| From | Event | To | Allowed? |
|---|---|---|---|
| created | provider authorises | authorised | yes |
| authorised | capture | captured | yes |
| captured | refund (partial or full) | partially refunded / refunded | yes, up to the captured amount |
| authorised | void, or authorisation expires | voided | yes |
| captured | authorise | - | no: ignore or alert |
Enforce transitions with conditional updates (UPDATE payments SET status = 'captured' WHERE id = $1 AND status = 'authorised'), so concurrent webhooks and API calls can’t apply the same transition twice. Whoever arrives second simply finds nothing to update. The lock or retry post measures this approach under contention, and the design patterns post covers state machines in general.
The third clue: the ledger #
Even with safe retries, a balance that gets updated in place is a crime scene with no witnesses: if it’s wrong, nothing tells you how it got that way. Here’s where we borrow from accountants, who solved this one for us centuries ago. Never store “balance = 120.00” and update it. Store entries:
| Entry | Account | Debit | Credit |
|---|---|---|---|
| Order #881 captured | Revenue | 4,999 | |
| Order #881 captured | Provider clearing | 4,999 | |
| Provider fee | Fees expense | 145 | |
| Provider fee | Provider clearing | 145 |
- Every transaction’s entries sum to zero, so money can’t appear or vanish. One check on every write catches whole classes of bugs; I find that quietly wonderful.
- Entries are append-only; a mistake is fixed with a reversing entry, which keeps the history auditable.
- Balances are sums of entries (cached in a snapshot table if needed, rebuilt from entries).
- Amounts are integers in the smallest currency unit, with the currency stored next to them. Never floating point.
The witnesses: webhooks and reconciliation #
Your own records are only half the story. The provider saw the other half, and two witnesses settle what one can’t.
- The provider tells you what really happened (captured, failed, disputed, refunded) through signed webhooks. Verify the signature, store the event ID, and ignore duplicates; providers deliver at least once and out of order.
- Your API’s view and the webhook’s view meet in the state machine: whichever arrives first moves the payment; the other is a no-op.
- Reconcile daily: load the provider’s settlement report and match every line to a ledger entry. Unmatched lines in either direction are bugs or fraud, and someone looks at each one.
Other cases with the same culprit #
The same lost-response problem turns up wherever money moves, each with its own twist:
| Situation | Extra care |
|---|---|
| Checkout | Disable the button after the first click, and use an idempotency key: the UI alone isn’t enough |
| Refunds | Idempotency keys per refund request; a refund can’t exceed captured minus already refunded, checked in the same transaction |
| Payouts to sellers | Two-step: create a payout record (idempotent), then a worker sends it; never retry a payout whose outcome is unknown without asking the provider first |
Remember this
- Assume every call can time out after it succeeded.
- One idempotency key per user intent, forwarded all the way to the provider.
- Never update a balance in place: append entries that sum to zero.
Case closed: what I’d do by default #
- Idempotency keys on every endpoint that moves money, forwarded to the provider.
- An explicit state machine enforced with conditional updates.
- A double-entry, append-only ledger in integer minor units.
- Signed, deduplicated webhooks as the provider’s source of truth.
- Daily reconciliation with alerts on every mismatch.
What I appreciate most here is the humility built into the design: it assumes the network will lie to you, and it still comes out right. No single technique catches the culprit alone; together they make a double charge something the system simply won’t do.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.