Topic 3 of 5 · 5 min read
Race conditions in AI-written data code
Goal: Find the race in an AI-written handler and fix it with an atomic update, a unique constraint or a row lock.
When generated code reads a value, decides in application code and writes back, two requests can interleave between the read and the write, so move the decision into one atomic statement. Assistants such as Copilot, Cursor and Claude write this shape often because it reads naturally and passes a test with one user.
Check yourself · 1 of 3
Which code shape is a read-modify-write race?
Why it matters
These bugs do not fail in review or in CI. They appear as a counter that is short by a few, two accounts with the same email, or a wallet balance that no longer matches its ledger. They are rare per request and certain at scale.
The three shapes to look for
- Read-modify-write.
value = get(); set(value + 1). Two requests read 41 and both write 42. - Check-then-insert.
if not exists(email): insert(email). Two requests both pass the check. - Check-then-act on a balance.
if balance >= amount: balance -= amount. Two withdrawals of 80 from 100 both pass the check.
The fixes, in order of preference
- Atomic update. Let the database do the arithmetic:
UPDATE accounts SET balance = balance - 80 WHERE id = 5 AND balance >= 80. Check the affected row count: 0 means the funds were not there. - Unique constraint. Put a
UNIQUEindex on the email and insert. A duplicate raises an error you handle. The constraint is the only check that cannot race. - Upsert.
INSERT ... ON CONFLICT DO UPDATEfor "create or increment". - Row lock.
SELECT ... FOR UPDATEwhen logic is too complex for one statement. Lock, then read, then write, all in one transaction. - Serializable with retry for rules that span several rows.
An application-level mutex or an in-memory flag does not work once you run more than one server process.
Before and after
// Before: passes a single-user test
const acct = await db.accounts.findById(id);
if (acct.balance < amount) throw new Error("Insufficient funds");
await db.accounts.update(id, { balance: acct.balance - amount });
// After: one atomic statement, row count tells the result
const res = await db.query(
"UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1",
[amount, id],
);
if (res.rowCount === 0) throw new Error("Insufficient funds");
How to test it
Fire 20 concurrent requests at the endpoint with a script and check the end state. A test that runs requests one after another proves nothing.
What goes wrong
- Adding a
SELECTfirst "to be safe", which only widens the window. - Relying on a cache or a lock inside one process.
- Catching a unique-violation error and returning a 500, instead of treating it as "already exists".
Examples
The view counter
posts = db.get(post_id)
db.update(post_id, views=posts.views + 1)
Under load a post with 1,000 real views shows 940. The fix is UPDATE posts SET views = views + 1 WHERE id = %s.
Signup with an email check
A generated signup calls find_by_email and inserts if nothing is found. Two double-clicks create two users. Add UNIQUE (email), insert directly, and map the unique-violation error to a friendly "this email is already registered" response.
Key points
- The race lives between the read and the write; shrink it to zero by making the decision inside one statement.
- A single UPDATE with a guard in the WHERE clause, plus a row count check, fixes most balance and counter bugs.
- A unique constraint is the only reliable duplicate check; an existence query before the insert can race.
- SELECT FOR UPDATE serializes writers on the rows you lock, inside one transaction.
- Test with concurrent requests, because sequential tests cannot reveal a race.
Common mistakes
- Trusting a passing single-user test as proof of correctness.
- Adding an extra existence check before the insert instead of a unique constraint.
- Using an in-process lock when the app runs as several processes or containers.
- Ignoring the affected row count of a guarded UPDATE.
Check yourself · 2 of 3
A signup handler checks that the email does not exist, then inserts. Duplicates appear under load. What is the most reliable fix?
Check yourself · 3 of 3
A guarded update, UPDATE accounts SET balance = balance - 80 WHERE id = 5 AND balance >= 80, affects 0 rows. What does it mean?
Practice items, not counted towards your mastery.
Start here
- Transaction Isolation (PostgreSQL documentation) (opens in a new tab)DocsFree
What read committed, repeatable read and serializable allow, and why serialization failures must be retried.
- PostgreSQL: Explicit locking (opens in a new tab)DocsFree
Row and table lock modes, FOR UPDATE, and the section on deadlocks and lock ordering.
- Jepsen: Consistency models (opens in a new tab)ArticleFree
A map of isolation and consistency models and which anomalies each one allows.
More for this topic
- PostgreSQL: INSERT (ON CONFLICT) (opens in a new tab)DocsFree
The exact semantics of ON CONFLICT DO NOTHING and DO UPDATE for atomic upserts.