DAT-16Required
Make conditional writes
Put the condition into the write itself, so the database decides atomically. Never read a value, decide in the app and write it back.
How to do it
Use UPDATE … WHERE balance >= $1, a unique constraint or INSERT … ON CONFLICT. Check the number of rows changed. For records edited by people, add a version column and update only when the version still matches. The race conditions rule shows the attack.
Examples
SQL example
UPDATE accounts SET balance_cents = balance_cents - $1, version = version + 1
WHERE id = $2 AND version = $3 AND balance_cents >= $1;
-- 0 rows changed: someone else changed it first, or the balance is too low
How to check
A test forces the race. Two transactions read the same coupon, wait at a barrier, then both redeem it. One write changes 1 row and the other changes 0.
Sources
Related rules
- ARC-80 Take locks in one written order in Clean code and architecture
- ARC-40 Guard state that concurrent code shares in Clean code and architecture
- TST-62 Run the tests with a race detector in Testing
- API-33 Stop lost updates with ETags in API design
- APS-53 Make each change happen exactly once in Application security
- PAY-13 Move orders through a fixed set of states in Payments and billing
- SCL-8 Keep locks and counters in a shared store in Scaling
- USG-7 Hold credits before costly work and settle after in Usage-based billing
- ECM-7 Decrement stock in one conditional update in E-commerce and fulfilment
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/transactions-and-concurrency/conditional-writes">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.