· 16 min read ·
Where payment systems lose money: 9 failure modes, measured

Summary
The nine best-known ways a payment system loses money or charges twice are: repeated requests, concurrent payments against one balance, deadlocks, bank timeouts, a crash between saving and publishing, duplicated webhooks, concurrent refunds, floating-point rounding and no end-of-day check. Each was measured 10 times on PostgreSQL. Unprotected code made 950 extra charges out of 1,000 requests, charged 50 customers twice and credited a merchant 13,075 TL too much. Known patterns (idempotency key, row lock, outbox, state machine, reconciliation) brought every error to zero.
Think of a pay button. The customer taps it, money is taken, the order is confirmed. Coding that flow is quick. The hard part is keeping the money in the right place when the network drops, the bank answers late or the server crashes.
For this article nine situations were picked in which a payment system loses money or sends it to the wrong place. Each one ran on a real PostgreSQL database in two ways: first with the unprotected code most first versions contain, then with the well-known pattern that closes the hole. Every scenario was repeated 10 times, and then the money was counted.
Every number comes from an open-source lab. The code is .NET 10, the database PostgreSQL 16. The bank, timeouts and server crashes are simulated in memory; locks and constraints are the database’s own. Amounts are in Turkish lira (TL); 1 TL is 100 kuruş.
1. The same payment arrives more than once
The best-known one. The customer taps twice, or the server takes the money but the response is lost and the app sends the request again. To the server these are new payments.
In the lab 50 orders were each sent as 20 simultaneous copies. 1,000 requests in total; the correct result is 50 charges.
Unprotected code charged all 1,000. The surprise is the middle bar: code that looks at a client-supplied key, asks “have I seen this key?”, pays if not and stores the key afterwards still made 398 charges instead of 50. That is how systems behave when the key lives in a separate store such as Redis. Simultaneous copies pass the check together, because none of them has written the key yet.
The fix is an idempotency key, with one condition: it must be written in the same database transaction as the payment. The transaction starts by inserting the key into a unique table with INSERT ... ON CONFLICT DO NOTHING. A second request with the same key waits on that row until the first transaction ends. If the first succeeded, the second receives the stored response. If the first failed, the key is rolled back too and the second request does the work cleanly.
The demo below replays the moment the same payment arrives 20 times, slowed down. Toggle the protection to see the difference. The other two tabs show the next two scenarios.
2. Payments race for the same balance
A wallet holds 10 TL. 30 payments of 1 TL arrive at once. At most 10 may succeed. In the lab 20 wallets each took this load at the same time, so exactly 200 of 600 payments should have gone through.
Two kinds of unprotected code were tried, and in both all 600 went through. The difference is where the money went:
1- Code that reads the balance, computes the new value and writes balance = 900 overwrote itself. The merchant received 600 TL but wallets lost only 48.50 TL in total. 551.50 TL appeared from nowhere.
2- Code that reads and checks the balance, then decrements with balance = balance - 100, did not overwrite but checked against a stale balance. All 20 wallets ended at minus 20 TL, 400 TL in total.
There are two correct ways, and both let exactly 200 payments through in every run. The first is a row lock: SELECT ... FOR UPDATE locks the wallet row, and the second payment waits and then sees the current balance. The second is a conditional update: check and decrement in one statement, UPDATE ... SET balance = balance - 100 WHERE balance >= 100. If it updates zero rows, the balance was not enough. For single-account operations the second is faster; when several accounts must stay consistent together, the lock reads more clearly.
There is also a last line of defence: a CHECK (balance >= 0) constraint on the table. If someone forgets the lock in code, the database still rejects a negative balance.
3. Two payments wait for each other
Wallet A pays B while B pays A. The natural first version locks the payer’s row, then the payee’s. The first payment locks A, the second locks B, and each waits for the row the other holds. That is a deadlock. PostgreSQL detects it after 1 second and kills one of the payments, and a customer sees an error.
400 opposite transfers were sent between 10 pairs of wallets. With unprotected code 256 payments were killed by deadlocks and the whole batch took 28 seconds. The fix is tiny: always lock both rows in the same order, by id (WHERE id = ANY(...) ORDER BY id FOR UPDATE). Both payments then ask for A first, one waits, and no cycle can form. Result: 0 killed, 0.4 seconds.
4. The bank does not answer
The payment service calls the bank and the response does not arrive in time. The real problem is that two different situations look the same from outside: the bank may never have taken the money, or it took it and the response got lost.
In the lab, for 1,000 orders, 5% of bank calls timed out before the money was taken and 5% after. These rates are not from the real world; they were chosen to make the mechanism visible.
UnprotectedTimeout → "payment failed" → customer taps again → new payment, new charge
→Result50 customers charged twice (median of 10 runs)
ProtectedOne reference per payment → "unknown" on timeout → ask the bank by reference → retry with the same reference if needed
→Result0 double charges, 0 lost payments
The pattern has two parts. First, the payment goes to the bank with its own id, and the bank does not execute a request with the same id twice: the idempotency key from scenario 1, pointed at the bank. Second, a timeout is recorded as “unknown”, not “failed”. For unknown payments the bank’s status query is called and the decision follows its answer. In a real system a background job runs that query on a schedule.
5. The server crashes between saving and publishing
After a payment is saved, other systems must hear about it: shipping, invoicing, e-mail. Usually through a message broker such as RabbitMQ. The problem is that writing to the database and publishing a message are two separate writes. If the server dies between them, one is done and the other is not.
In the lab, every one of 1,000 orders had a 5% chance of a crash between the two steps:
1- Save-then-publish: 48 orders were paid but shipping never heard about them.
2- Publish-then-save: the opposite. 48 orders were shipped with no payment in the database.
The fix is the transactional outbox. The message is not sent to the broker directly. It is written as a row in an outbox table in the same transaction as the payment, so either both exist or neither does. A separate relay reads unsent rows, publishes them and marks them as sent.
The measurement also showed that the outbox alone is not enough. If the relay crashes after publishing but before marking the row, it publishes the same message again after restarting. Nothing is lost, but some messages arrive twice: 215 of 1,000 orders were shipped twice. The consumer needs an inbox as well: a unique table of message ids that skips any id it has already seen. With outbox and inbox together: 0 lost, 0 shipped twice.
6. Webhooks arrive twice or out of order
Payment providers usually report results by webhook: “payment pending”, then “payment succeeded”. Many providers, Stripe included, state two things in their documentation: the same event can be delivered more than once, and events may arrive out of order.
In the lab, events for 1,000 payments were duplicated with 30% probability, shuffled and handed to 8 parallel handlers. For half of the payments “succeeded” arrived before “pending”.
Code that applies every event as it comes made two mistakes. It credited the merchant again on every duplicated “succeeded”: the merchant received 13,075 TL more than it should have. And a late “pending” moved a successful payment back to pending: 501 payments ended with the wrong status.
The fix is three rules. The event id is stored in the same transaction, and a seen event is skipped. Status may only move forward, enforced in the database with UPDATE ... WHERE status = ANY(allowed previous states). And money moves not when an event arrives but when the status actually changes to succeeded. Result: 0 wrong statuses and a merchant balance correct to the kuruş.
7. Refunds race on the same payment
A refund is a payment in reverse, and the same race exists. A support agent clicks twice, or an automated rule and a person start a refund at the same moment.
In the lab, each of 20 payments of 10 TL received 20 concurrent partial refunds of 1 TL. At most 200 refunds should succeed. Code that sums previous refunds, checks and then inserts made 377. All 20 payments were refunded more than was paid, 177 TL in total.
The fix is the lock from scenario 2. The payment row keeps a “refunded so far” column, the decision is made while that row is locked, and a CHECK (refunded <= amount) constraint stays as the last line of defence. Result: exactly 200 refunds.
8. Floating point loses a kuruş
No database and no concurrency here, only the number type. For each of 1 million amounts from 0.01 TL to 10,000 TL, two everyday calculations were run.
The first is a commission: the amount as a double in lira, multiplied by the rate and rounded to the kuruş. Five rates were tried.
The result depends on the rate, which is exactly what makes the bug hard to notice. At 1.75% and 20% there were no errors; at 10%, 1,638 amounts were wrong. For example, 10% of 0.35 TL is 0.035 TL, which should round up to 0.04 TL. But double stores that number as 0.034999999999999996 and the result is 0.03. The same calculation with decimal, or with integer kuruş, was wrong in none of 5 million cases.
The second is instalments: split the amount into 3 equal parts and round each to the kuruş. For 100 TL each part is 33.33 TL, totalling 99.99 TL. For two thirds of the 1 million amounts the instalments did not add up: some customers were charged one kuruş too much, others one too little. The fix is to give the leftover kuruş to the first instalments: 33.34 + 33.33 + 33.33. The total always matches.
9. Nobody checks at the end of the day
The patterns above prevent most errors, but not all. The bank can reverse a payment on its side on suspicion of fraud, someone can make a manual correction, or there can be a bug nobody knows about yet. The only way to catch these is reconciliation: every day, compare the bank’s records with your own ledger, one by one.
In the lab one day of scenario 4 ran through both pipelines, then the bank silently reversed 0.3% of the charges. The reconciliation job matched both sides by charge id. In the unprotected pipeline it found 55 differences: mostly double charges the bank had and our ledger did not, plus a few payments we showed as successful that the bank had reversed. In the protected pipeline it found only the bank’s own reversals, 3 on average. Protected code could not have prevented those. Only the end-of-day comparison showed them.
Summary
| Failure mode | Unprotected | Fix | Protected |
|---|---|---|---|
| Repeated request | 950 extra charges in 1,000 requests | Idempotency key, same transaction | 0 |
| Concurrent payments | 551.50 TL from nowhere, or 400 TL negative | Row lock or conditional update | 0 |
| Deadlock | 256 of 400 payments killed | Lock in id order | 0 |
| Bank timeout | 50 customers charged twice | Reference and status query | 0 |
| Crash between save and publish | 48 orders never reached shipping | Outbox and inbox | 0 |
| Duplicated webhooks | 13,075 TL too much, 501 wrong statuses | Event id and state machine | 0 |
| Concurrent refunds | 177 TL refunded too much | Locked refund total | 0 |
| Floating point | 2,716 wrong commissions | decimal or kuruş, allocate the remainder | 0 |
| End of day | 55 differences, invisible if nobody looks | Reconciliation | Only the bank’s reversals |
All unprotected numbers are the median of 10 runs. On the protected side not one of the 10 runs produced a single error, and the lab’s tests check that again on every run.
Limits
The failure rates (5% timeouts, 5% crashes, 30% duplicated webhooks) were not measured on a real system; they were chosen to make the mechanism visible in a few minutes. In reality they are much rarer. But for a system handling hundreds of thousands of transactions a day, rare happens daily. The simulated bank does not model any real bank’s API. Concurrency results vary from run to run; minimum and maximum values are in the repository. Measurements were taken on 27 November 2026 on a 4-core machine, with the application and the database on the same machine.
Three of these patterns (idempotency key, row lock and lock ordering) are implemented, together with a double-entry ledger, in Payment Core, a small payment core I am working on. The lab measures each failure on its own; Payment Core puts the fixes together in one working system. Refunds, an outbox, payouts through a bank simulator and end-of-day reconciliation are in the same repository.
I prepared the code and measurements with Claude Code. Anyone can reproduce the same results on their own machine with one command from the repository. Which of these nine has bitten your system?
FAQ
- Isn't it enough to keep the idempotency key in Redis?
- No. With the key in a separate store, "check, then pay" becomes two steps and concurrent copies pass the check together. In the measurement this approach still made 348 extra charges out of 1,000 requests. Writing the key in the same database transaction as the payment, under a unique constraint, brought extra charges to zero.
- Should a bank timeout mark the payment as failed?
- No. A timeout means "unknown". In the measured scenario half of the timeouts happened after the money was taken. Move the payment to an unknown state, ask the bank what happened using the same reference, and reuse that reference if you retry.
- Does an outbox deliver each message exactly once?
- No, at least once. If the relay crashes after publishing but before marking the row, it publishes again. In the measurement 215 of 1,000 orders were shipped twice. The consumer needs an inbox table that stores message ids and skips repeats.
- Should money be stored as decimal or as integer minor units?
- Both give correct results; double does not. With double, thousands of commissions were off by one kuruş at some rates, while decimal and integer kuruş had no errors. Integer minor units in the database and the API are the simplest option.
- With these patterns in place, is reconciliation still needed?
- Yes. No code can prevent a reversal made on the bank's side or a manual correction. In the measurement, only the end-of-day comparison found the payments the bank silently reversed, even in the protected pipeline.
Sources
- payment-failure-lab (code, tests and all results)
- Payment Core (a payment core where the patterns work together)
- Full measurement results (JSON)
- PostgreSQL, explicit locking and deadlocks
- PostgreSQL, INSERT ... ON CONFLICT
- Stripe, idempotent requests
- Stripe, duplicate and out-of-order webhook events
- Transactional outbox pattern (microservices.io)
Comments
No comments yet. Be the first to write one.