Race conditions and TOCTOU
Two requests that each pass a check alone can break an invariant together.
Remember: Put the condition and the state change in one atomic statement, and check how many rows it changed.
A race condition happens when the outcome depends on the timing of concurrent requests. The classic form in payments is time-of-check to time-of-use (TOCTOU): you check a condition, then act on it later, and another request changes the state in between.
- The balance is 100. Two requests each want to move 80.
- Both read 100 and both pass the check.
- Both debit. The balance ends at -60.
const from = await db.account.findUnique({ where: { id: fromId } });
if (from.balanceMinor < amount) throw new Error("Insufficient funds");
await db.account.update({
where: { id: fromId },
data: { balanceMinor: { decrement: amount } },
});
const debit = await tx.account.updateMany({
where: { id: fromId, balanceMinor: { gte: amount } },
data: { balanceMinor: { decrement: amount } },
});
if (debit.count !== 1) throw new Error("Insufficient funds");
Why in-memory locks fail
A Map or a mutex lives inside one process. With several serverless instances or replicas, each one has its own copy of the lock, so the race is still there.
Atomicity
Debit and credit must be one transaction, so either both happen or neither does. Always check the rows affected: zero rows means the condition was not met.
Test it properly: send 20 identical requests in parallel and check the final balance, not the response of a single request.
Questions to ask yourself
- Which state does this code read, and which does it change, in separate steps?
- What happens if two identical requests arrive together?
- Are the debit and the credit in one transaction?
Practise this
- Two debits in parallel · Business logic
- Coupon redeemed twice · Business logic