How Do You Prevent Race Conditions in Financial Code?
Two requests read the same balance at the same moment. Both update it. One update silently disappears. In a billing system, that’s not a bug, it’s lost money. Here’s how we prevent it, and when we’d choose differently.
In short: When two operations change the same financial record at once, one can overwrite the other: the classic lost update. There are three main defences. Pessimistic locking (SELECT ... FOR UPDATE) locks the row when you read it, so other writers wait. Optimistic locking adds a version number and rejects an update if someone else changed the row first. Atomic conditional updates do the check and the change in one SQL statement. In our billing and wallet code we use pessimistic row locks in more than 20 places, because our money operations call a payment gateway in the middle, and a conflict detected after a customer was charged is too late. This article explains the principles we follow and the trade-offs.
The race condition, in one picture
A practice wallet holds a balance. Two operations arrive at almost the same time: a subscription payment credits the wallet, and a processing fee debits it.
Nothing crashes. No error is logged. The numbers are simply wrong, and they stay wrong until someone reconciles the books. That’s why race conditions in financial code are so dangerous: they’re silent.
The same pattern appears everywhere money moves:
- two staff members changing the same subscription at once;
- a scheduled renewal job running while a staff member cancels the subscription;
- a retry arriving while the original request is still in progress;
- two background workers picking up the same record.
Three ways to prevent it
1. Pessimistic locking: SELECT ... FOR UPDATE
Lock the row at the moment you read it. Any other transaction that tries to lock the same row waits until you commit or roll back.
BEGIN;
SELECT * FROM wallets WHERE location_id = 42 FOR UPDATE; -- row locked
-- calculate, call services, update
UPDATE wallets SET total_credit = total_credit + 100 WHERE location_id = 42;
COMMIT; -- lock releasedIt’s called pessimistic because it assumes a conflict will happen and prevents it up front.
2. Optimistic locking: a version number
Don’t lock anything. Give each row a version column. When you update, require that the version hasn’t changed since you read it, and increment it.
-- read: balance = 1000, version = 7
UPDATE wallets
SET balance = 1100, version = 8
WHERE id = 42 AND version = 7;
-- 0 rows updated means someone else changed it first: retry or rejectIt’s called optimistic because it assumes conflicts are rare and only checks at the end.
3. Atomic conditional updates
For simple changes, skip the read altogether and let the database do the check and the change in one statement:
UPDATE wallets
SET balance = balance - 500
WHERE id = 42 AND balance >= 500;
-- 0 rows updated means insufficient balanceThere’s no window between reading and writing, so there’s nothing to race.
The debate: which one should you use?
| Comparison | Pessimistic lock | Optimistic version check | Atomic update |
|---|---|---|---|
| When the conflict is caught | Before any work starts | At the final write | At the write |
| Behaviour under contention | Others wait (or fail fast) | Losers retry | Losers get 0 rows |
| Works with external calls mid-operation | Yes | Poorly | Not applicable |
| Complexity | Low | Retry logic needed | Lowest |
| Main risks | Lock waits, deadlocks, long-held locks | Retry storms, wasted work | Only fits simple changes |
| Best for | Multi-step money operations with side effects | Short edits where conflicts are rare | Counters and balances changed in one step |
The deciding question for us was simple: does the operation call something outside the database before it writes?
Why we chose pessimistic locks for money
Most of our financial operations look like this: read the subscription, calculate proration, call the payment gateway, then record the invoice, the subscription change and the wallet transactions.
With optimistic locking, a conflict is discovered at the final write. By then the gateway has already charged or refunded the customer. You’d have detected the race correctly and still be left with money that moved for an operation you’re about to reject.
With a pessimistic lock, the second request waits (or fails fast) before it calculates anything or calls the gateway. Only one operation on a subscription can be in progress at a time. The lock protects the database, and the idempotency guard described in the previous article protects the gateway call.
The principles we follow
Across the billing and wallet code we’ve applied the same principles repeatedly.
1. Lock the record that owns the money
We lock the subscription row for subscription changes, and the wallet row for wallet credits and debits. Not a parent record, not a whole table: the single row whose state the operation depends on.
2. Lock before you read the values you’ll use
The lock is taken in the same query that fetches the record, before any calculation. If you read first and lock later, you can calculate from a stale value. In our services, the fetch method is the locking method.
3. Re-check state after you get the lock
Our scheduled jobs (renewals, retries, automatic cancellations) first collect a list of candidate IDs, then lock each record one at a time. Between those two steps, a staff member might have cancelled the subscription, or another worker might have processed it. So after taking the lock, the job checks the status again, and skips the record if it has changed.
4. Lock only the table you mean
When a query joins several tables, a plain FOR UPDATE can lock rows in all of them. We use FOR UPDATE OF <table> to lock only the main record, so loading related data (the patient, the package, the coupon) doesn’t lock those rows too.
SELECT ...
FROM subscriptions s
JOIN packages p ON p.id = s.package_id
WHERE s.id = :id
FOR UPDATE OF s; -- locks the subscription, not the package
5. Fail fast on hot rows
A wallet can be touched by many operations. Waiting in a queue for a wallet lock can tie up workers and stretch response times. For wallets, and for cancellations, we use FOR UPDATE NOWAIT: if the row is already locked, the request fails immediately instead of waiting.
Choosing between waiting and failing fast is a deliberate decision per operation:
| Use NOWAIT when… | Wait for the lock when… |
|---|---|
| The row is hot and waits could pile up | Conflicts are rare and short |
| Failing and retrying is acceptable | The caller can’t easily retry, such as a background job |
6. Keep transactions short, and know when they aren’t
Locks are released at commit, so a long transaction means a long lock. We keep calculation and database work tight.
We’re honest about the exception: in payment flows, the lock is held while the gateway call happens. That’s the price of catching the conflict before money moves. We accept it because the lock covers only one subscription, so it only blocks other operations on that same subscription, and those should wait.
7. Snapshot the ledger after every change
Every wallet credit and debit also records a snapshot of the wallet’s totals at that moment. If something does go wrong, the history shows exactly when the numbers diverged.
8. Combine locks with idempotency
Locks stop two requests running at the same time. They don’t help when the same request is retried after a partial failure. That needs an idempotency guard, which we covered in the previous article. In financial code you need both.
Beyond balances: matching orders on a trading platform
These principles aren’t limited to wallets and subscriptions. On a fractional real-estate trading platform I worked on, we wrote the engine that matches buy and sell orders and generates trades, working the way a stock exchange does, with market orders and limit orders.
Order matching is one of the hardest concurrency problems in finance, because a single trade changes several records at once: the buy order, the sell order, both investors’ holdings and both cash balances. The same principles apply, with a few additions:
- Lock both orders before matching. Two incoming orders must not both match against the same resting order.
- Always lock in the same order, for example by order ID. If one transaction locks order A then B, and another locks B then A, they deadlock.
- Re-check the remaining quantity under the lock. An order that was open when it was read may already be partly or fully filled.
- Write the trade and every balance change in one transaction. Either the whole trade happens, or none of it does.
- Handle partial fills explicitly. A large order can match several smaller ones; each match reduces the remaining quantity and leaves the rest of the order on the book.
What we’d improve
- Map lock failures to a clear response. When a NOWAIT lock can’t be acquired, the request fails, but today that doesn’t always surface as a clear “busy, please retry” message. A specific status code and message would make retries cleaner for users and clients.
- Document lock ordering. When an operation locks more than one row, for example a subscription and then a wallet, every code path should lock them in the same order to avoid deadlocks. That should be a written rule in our agent instructions, not just a habit.
- Use atomic updates where they fit. Some balance adjustments could be a single conditional
UPDATEinstead of lock-read-modify-write. It’s simpler, and it holds the lock for less time. - Measure lock waits. Database monitoring can show which rows are contended and for how long. That data should drive the “wait or fail fast” choice.
Optimistic locking isn’t wrong; it’s for different work
None of this means optimistic locking is a poor choice. It’s excellent for:
- editing profiles, settings and documents where conflicts are rare;
- long user sessions where holding a lock would be unreasonable;
- high-read, low-write data where locks would add needless waiting.
The point is to choose per operation, based on what happens between the read and the write. For us, when a payment gateway sits in the middle, the answer is a lock.
The forward deployed angle
Clients rarely ask for “correct concurrency control”. They ask for balances that are right. A forward deployed engineer has to spot where race conditions can hide in the client’s financial flows, often before anyone has seen one, and choose the right defence for each. Learn more about how our forward deployed engineers work.
Key takeaways
- Race conditions in financial code are silent: no crash, just wrong numbers.
- Pessimistic locks catch conflicts before work starts; optimistic locks catch them at the end; atomic updates avoid the window entirely.
- If an operation moves money through an external service before writing, catch conflicts before the call, which means a pessimistic lock.
- Lock the record that owns the money, lock as you read, and re-check state after locking.
- Use
FOR UPDATE OFin joined queries andNOWAITon hot rows. - Pair locks with an idempotency guard: locks handle concurrency, idempotency handles retries.
Frequently asked questions
What is a race condition in a database?
A race condition happens when two operations read and update the same data at the same time, and the final result depends on which finishes last. The most common form is a lost update, where one write silently overwrites another.
What does SELECT FOR UPDATE do?
It locks the selected rows until the transaction commits or rolls back. Other transactions that try to lock or update those rows must wait, or fail immediately if they use NOWAIT.
What is the difference between pessimistic and optimistic locking?
Pessimistic locking prevents conflicts by locking data when it’s read. Optimistic locking allows concurrent reads and detects conflicts when writing, usually with a version number, then retries or rejects the losing update.
Which is better for payments?
For payment flows that call an external gateway before writing, pessimistic locking is usually safer, because it stops a conflicting operation before any money moves. Optimistic locking would detect the conflict only after the charge.
What does NOWAIT do?
It makes a lock request fail immediately if the row is already locked, instead of waiting. It’s useful on heavily used rows, where waiting could pile up requests.
Do I still need idempotency if I use locks?
Yes. Locks prevent two operations running at the same moment. Idempotency prevents the same operation from taking effect twice when it’s retried after a partial failure.
