What is Race condition?
A class of bug where two concurrent operations interact incorrectly because the order of their steps is not enforced. Common security manifestation: TOCTOU (time-of-check-time-of-use) where a permission is checked, then the protected action runs, but the state changed in between.
Full explanation
Race conditions occur when correctness depends on operation ordering that is not guaranteed by the runtime. Security-critical example: a function checks 'does user have N credits' (read), then deducts N credits (write). If two concurrent invocations both pass the check before either deducts, both deduct successfully — user gets 2N value for N credits. The defense is making check + action atomic: a single SQL UPDATE with a WHERE clause that includes the precondition (`UPDATE accounts SET credits = credits - 5 WHERE user_id = X AND credits >= 5`), or a database transaction with appropriate isolation level (SERIALIZABLE or row-level locking).
Example
Stripe checkout flow: backend reads `cart.total`, charges card for that amount, then marks the cart as paid. If a concurrent request modifies the cart between the read and the charge, the user is charged the wrong amount. Fix: lock the cart row at the start of checkout (`SELECT ... FOR UPDATE`), or store the amount in the Stripe payment intent at cart-finalization time and use it instead of re-reading.
FAQ
How do I find race conditions in my code?
Look for sequences of (read → check → write) on the same resource where another concurrent operation could change state between steps. Pattern: `if (await db.read(...)) { await db.write(...) }`. The interval between read and write is exploitable. Static analysis is bad at finding these; sandbox-replay with concurrent attackers (Securie's race-condition specialist, alongside the MVP) catches them empirically.
What's TOCTOU?
Time-Of-Check-Time-Of-Use: the canonical race-condition shape. Check a precondition (file exists, user has permission, account has balance), then perform the action that depends on the precondition. If the state changes between check and use, the action runs against state the check did not validate. Common in filesystem operations and distributed systems.