Q7 · How would you prevent race conditions in a high-throughput workflow?
Back to 24 Architecture Questions.
The question is not “use locks”. The axis it turns on: which invariant must hold across concurrent writers, and what enforces it. A race condition is two writers breaking one invariant between them: both read a balance of 100, one writes 90, the other writes 110, and the withdrawal is silently gone. No tool choice means anything until that invariant is a sentence.
What the answer should contain
Name the invariant before naming a tool. “Balance never goes negative”, “one seat per ticket”, “counters move by exact deltas”. Until the invariant is a sentence, lock choices are superstition.
Enforcement has a hierarchy, ordered by throughput.
- Atomic primitives (CAS, conditional update): the check and the write are one indivisible
step (
UPDATE ... WHERE balance >= 10). Fastest, works only when the invariant is local to one record. - Optimistic concurrency (version column): writers proceed; the commit verifies the version and losers retry. High throughput until contention makes retries expensive.
- Pessimistic locks (row locks, distributed locks): throughput drops, but waits are bounded. Locks must be short, acquired in a consistent order (deadlock prevention), and expire safely.
- Single-writer serialization: funnel all writes for a key into one queue partition or one actor. Concurrency for that key disappears, ordering comes free, and the queue’s rate becomes the ceiling.
Pick by contention, not by habit. Local invariant, low contention: CAS. Low contention, multi-record: optimistic. Multi-record invariant under contention: transactions and locks. Pathologically hot key: single writer per key, so “high throughput” and “one writer” stop contradicting each other.
Keep the critical section minimal. Read and lock, copy data out, compute outside, write back with the check. The longer a lock is held, the lower the ceiling.
Test the invariant under concurrency. N parallel writers against the real workflow with an assertion on the invariant. Sequential unit tests cannot lose a race; parallel load can.
Measure contention. Lock wait time, CAS retry rate, queue depth per key. Rising retries mean the wrong level of enforcement was picked for the contention profile.
Ideas worth mentioning out loud
- “A race is two writers and no arbiter. Name the invariant, then pick the cheapest arbiter that still holds it at your throughput.”
- Shard the arbiter: one queue partition or actor per key turns a global bottleneck into N independent ones.
- Optimistic concurrency scales beautifully until about one in ten writers loses its round; then the retry storm arrives, and the timeouts, connection pools, and retry caps you set start absorbing it instead of the database.
Follow-ups to expect
- Distributed locks, Redis, Redlock? Useful for per-key mutual exclusion with expiry and fencing tokens; move to a consensus store when correctness must survive node failure.
- What about read-modify-write in application code? That is the race itself. Push the check into the atomic layer.
- How do you prove it holds? The invariant assertion under concurrent load, run in CI, not code review.
Red flags in an answer
- “We will add a lock if it becomes a problem.”
- Locks with no timeout or no acquisition order.
- Process-level mutexes guarding data another process also writes.
- An invariant that exists only as an accident of current timing.
Sources
- Explicit Locking, PostgreSQL documentation: the pessimistic tier in a real engine. Row locks, lock ordering, and deadlocks, from the database that has to make them work.
- Single Writer Principle, Martin Thompson: the serialization tier, from the LMAX work that made single-writer designs a known quantity in high-throughput systems.