Module 5 · Distributed systemsLesson 51 of 886 minIntermediate

Race conditions

A race condition is when the result depends on the timing of things running at once. "Check, then act" is the classic trap.

Try it

Play "Check, then write" and count tickets sold. Then compare the atomic update and the row lock.

A race condition is a bug where the outcome depends on which of two concurrent operations happens first. Code that is correct when run alone becomes wrong when run twice at the same time.

The classic shape: check, then act

stock = read_stock(ticket)
if stock > 0:
    write_stock(ticket, stock - 1)
    sell()

Two requests run this together. Both read 1, both pass the check, both sell. This "check-then-act" pattern appears everywhere: unique usernames, coupon redemption, bank balances, seat booking.

The other common shape is read-modify-write: two requests read a counter of 41, both add 1, both write 42. One increment is lost.

Fixes

  • Atomic operations: UPDATE ... SET n = n - 1 WHERE n > 0 or Redis INCR. The check and change happen in one indivisible step.
  • Unique constraints: let the database reject the second username or the second redemption of a coupon.
  • Optimistic concurrency: store a version number; write only WHERE version = 7, and retry if someone else changed it first.
  • Locks: SELECT ... FOR UPDATE, or a distributed lock, so the second request waits.
  • Single owner: route all operations for one item to one worker (for example, by partitioning a queue by ticket id), so they never run at the same time.

Why they're nasty

Races depend on timing. They pass every test on a quiet laptop and appear only under load, in production, rarely enough to be hard to reproduce. When you see "check, then act" or "read, change, write" on shared data, ask what happens if two run at once.

Quick check

Which is a safe way to sell the last ticket exactly once?