A race condition let a trading simulator spend money twice
Two parallel trade requests passed the same balance check and both spent the cash. Fixed with optimistic concurrency and locked in by a 100-user load test.
A financial-education AI assistant I was building had a paper-trading simulator. Users buy and sell stocks with virtual money, and the handler checks the balance on each trade. The trade endpoint had a read-check-write gap. Two requests arriving in the same millisecond would both read the balance, both decide the user could afford the trade, and both commit. Classic lost update, with a $0 floor that was easy to break through.
I fixed it with optimistic concurrency control and locked the fix in with a load test.
The old path
The trade handler read available_cash and then called account.save(). Between the read and the save, nothing stopped another request from reading the same value. On MongoDB that means two writes land and one silently overwrites the other. If both are trades of $300 against a $500 balance, the account ends at $200, down $600 total, as if $200 appeared from nowhere.
Real users rarely race the endpoint. A load test does.
The fix
findOneAndUpdate with a filter on both available_cash and the document version __v that Mongoose adds automatically. Only one of two concurrent writes matches the version, so only one commits. The other sees a stale version and retries. On retry it reads the new, lower balance and gets rejected cleanly.
I found a second place with the same shape. POST /accounts/:accountId/orders also had an unguarded account.save(). Same patch, same retry loop.
The second bug hiding behind it
While wiring the test I noticed balances were wrong on fresh accounts. cash_balance was being set to $100,000 on creation. available_cash, the field the trade handler actually reads, was defaulting to $10,000. Two fields with the same role, two defaults, silent divergence. Fixed by setting both explicitly in getOrCreateAccount.
The load test
A k6 script fires 100 virtual users at the trade endpoint concurrently. Before the fix the balance could go negative. After: 71 trades approved, 29 rejected, final cash $19.91, never below zero. The test lives as a permanent regression guard at tests/k6/simulatorOccTest.js.
What I would do differently
Write the race-condition test before the first version of the handler. Correctness tests on a single request will never catch a lost update.
The other lesson. When two fields exist for the same thing, one of them is going to drift. Prefer one source of truth. Where that is not possible, assert on account creation that the pair agrees, so the first user to hit the drift gets a loud failure, not a quiet $10,000 hole.