Race Condition

A race condition is a bug that appears only when two operations run at the same time and interleave — like two people booking the last slot at once.

Slot 10:00 is free

Request A · Asha

    Database

    slot 10:00

    free

    Request B · Ravi

      Asha (request A) and Ravi (request B) press "Book" at the same moment.

      Step 1 / 6

      In Build & Defend, Aria asks how your booking API stops exactly this. Defend your own code →

      Step by step

      The example above, written out — the same steps the animation plays.

      1. 1Slot 10:00 is free. Asha (request A) and Ravi (request B) press "Book" at the same moment.
      2. 2A checks. Request A reads the slot: free.
      3. 3B checks. Request B reads the slot before A has written anything: still free.
      4. 4A writes. A inserts Asha's booking.
      5. 5B writes too — double booked!. B already decided the slot was free, so it inserts Ravi's booking too. Two patients, one slot.
      6. 6Why tests didn't catch it. Each request is correct on its own; the bug only appears when they interleave. That is a race condition — the check and the write must happen as one step.

      What's happening?

      1. Without protection, both requests check that the slot is free before either has written, so both book it.
      2. With a lock, the second request waits until the first has finished, then sees the slot is taken.
      3. With a unique constraint, the database itself refuses the second booking, whatever the timing.

      Where you'll meet it

      Booking seats and appointments, wallet balances, stock counts, coupon redemptions — anything where two users can change the same thing at once.

      Common mistake

      Checking "is it free?" in code and then inserting, as two separate steps. Each step is correct; the gap between them is the bug.

      FAQ

      Why don't tests catch race conditions?

      Tests usually send one request at a time. The bug only shows when requests overlap, which happens under real traffic.

      Lock or unique constraint — which is better?

      A unique constraint is the last line of defence and cannot be bypassed; a lock lets you check business rules safely. Production systems often use both.

      What should the API return to the loser?

      A clear conflict — HTTP 409 — so the client can tell the user the slot was just taken.