map / coding / concurrency / interactive

Coding · interactive deep dive

Concurrency & race conditions

The principleA race condition exists when correctness depends on how operations from different threads interleave — and even counter++ is a read, a modify, and a write that another thread can slip between.
01

You are the scheduler.

Two threads each increment a shared counter once. You decide which thread runs next. Find the interleaving that loses an update, then turn on the mutex and try again. Finally, let a random scheduler run hundreds of times and look at the spread of results.

Two threads · counter++ each · expected result: 2
Thread 1 · r = –
2r = r + 1 // add
3counter = r // store
Thread 2 · r = –
2r = r + 1 // add
3counter = r // store
Step the threads in any order you like.
shared counter
0
mutex held by
n/a
counter++ is three steps, not one. Try loading in both threads before either stores.

The simulator switches threads at random after every instruction. Real schedulers switch far less often, which is exactly why races slip through tests and show up under production load.

02

Why it happens.

counter++ compiles to a load into a register, an add, and a store. If both threads load before either stores, both write back the same value, and one increment disappears — a lost update. Nothing crashes; the answer is just wrong, and only sometimes.

That “only sometimes” is what makes races dangerous. The window between load and store is tiny, so tests on an idle laptop almost always pass. Under production load, with many cores and many threads, the rare interleaving becomes routine.

03

The fixes, from simplest to most scalable.

  • Mutex: make load–add–store a critical section. Simple and correct; contention serializes threads.
  • Atomic operations: hardware read-modify-write (fetch-and-add, compare-and-swap) does the increment as one indivisible step.
  • Don’t share: give each thread its own counter and sum at the end, or pass messages to a single owner. No shared mutable state, no race.

The same pattern appears far beyond threads: two requests reading and writing the same database row, two cron jobs on different hosts, check-then-act on a file. The tools change — transactions, conditional writes, compare-and-set on a version number, leases — but the shape is identical.

04

How it shows up in interviews.

Coding rounds

“Make this rate limiter / cache / counter thread-safe.” Name the shared state, then choose lock, atomic, or no sharing.

Code review

“What’s wrong with this code?” Look for check-then-act and read-modify-write on shared state.

Distributed

“Two workers process the same job.” The same race at system scale: idempotency, leases, and conditional writes.

05

A sample question, and a strong answer dissected.

The question“Our service counts requests per customer in an in-memory map, and the totals come out lower than the load balancer’s logs. The handler does counts[customer] += 1 from many threads. What’s wrong, and how would you fix it?”
Name the race

“counts[customer] += 1 is a read, an add, and a write. Two threads can read the same value and both write back value + 1, losing an increment. Undercounting is exactly the symptom of lost updates.”

Identifying the read-modify-write precisely is the core of the answer.

Spot the second race

“There may be a second problem: inserting a new customer can modify the map’s internal structure. In many languages, concurrent writes to an unsynchronized map can corrupt it or crash, not just miscount.”

Noticing the map itself is shared state shows real depth.

Fix simply

“The simplest correct fix is a mutex around the update, or a concurrent map with an atomic increment operation. I’d write a test that hammers it from many threads and checks the exact total.”

Starting with the simplest correct fix is good engineering judgment.

Fix for scale

“If one hot lock becomes a bottleneck, shard: per-thread or striped counters summed on read, since we read totals far less often than we write them.”

Discussing contention shows you think about performance, not just correctness.

Prevent recurrence

“I’d also run tests under a race detector where the language has one — Go’s -race or ThreadSanitizer for C/C++ — since races rarely show up in ordinary testing.”

Tooling over vigilance is the SRE mindset.

06

Common pitfalls.

“It passed the tests”Races are timing-dependent; passing tests prove little.
Check-then-act“If not exists, create” is a race unless the check and the act are one atomic step.
Locking reads onlyEvery access to shared mutable state — reads and writes — must use the same lock.
Lock orderingTwo locks taken in different orders by different threads is a deadlock waiting to happen.

Back to the principle

Concurrency — the principle

Read →