Lesson 13 of 14 · 20m
Shared Mutable State Is Where Races Live
Check-then-act in two steps is an open door — atomic primitives, single ownership, and one lock order close it.
Two requests arrive for the last seat. Both run if seats_remaining > 0, both see 1, both book. The check and the decrement were two steps, and in a concurrent system anything between two steps is an open door. That's a race condition: correctness that depends on timing — a bug that exists only when the scheduler blinks.
Check-then-act is the classic shape
if (!exists(path)) create(path) is a time-of-check/time-of-use bug — between the check and the act, the world changed. The fix is making it one indivisible step: open(path, O_CREAT | O_EXCL) fails if the file already exists, because the kernel does check-and-create atomically. Lockfiles prefer mkdir over open for the same reason — directory creation is atomic on every filesystem.
The seat-booking case has the same fix at the database level. Don't SELECT then UPDATE — let the database arbitrate in one statement:
UPDATE seats SET taken_by = $1
WHERE id = $2 AND taken_by IS NULL
RETURNING id;
-- one row back: you won it. Zero rows: someone else did, honestly.Whatever your language, the primitive you want is the one that can't be interleaved.
The expensive version
This isn't a laptop problem. Therac-25's class3 flag raced against operator input — a correction typed in under eight seconds slipped through a window in the task-switching logic, and the machine delivered roughly a hundred times the intended dose; patients died of radiation injuries between 1985 and 1987. Mars Pathfinder's July 1997 reboots were a priority inversion: a low-priority task held a mutex the high-priority bus task needed while medium-priority work kept preempting — the fix was enabling priority inheritance, a flag VxWorks already had. Neither bug was exotic. Both were shared mutable state plus timing.
The rules that keep you honest
- Mutate in one place. A field written by two owners is a race; a field owned by one goroutine, thread, or task is a program. Go's proverb says it: don't communicate by sharing memory, share memory by communicating — channels hand ownership across; mutexes lend it out.
- Hold locks for statements, not operations. Lock, update the map, unlock — then do the I/O outside the critical section.
- One lock order, globally. Two threads acquiring A-then-B and B-then-A will deadlock eventually; pick an order and never invert it.
volatileis not synchronization. Java's pre-Java-5 double-checked locking idiom was famously broken — visibility without ordering is a mirage. Reach for real atomics (atomic.AddInt64,AtomicInteger) or real mutexes.- Let the detector find them.
go test -raceand C/C++'s ThreadSanitizer watch for the interleavings you can't; Rust's type system refuses to compile most data races outright. Run detection in CI before production finds your windows for you.
One more shape deserves naming: read-modify-write on a counter. balance = balance + 100 across two requests reads the same balance, and the second write silently overwrites the first — a lost update. The fix is again one atomic step: UPDATE accounts SET balance = balance + 100, an AtomicInteger, or sync/atomic. If you fetched it, mutated it, and wrote it back, you already lost.
Immutable data makes most of this evaporate — a value that can't change can't race. That's why pure functions and readonly/final fields aren't purism; they're concurrency control you get for free.
Try this: find a shared counter or map in a service you run. Write down every writer and every read-modify-write path. Then answer honestly: what serializes them? If the answer is "nothing," that's the finding.
Pitfalls
- "It hasn't happened yet" is not evidence — races hide until load creates the window.
synchronizedon the wrong object synchronizes nothing.- Sleep-based coordination —
sleep(1)to "let it settle" — moves the bug; it doesn't remove it. - A race detector that only runs on release day is an incident scheduled.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
What is Go? The Language Google Built for Production Engineering
Go is a statically typed, compiled language built at Google in 2009. It compiles to a single binary with no runtime dependency, starts in milliseconds, and handles concurrency through goroutines and channels. Docker, Kubernetes, and Terraform are all written in Go. Here is why.
What is Rust? The Language That Makes Systems Programming Safe
Rust eliminates entire categories of bugs — null pointer dereferences, buffer overflows, data races, use-after-free — at compile time with no runtime overhead. Microsoft, Google, Amazon, and the Linux kernel all use it for systems code.
What is Java? The Language That Runs Minecraft, Your Bank, and Half the Internet
Java has been declared dead approximately forty times since 1995. It still runs Minecraft, Android, LinkedIn, Twitter's backend, and the financial systems that process your paycheck. Here is what the language actually is, how the JVM works, and why it refuses to die.
What is Python? Enterprise, Data Science, and the Backend of the Web
Python runs Instagram, Dropbox, Netflix, Spotify, and Reddit. It trains the models that power modern AI. It processes petabytes of data in enterprise pipelines. And I ignored it for years because I thought it was just for academics. Here is what changed my mind.