Two bets, one balance
Under load, accounts in our betting wallet drained to zero while accepting more stakes than they ever held, and somebody reconciled the difference by hand the next morning. Nothing had thrown. No row was negative. The error log was clean.
That was the part that cost me the most time. I was looking for a failure, and there wasn't one. Every request had succeeded, and the total was wrong anyway.
The code that looked fine
if (stake <= 0)
return Reject("stake must be positive");
1var wallet = await db.Wallets.FindAsync(walletId);
2if (wallet.Balance < stake)
return Reject("insufficient funds");
wallet.Balance -= stake;
3await db.SaveChangesAsync();- The balance is read here and held in memory.
- The decision is made against that in-memory copy.
- The write only reaches the database here. Everything between line 4 and line 10 is the window.
This is EF Core on SQL Server, with a separate DbContext per request, tracked entities and no concurrency token. With a token configured, the second save would throw instead of silently overwriting. Read, check, write: each line is correct on its own. The bug lives in the gap between the read and the write, which is where a second request gets to run.
Two bets in the same instant
Both requests read the balance before either writes, so both pass the check. Simplified to the reads, decisions and writes that matter; other columns and the bet rows are left out.
A and B each load the wallet. Both see 100, which was true when each of them read it.
- Bet A
- read 100
- Bet B
- read 100
- Balance in the database
- 100
Step-by-step transcript
- Both read
A and B each load the wallet. Both see 100, which was true when each of them read it.
- Bet A
- read 100
- Bet B
- read 100
- Balance in the database
- 100
- Both decide
100 covers a stake of 100, so both requests accept. Neither can see the other.
- Bet A
- accepted
- Bet B
- accepted
- Balance in the database
- 100
- A writes
A saves 100 - 100 = 0.
- Bet A
- saved 0
- Bet B
- accepted
- Balance in the database
- 0
- B writes
B also computed 100 - 100 = 0 from its stale read, and saves the same value. Stakes accepted: 200. Money that existed: 100. The balance looks perfectly healthy.
- Bet A
- saved 0
- Bet B
- saved 0
- Balance in the database
- 0
Money bugs do not degrade gracefully. A double-spend costs the stake, and the stake has left the building by the time anyone notices. In my case we found it in the settlement report, not in the error log.
Take the lock before the read
The fix was to move the waiting to before the decision. The read, the check and the debit now happen in one transaction, and the read takes an update lock on the wallet row that is held until the commit. Error handling matters here too: without it, a failed insert can roll back only that statement and leave the debit free to commit.
CREATE OR ALTER PROCEDURE dbo.DebitWallet
@WalletId int,
@Stake decimal(18,2),
@Accepted bit OUTPUT
AS
1SET XACT_ABORT ON;
DECLARE @Balance decimal(18,2);
2IF @Stake IS NULL OR @Stake <= 0
THROW 50001, 'Stake must be positive.', 1;
BEGIN TRY
BEGIN TRANSACTION;
SELECT @Balance = Balance
3 FROM Wallets WITH (UPDLOCK, ROWLOCK)
WHERE Id = @WalletId;
4 IF @Balance >= @Stake
BEGIN
UPDATE Wallets SET Balance = Balance - @Stake WHERE Id = @WalletId;
5 INSERT INTO Bets (WalletId, Stake) VALUES (@WalletId, @Stake);
SET @Accepted = 1;
END
ELSE
SET @Accepted = 0;
COMMIT;
END TRY
BEGIN CATCH
6 IF @@TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;- XACT_ABORT ON makes a runtime error doom the whole transaction instead of just one statement.
- A null, zero or negative stake is refused before any transaction opens. Without this, a negative stake passes the balance check and adds money to the wallet.
- UPDLOCK on the read is the whole fix. The second bet blocks here, not later.
- By the time a waiting bet gets here, it is checking the balance the first bet actually left behind.
- The bet row is written in the same transaction as the debit.
- Any failure rolls back the active transaction and rethrows, so the debit and the bet commit together or not at all.
UPDLOCK is the SQL Server spelling. SELECT ... FOR UPDATE is the same idea elsewhere. The second bet now stops at the read until the first one commits, then reads 0 and sets @Accepted to 0 without touching the wallet. The caller checks that output and returns the insufficient-funds rejection, so acceptance and rejection are distinguishable. Same three steps, same order. They just can't interleave any more.
What it cost
Debits against a single wallet now take turns. A busy account has a throughput ceiling that more application servers won't raise, because the limit is one row in one database. Bets on different wallets mostly run in parallel, though ROWLOCK is a request, not a promise: indexes and lock escalation can widen contention, so I wouldn't claim different wallets never block each other.
I took that trade. One person can only place so many bets at once, so concurrency inside a wallet buys almost nothing, and correctness inside that wallet is the product. The new cost is also one I can watch: lock waits, deadlocks and transaction time are on a dashboard. That beats a reconciliation spreadsheet. The transaction has to stay short, with no network calls while the lock is held.
It wasn't the only option. A single conditional UPDATE ... WHERE Balance >= @Stake, followed by a check of the affected row count, makes the same decision without a separate read. Optimistic concurrency, which rejects a save if the row changed since it was read, also works. They change whether a competing request waits or retries. Neither makes the contention disappear.
Why tests didn't catch it
My tests sent one request at a time, and one request at a time is the only way this code is correct. The broken endpoint also answered 200 to both competing bets, so even a concurrent test that only checked status codes would have passed. What catches it is firing competing stakes at one wallet and asserting on the money afterwards.
- Q: Why not just raise the isolation level?
- A: Serializable can prevent this outcome, but competing transactions may deadlock or abort, and the application has to handle that. I preferred stating the rule explicitly with a lock, where the waiting happens in a place I chose.
- Q: What should the test assert?
- A: With no deposits or payouts in the test, check three things: accepted stakes don't exceed the starting balance, final balance equals the starting balance minus accepted stakes, and every accepted bet has exactly one committed debit. A nonnegative balance proves nothing here, since zero is what the broken version produced too.
The fix made the system slower in a place I can point at, in exchange for removing a bug I could only ever find after the money had gone. I'd make that trade again.
Cite this article
Mohamed Hosny, “Two bets, one balance”, www.mohamed-hosny.dev, . https://www.mohamed-hosny.dev/blog/two-bets-one-balance
Referencing this? Please credit Mohamed Hosny and link to the original page.