Topic 3 of 5 · 5 min read
Race conditions in generated code
Goal: Spot a race condition in AI-written code and choose the transaction, lock or atomic operation that removes it.
A race condition happens when code checks something, then acts on it, and the answer changes in between. AI code is written as if one request runs at a time, so it passes every single-user test and fails under real traffic.
Check yourself · 1 of 3
Two users book the last seat at the same time and both succeed. Which pattern in the code caused it?
Why it matters
An assistant reasons about the function in front of it. It rarely asks "what if two of these run at once?" The bug is invisible in review of a single path and in unit tests, and shows up as duplicate rows, oversold stock or a balance that is off by one transfer. It is also hard to reproduce, which makes it expensive.
How to find it
Read each function and look for check-then-act: a read followed by a write that depends on the read.
- Read, decide, write. "If the username is free, insert it." Two requests both see "free".
- Read-modify-write.
count = get(); set(count + 1). Two updates both start from the same count and one is lost. - Shared mutable state. A module-level dictionary, a cache, a counter in a server that runs several workers or threads.
- Two steps that must go together. Debit one account, credit another, with no transaction around them.
For each, pick the smallest tool that closes the gap:
- A database constraint, such as a unique index. The database rejects the second insert, and you handle that error.
- An atomic statement, such as
UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0. - A transaction with the right isolation level or a row lock (
SELECT ... FOR UPDATE). - A distributed lock only when no database operation can express it.
Before and after
def reserve_seat(flight_id, user_id):
seat = db.query("SELECT seats_left FROM flights WHERE id = %s", flight_id)
if seat.seats_left > 0:
db.execute("UPDATE flights SET seats_left = seats_left - 1 WHERE id = %s", flight_id)
db.execute("INSERT INTO bookings (flight_id, user_id) VALUES (%s, %s)", flight_id, user_id)
With one seat left, two users both pass the check. Fix it by making the check part of the write:
with db.transaction():
updated = db.execute(
"UPDATE flights SET seats_left = seats_left - 1 WHERE id = %s AND seats_left > 0",
flight_id,
)
if updated.rowcount == 0:
raise SoldOut(flight_id)
db.execute("INSERT INTO bookings (flight_id, user_id) VALUES (%s, %s)", flight_id, user_id)
What goes wrong
- An in-process lock that works on a laptop but not across several server instances.
- Wrapping in a transaction and assuming that alone prevents the race; at the default isolation level the read can still be stale.
- Fixing it in the app with a sleep or a retry instead of the database.
Examples
The lost counter
const views = await redis.get(`views:${id}`);
await redis.set(`views:${id}`, Number(views) + 1);
Two requests read 41 and both write 42. Use the atomic INCR command instead.
Unique username
if not User.exists(username=name):
User.create(username=name)
Two signups with the same name both pass the check. Add a unique index on username, call create, and catch the duplicate-key error.
Key points
- Look for check-then-act and read-modify-write: a read followed by a write that depends on it.
- A unique constraint or a conditional atomic UPDATE is usually better than application-level checks.
- A transaction does not automatically remove a race; the isolation level and the locking matter.
- In-process locks and module-level state fail as soon as there is more than one worker or server.
- A single-user test proves nothing about concurrency; ask for a test that runs the call in parallel.
Common mistakes
- Trusting a check made a few lines earlier in the same function.
- Adding a mutex in one process when the app runs on several instances.
- Assuming a transaction means serial execution.
- Testing concurrency only by running the code once.
Check yourself · 2 of 3
Which change most reliably prevents two signups with the same username?
Check yourself · 3 of 3
Why does count = get(); set(count + 1) lose updates?
Practice items, not counted towards your mastery.
Start here
- Making retries safe with idempotent APIs (Amazon Builders' Library) (opens in a new tab)ArticleFree
How idempotency tokens let a client retry a request without doing the work twice.
- Timeouts, retries and backoff with jitter (AWS Builders' Library) (opens in a new tab)ArticleFree
Why every remote call needs a timeout and how capped backoff with jitter avoids retry storms.
- Error Handling Cheat Sheet (OWASP) (opens in a new tab)DocsFree
Handle errors centrally, fail safely and log enough detail without leaking it to users.
More for this topic
- Transaction Isolation (PostgreSQL documentation) (opens in a new tab)DocsFree
What concurrent transactions can see, and which anomalies each isolation level allows.
- CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition (opens in a new tab)StandardFree
The standard definition of check-then-act races, with examples and mitigations.