Agent Wranglers

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

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.