Lesson 5 of 13 · 20m
Shared Memory: Mutexes, Atomics, and the Races That Ship
concurrent map writes is a fatal error recover() can't catch — mutexes, RWMutex costs, typed atomics, and what -race actually proves.
The crash log said fatal error: concurrent map read and map write and the process was gone. Not a panic — recover() cannot touch a runtime fatal error. It prints the stacks and kills the binary, mid-request, mid-anything. The wrong mental model is "channels for everything" — the proverb says share memory by communicating, but a real service still shares memory, and it has to do it on purpose.
When a mutex beats a channel
Channels move data between goroutines. A mutex protects state several goroutines touch — a cache, a stats counter, a config snapshot. Forcing that state through a channel adds a broker goroutine and a serialization point where a lock is three lines:
type Stats struct {
mu sync.RWMutex
hits map[string]int64
}
func (s *Stats) Inc(k string) {
s.mu.Lock()
defer s.mu.Unlock()
s.hits[k]++
}
func (s *Stats) Get(k string) int64 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.hits[k]
}Rules that keep you alive: the lock guards specific fields — name it mu, keep it unexported, park it next to what it protects; never take locks in an order two paths disagree on; keep the critical section to data, not I/O. defer mu.Unlock() in a hot loop costs a defer per iteration — unlock explicitly when the profile says so.
RWMutex allows many concurrent readers — and each RLock/RUnlock is slower than a plain Lock because it updates a shared reader count. It earns its keep only when reads vastly outnumber writes and critical sections aren't trivial. Under heavy write pressure it buys nothing. Profile, don't assume.
Atomics for scalars
Since Go 1.19, atomic.Int64, atomic.Bool, atomic.Uint64 give race-free scalars without a lock:
var inFlight atomic.Int64
inFlight.Add(1)
defer inFlight.Add(-1)Atomics are for counters, flags, and last-value-wins snapshots. The moment the logic is "check this AND update that," you wanted a mutex — atomics compose into subtle races faster than they compose into correctness. sync.OnceValue(f) (Go 1.21) memoizes a lazy computation; sync.Once guards init exactly once and is the right answer to "initialize on first use."
sync.Map exists for two narrow cases — write-once-read-many caches and key sets disjoint per goroutine — and underperforms map + RWMutex almost everywhere else. Reach for it last, not first.
What the race detector actually does
go test -race instruments memory accesses and tracks happens-before at runtime. It finds races the code actually executes — a race on a path your tests don't run is a race you'll ship. The cost is real (the docs put it at roughly 5–10× memory and up to 20× CPU), which is why it lives in CI and canary tests, not your dev default. A found race is a logic bug even if production never glitches on it — the Go memory model gives a racy program no guarantees, not degraded ones. That map write didn't just corrupt a count; it ended the process.
go vet's copylocks check catches the cousin bug: copying a struct containing a sync.Mutex — passing Stats by value, for _, s := range servers over mutex-bearing structs. A copied mutex protects a copy of nothing.
Field notes
sync.Poolamortizes allocation on hot paths (buffers, decoders); the GC may empty it at any collection. It is not a cache, and cleared entries aren't a bug.concurrent map iteration and map writeis the same fatal class: maps tolerate zero writers-plus-readers without synchronization, full stop.- Uber's style guide (
github.com/uber-go/guide) carries the canonical production treatment of this in team-playbook form.
Try this
Write a map[string]int incremented by 100 goroutines, no lock. Run it under -race and read the report — two stacks, both accesses named. Then run it uninstrumented in a loop until fatal error: concurrent map writes kills the process. Now fix it with atomic.Int64 and again with sync.Mutex, and benchmark both — the result will surprise nobody who has profiled it before.
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.
Go Lang 1.19: Refines Generics and Memory Model
Go 1.19, the latest version of Google’s Go (Golang) programming language, has reached production availability. The update improves recently added generics and debuts an enhanced memory model. With Go Language version 1.19, released August 2, generics development focused on addressing subtle…
One Slow Call, Three Runtimes: How PHP-FPM, Python ASGI and Node Fall Over When a Dependency Takes 200 ms
I put the same 200 ms wait behind PHP-FPM, FastAPI on uvicorn and a plain Node server, then hit each one with 50 concurrent requests. Handled correctly, the async runtimes served 205-211 req/s against FPM's 19.6. One blocking call in the wrong place took both of them down to 4.98, slower than...
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.