map / coding / concurrency

Coding · principle 3 of 6

Concurrency & races

A race happens when correctness depends on the interleaving of operations you don’t control.

01 · Why it’s true

Something as simple as count = count + 1 is really three steps: read the value, add one, write it back. When two threads run those steps at the same time, they can both read the same old value, and one update is lost.

Whether it happens depends on timing, so the bug can pass every test and appear only under load. The fix is to make the read-modify-write atomic: a lock (mutex), an atomic operation, or giving each piece of data a single owner.

02 · Picture it

Thread 1runs count += 1countshared memory, starts at 5Thread 2runs count += 11read → 52read → 53write 64write 6 — overwrites5count = 6, should be 7requestwhere it goes wrongstep inside one actorBoth threads read before either wrote. A lock or an atomic increment makesread-add-write one indivisible step.
WHO’S INVOLVEDThread 1runs count += 1countshared memory, starts at 5Thread 2runs count += 11Thread 1 → countread → 52Thread 2 → countread → 53Thread 1 → countwrite 64Thread 2 → countwrite 6 — overwrites5countcount = 6, should be 7requestwhere it goes wrongstep inside one actorBoth threads read before either wrote.A lock or an atomic increment makesread-add-write one indivisible step.
Two threads, one variable, one lost update.

03 · In the interview

  • Writing thread-safe code in coding rounds (for example, a counter or a cache).
  • Debugging intermittent issues that appear only under load.
  • Knowing the costs: lock contention, deadlocks, and how to avoid them (always take locks in the same order).

04 · Practice question

“Our request counter shows fewer requests than the load balancer logged. The code is counter += 1 in a multi-threaded server. Why, and how do you fix it?”

A strong answer covers

  1. += is a read, an add, and a write; two threads can interleave and lose an update.
  2. Fix with an atomic increment, or protect the update with a mutex.
  3. At high request rates, reduce contention with per-thread counters that are summed when read.
  4. Add a test that hammers the counter from many threads and checks the total.

Want to play with it? Open the interactive deep dive →