Lesson 18 of 20 · 16m
Race conditions: the gap between check and act
Double-spends, limit overruns and symlink swaps — and the atomic writes, locks and constraints that close the gap.
Two requests arrive together. Both read balance = 100. Both see "enough funds". Both proceed — and you paid out 200. The check and the act were separated, and whatever fits between them is the race.
The wrong mental model: "my framework serializes requests", or "the odds are tiny." Odds are a function of attacker effort, and James Kettle's 2023 PortSwigger research ("Smashing the state machine") made these reliable: HTTP/2's single-packet last-byte sync lands multiple requests within a millisecond, and the write-up demonstrated limit-overrun, multi-endpoint and confirmation races on real applications. The classic instances are coupon and voucher codes redeemed twice, invites accepted past member caps, and quota checks bypassed — plus the older filesystem family where access() then open() lets a symlink swap in between (CWE-367; installers writing as root into /tmp are the canonical victims).
Make check-and-act one operation
Push the condition into the write. A single SQL statement is atomic:
UPDATE accounts SET balance = balance - 100
WHERE id = $1 AND balance >= 100
RETURNING balance; -- no row → the check failed, nothing was deductedLock what you read. SELECT … FOR UPDATE inside a transaction holds the row until commit — the second request waits instead of racing:
BEGIN;
SELECT balance FROM accounts WHERE id = $1 FOR UPDATE;
-- decide
UPDATE accounts SET balance = … WHERE id = $1;
COMMIT;Let constraints enforce. A UNIQUE index rejects the second insert even when both requests "passed" the existence check; INSERT … ON CONFLICT DO NOTHING claims a resource exactly once, and RETURNING tells you which side won. Constraints don't sleep between check and act — your code does. Two-phase flows (reserve, then commit) need the same atomic claim: a status='pending' row written non-atomically races identically.
Idempotency keys for retried operations. Stripe's Idempotency-Key header replays the stored response for a retry instead of double-charging: store key → result, first commit wins.
Advisory locks and isolation where invariants span rows: pg_advisory_xact_lock, or SERIALIZABLE isolation, which aborts the loser outright — retry it, that's the contract.
The same rule holds off-SQL: Redis SET key val NX EX 300 claims a name exactly once, INCR is a single atomic operation, and Lua scripts run to completion without interleaving — which is why Redis-backed rate limiters and distributed locks are built from them, not GET-then-SET. Check the row count on conditional writes too: UPDATE … WHERE balance >= 100 RETURNING returns zero rows as a result, not an exception, so it fails closed. And idempotency keys aren't only for money paths — signup, redemption and provisioning deserve the same once-only guarantee.
The subtler variant spans endpoints: a check living on one route and the write on another (/redeem validates the coupon, /confirm spends it) means an attacker who fires both legs in parallel gets the invariant for free. Kettle's write-ups include exactly these multi-endpoint races — plus single-endpoint limit overruns where a token bucket counter is read and incremented non-atomically.
The file-level twin
exists()/access() then open() is the same bug against the filesystem — and rename is atomic on POSIX only within one filesystem, so cross-device moves are copy-and-delete and reopen the window. Don't check then act — act atomically: open(path, O_CREAT | O_EXCL) to claim a name (O_NOFOLLOW keeps a planted symlink out of it — the pattern behind every safe mktemp), os.replace/rename for atomic swap, and operate on the file descriptor rather than the path where you can.
What isn't a fix
Disabling the submit button after one click is UX, not concurrency control — the second request doesn't care about your button. Client-side debounce, disabled attributes, and "we checked in JS first" all die at the same place: the attacker sends HTTP, not gestures. The enforcement layer is the database or the kernel, not the browser — and a mutex in your app code only serializes your processes; the attacker doesn't run your mutex.
Practice
Single-statement conditional writes; FOR UPDATE or unique constraints where you must read-then-write; idempotency keys on money paths; atomic O_EXCL/rename on files — and a load test that fires the same request twice concurrently before you ship it — Kettle's Turbo Intruder (sendGroup, last-byte sync) is the free tool built for exactly this.
Keep reading
Related articles from the SudoSecurity blog.
Building a Production REST API With Node.js and Express
Build a REST API in Node.js and Express the way production systems need: input validation, JWT auth, refresh token rotation, status codes, rate limiting, idempotency keys, and centralized error handling.
RSA in JavaScript Part 2: The JWT Is Where You'll Actually Meet It
Most JavaScript developers never call an RSA function directly. They verify an RS256 token, and two classic attacks turn that into an authentication bypass — both demonstrated here, both fixed by one line.
RSA Signatures: The Version in Most Tutorials Is Forgeable
Signing is encryption with the keys swapped, and that symmetry is exactly what makes the naive implementation breakable. Here are two forgeries executed against textbook RSA signatures, and what PSS does that hashing alone cannot.
Ask Java for AES and You Get ECB. Nobody Warns You.
Cipher.getInstance("AES") compiles, runs, encrypts, decrypts, and hands you the weakest mode in the box. Here is the OpenJDK source that makes that decision, and the line where ECB gets chosen for you.