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.

One writer at a time Without an arbiter, two writers both land on the shared state and the last write wins, losing one update. With an arbiter in front of the shared state, one writer is admitted at a time and the invariant holds. FIGURE 7 ONE WRITER AT A TIME The Race Writer A writes 90 Writer B writes 110 Shared State balance both read 100; last write wins, one update is lost The Gate Writer A writes 90 Writer B writes 110 Arbiter lock, CAS, queue Shared State balance the arbiter admits one writer at a time; the invariant holds

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.

  1. 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.
  2. Optimistic concurrency (version column): writers proceed; the commit verifies the version and losers retry. High throughput until contention makes retries expensive.
  3. 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.
  4. 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

Follow-ups to expect

Red flags in an answer

Sources