Skip to content

Lesson 19 of 19 · 18m

Race Conditions and TOCTOU: The Check and the Use

Check-then-write across a request boundary is a race — single-packet attacks, double-spent coupons, and why the durable fix is a database predicate, not an if statement.

if (invite.used) return 409; then mark used, then grant the reward. Two requests arrive in the same millisecond. Both reads see used=false. The one-time invite just granted twice. The check ran, and it was true when it ran — time of check to time of use are different moments, and in between, the state moved.

Where TOCTOU lives in web code

Read-modify-write across a request boundary is the shape: one-time tokens (invite accepts, password resets, magic links), balances and limits (transfers, coupons, votes, free-trial counters, rate-limit buckets), stock and oversell, permission checked then action executed. The vulnerable code looks correct in review because it is correct — sequentially. Concurrency is the missing clause.

The window is milliseconds. The way you win it isn't luck, it's submission quality.

The single-packet attack

James Kettle's "Smashing the State Machine" (Black Hat 2023) showed how reliable this got: HTTP/2 coalesces around twenty requests into a single TCP packet — last-byte synchronization — so they arrive within the same sub-millisecond window on the back-end. On HTTP/1.1 the same effect comes from sending every request except its final byte, then releasing the last bytes together. Jitter was the only thing between a race bug and a reliable exploit, and this removes the jitter.

Test your own endpoints that way: N parallel last-byte-synced requests against the single-use endpoint. If N requests get N successes, the bug is real. Turbo Intruder and a ten-line asyncio.gather both do it; the gate is whether you ever looked.

The fix is in the database, not the if

  • Application locks don't scale. A mutex in one process is decoration in the other seventeen workers, pods, or regions.
  • SELECT ... FOR UPDATE in a transaction is correct — it serializes the check and the use — but it turns a hot row into a bottleneck under contention. Fine for password resets; painful on a popular coupon.
  • Atomic predicate update is the default answer: UPDATE invites SET used = true WHERE id = $1 AND used = false RETURNING id. One request returns a row and proceeds; the rest return nothing and must fail. Predicate and mutation are a single operation — there is no gap to lose. For counters it's the same shape: UPDATE coupons SET remaining = remaining - 1 WHERE id = $1 AND remaining > 0 RETURNING remaining — the decrement and the bound check are one statement, so the count can never go negative.
  • Unique constraints and idempotency keys answer "did this already happen" durably: INSERT ... ON CONFLICT DO NOTHING tells you a duplicate arrived. Stripe's idempotency-key API exists because this exact bug kept happening to payment retries; give clients a key, store it, and make replays return the original result.
  • Optimistic concurrency where it fits: a version column with compare-and-swap (UPDATE ... WHERE version = $v); the loser retries or fails cleanly.

Receipts

Egor Homakov's 2015 Starbucks gift-card bug is the canonical anecdote: two parallel balance transfers doubled the money. Bounty lore is full of the same shape — double votes, double withdrawals, reused promo codes — because check-then-write is the default form of business logic and nobody parallel-tests it.

One more target worth naming: rate-limit counters. read counter; if under limit, increment races the same way — a burst of parallel requests all read the same pre-increment value and all pass. Atomic increment (UPDATE ... SET n = n + 1 RETURNING n) or a token bucket in Redis (INCR + EXPIRE in one Lua block) closes it.

So: every state transition is a single SQL statement, or it has a constraint underneath it. Anything single-use gets parallel last-byte-synced testing. And if the fix you're writing is a lock inside one process, it isn't a fix — it's a decoration.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.