Find the bug · #44 · Races Medium JavaScript
Two withdrawals overdraw the wallet
Two withdrawals at the same moment both get paid, though the wallet only covered one.
On this page
The report
A wallet app lets users withdraw to their bank. A user with ₹100 tapped Withdraw ₹80 on their phone and laptop at the same moment. Both withdrawals were paid out, and the wallet still says ₹20.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Withdraws from a wallet. The balance lives in a database (db calls are async).
async function withdraw(db, id, amount) {
const balance = await db.get(id);
if (balance < amount) throw new Error('Insufficient balance');
await db.set(id, balance - amount);
return balance - amount;
}Read it, then pick a line.
Both withdrawals read the balance before either one writes. What do they both see?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
// A stand-in for the database: every call takes a moment, like a real one.
function makeDb(balances) {
const tick = () => new Promise((r) => setTimeout(r, 5));
return {
async get(id) { await tick(); return balances[id]; },
async set(id, value) { await tick(); balances[id] = value; },
// One step in the database, like UPDATE ... SET balance = balance - ? WHERE balance >= ?
async decrementIfAtLeast(id, amount) {
await tick();
if (balances[id] < amount) return null;
balances[id] -= amount;
return balances[id];
},
};
}
const balances = { asha: 100 };
const db = makeDb(balances);
const results = await Promise.allSettled([withdraw(db, 'asha', 80), withdraw(db, 'asha', 80)]);
console.log(results.map((r) => (r.status === 'fulfilled' ? 'paid out 80' : r.reason.message)).join(', '));
console.log('balance: ' + balances.asha);It prints
paid out 80, paid out 80 balance: 20
It should print
paid out 80, Insufficient balance balance: 20
Show the answer: the bug, the fix, and how you’d find it
The bug (lines 3, 4, 5)
Lines 3 to 5 read the balance, check it, and write the new balance as three separate steps, with an await in between. Two withdrawals running at once both read ₹100, both pass the check, and both write ₹20: ₹160 paid out of a ₹100 wallet. The check and the update must be one step in the database, so the second withdrawal sees what the first one did.
The fix
1// Withdraws from a wallet. The balance lives in a database (db calls are async).2async function withdraw(db, id, amount) {3 const balance = await db.get(id);4 if (balance < amount) throw new Error('Insufficient balance');5 await db.set(id, balance - amount);6 return balance - amount;3 const left = await db.decrementIfAtLeast(id, amount);4 if (left === null) throw new Error('Insufficient balance');5 return left;7}How you’d find it
- Reproduce it the way it happened: two withdrawals started together with
Promise.all, not one after the other. Run them one at a time and the bug hides. - Write down the order of events: A reads 100, B reads 100, A writes 20, B writes 20. Each one checked a balance that was already out of date.
- That’s a check-then-act race. Anything that lets two requests through the same gap (an
await, a network call) can cause it.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
function makeDb(balances) {
const tick = () => new Promise((r) => setTimeout(r, 5));
return {
async get(id) { await tick(); return balances[id]; },
async set(id, value) { await tick(); balances[id] = value; },
async decrementIfAtLeast(id, amount) {
await tick();
if (balances[id] < amount) return null;
balances[id] -= amount;
return balances[id];
},
};
}
const balances = { ravi: 100 };
const db = makeDb(balances);
const results = await Promise.allSettled([withdraw(db, 'ravi', 70), withdraw(db, 'ravi', 70)]);
assert.equal(results.filter((r) => r.status === 'fulfilled').length, 1);
assert.equal(balances.ravi, 30);Where else this bites
- Booking the last seat, using a coupon “once”, claiming a username.
- SQL:
SELECTthenUPDATEwithout a transaction orSELECT … FOR UPDATE.