Race Conditions, the Race Detector, Deadlocks, Concurrency vs Parallelism
"If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever." — The Go Memory Model, go.dev/ref/mem (Version of June 6, 2022)
Summary: A data race is two unsynchronised accesses to the same memory, at least one a write; in Go it is a bug with no defined result for multi-word values. A race condition is any outcome that depends on timing, and it can exist in perfectly race-free code. A deadlock is a set of goroutines each waiting for another; the runtime catches only the case where every goroutine is blocked. Concurrency is how you structure the program; parallelism is whether it runs on several cores at once, and races exist either way. Focus: The memory model and happens-before, DRF-SC, torn reads of strings, slices and interfaces, the race detector (go test -race, ThreadSanitizer, GORACE, reading WARNING: DATA RACE reports, cost, CI), the six ways to fix a race (mutex, channel ownership, atomics, immutability, confinement, copying), the classic bugs (concurrent map writes, loop variable capture before Go 1.22, lazy init without sync.Once, check-then-act, TOCTOU, append from goroutines, closing shared resources), deadlocks (channels, lock ordering, recursive sync.Mutex, WaitGroup misuse, blocking select, unclosed HTTP bodies), diagnosis (SIGQUIT, GOTRACEBACK, pprof goroutine and goroutineleak profiles, runtime.Stack, go-deadlock), livelock and starvation, GOMAXPROCS, and testing (-race -count, stress loops, fuzzing, testing/synctest). Learning goal: Read a race report and fix the cause rather than the symptom, tell a data race from a race condition, design lock order and goroutine lifetimes so deadlocks cannot form, find a hang in production from a goroutine dump in minutes, and write concurrency tests that fail reliably when the code is wrong.
This page is the complete reference for concurrency bugs in Go: how they arise, how the toolchain finds them, and how to make them impossible. It assumes the primitives and does not re-teach them: goroutines and channel semantics are in Goroutines & Channels; select patterns in select; cancellation in context; the API of Mutex, RWMutex, Cond, Once, Pool and atomics in sync & atomic; bounded pools and errgroup in Worker Pools, Pipelines; test tooling in general in Testing & Benchmarking. Database-level races (lost updates, row locks, SQL deadlocks) belong to Locks & Concurrency Control, Deadlocks: Detection & Avoidance and Optimistic vs Pessimistic Locking; locks across machines are in Distributed Locking. Language-neutral design of concurrent components is in Concurrency Design.
Page map
| If you are looking for | Go to |
|---|---|
| The whole topic in a few tables | Everything in one minute |
| Why Go lets you write races at all | Why it exists |
| Go 1.1 race detector to Go 1.27 leak profile | Where it comes from |
| What exactly a data race is | Data race |
| Torn reads, corrupted interfaces and slices | Undefined behaviour and torn reads |
| Timing bugs with no data race | Race condition vs data race |
-race, ThreadSanitizer, cost, CI | The race detector |
Reading WARNING: DATA RACE | Reading a race report |
| Mutex, channel ownership, atomics, immutability, confinement, copying | Six ways to fix a race |
fatal error: concurrent map writes | Concurrent map writes |
| Closures in loops before and after Go 1.22 | Loop variable capture |
Lazy init, double-checked locking, sync.Once | Lazy initialization |
Check-then-act, TOCTOU, time.Now checks | Check-then-act and TOCTOU |
append from goroutines | Append races |
| Double close, send on closed, closing a conn in use | Closing shared resources |
all goroutines are asleep - deadlock! | Channel deadlocks |
| A→B vs B→A | Lock ordering |
Locking a sync.Mutex twice | Recursive locking |
Add/Done/Wait mistakes | WaitGroup misuse |
select that can never proceed | Blocking select |
| HTTP client hangs | Body not closed |
| Goroutines blocked forever without a crash | Goroutine leaks |
| Busy but no progress; one caller never served | Livelock and starvation |
Pike's talk, GOMAXPROCS=1 | Concurrency vs parallelism |
| Happens-before, DRF-SC, what atomics promise | The memory model |
| Bad code and the fix | Go |
| Exact messages, detector and runtime internals | Mechanics |
| Tested solutions | Solving the classic problems |
Stress tests, -count, fuzzing, testing/synctest | Testing concurrent code |
| Which tool for which symptom | Choosing |
| PHP-FPM's shared-nothing model compared | For PHP/Laravel developers |
| The same bugs across processes and services | In architecture |
| Run every failure yourself | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The bug families. Every row is unpacked in the concept catalogue.
| Bug | In plain words | Tiny example | Who finds it |
|---|---|---|---|
| Data race | Two goroutines touch the same variable, one writes, nothing orders them | go func() { n++ }() twice | go test -race (only on executed paths) |
| Race condition | The result depends on who runs first, even if every access is locked | if Available(s) { Book(s) } | Tests that force the interleaving; review |
| Deadlock (total) | Every goroutine is blocked | ch <- 1 with no receiver in main | Runtime: fatal error: all goroutines are asleep - deadlock! |
| Deadlock (partial) | Some goroutines wait for each other forever; the rest keep running | Transfer A→B and B→A | Nobody automatically; goroutine dump, go-deadlock |
| Goroutine leak | A goroutine blocks forever on something nobody will ever signal | Early return leaves senders on an unbuffered channel | goroutineleak profile (Go 1.27), dumps, NumGoroutine metric |
| Pool exhaustion | Looks like a deadlock; resources are checked out and never returned | resp.Body not closed | Dump shows goroutines waiting in net/http dials |
| Livelock | Everyone is busy reacting to everyone else; nothing completes | Two retriers that back off and retry in lockstep | CPU profile + no progress metric |
| Starvation | Work flows, but one kind of request never gets the resource | A writer behind a stream of readers | Latency percentiles, mutex/block profiles |
The toolbox.
| Tool | What it tells you | Cost | Since |
|---|---|---|---|
go test -race, go build -race | Data races that actually happened in this run, with both stacks | 5–10× memory, 2–20× time | Go 1.1 |
GORACE="halt_on_error=1 ..." | Detector options: stop at first race, log path, exit code | — | Go 1.1 |
go vet (copylocks, loopclosure, waitgroup/waitgroupgo) | Statically suspicious patterns | Compile-time | waitgroup Go 1.25, renamed Go 1.27 |
fatal error: concurrent map writes | Best-effort runtime check on maps | Always on, nearly free | Go 1.6 |
kill -QUIT <pid> / Ctrl-\ | Every goroutine's stack and wait reason, then exit 2 | Kills the process | Go 1.0 |
/debug/pprof/goroutine?debug=2 | Same dump, process keeps running | Stops the world briefly | net/http/pprof |
goroutineleak profile | Goroutines blocked on primitives no runnable goroutine can reach | GC-based | Experiment 1.26, GA 1.27 |
runtime.Stack(buf, true) | Dump from inside the program (watchdog) | Stops the world | Go 1.0 |
testing/synctest | Deterministic tests with fake time and "everyone is blocked" detection | Test-only | Experiment 1.24, GA 1.25 |
github.com/sasha-s/go-deadlock | Lock-order violations and long waits on mutexes | Wraps every lock | Third-party |
The fixes.
| Fix | When | Example |
|---|---|---|
| Mutex | Default for shared state with invariants across fields | mu.Lock(); m[k]++; mu.Unlock() |
| Channel ownership | One goroutine owns the state; others send requests | add <- 1, owner does n += d |
| Atomic | One word, no invariant with other fields | var hits atomic.Int64; hits.Add(1) |
| Immutability | Readers dominate; writers replace the whole value | atomic.Pointer[Config].Store(&newCfg) |
| Confinement | Each goroutine works on its own slot, merge after Wait | results[i] = f(i) |
| Copying | Hand a goroutine its own copy instead of a shared reference | go process(slices.Clone(batch)) |
Why it exists
Go made concurrency cheap to start: a go statement costs a few kilobytes of stack and no ceremony. It did not make concurrency safe to share. Goroutines live in one address space and can all reach the same variables, maps and slices; the language lets you pass a pointer anywhere and does not check who else holds it. That was a deliberate choice. The FAQ explains why maps are not synchronised: "requiring that all map operations grab a mutex would slow down most programs and add safety to few." The memory model then states the price: a program with a data race is incorrect, and for values larger than a machine word "such races can in turn lead to arbitrary memory corruption."
Instead of a type system that forbids sharing (Rust's approach), Go offers three things: a style ("share memory by communicating"), a precise memory model that says which operations order which, and tools that catch violations at run time (the race detector) or at least report them loudly (map checks, deadlock detection). This page is about using all three.
| Shared memory with locks | Message passing (channels) |
|---|---|
| State lives in one place; goroutines take turns | State lives in one goroutine; others ask it |
| Fast for small critical sections (≈ 110 ns/op contended here) | One send/receive per operation (≈ 420 ns/op here) |
| Bugs: forgotten lock, wrong lock, lock order | Bugs: nobody receives, nobody closes, leaked goroutines |
| Invariants across fields are easy (one lock) | Invariants are easy (one owner) but requests become messages |
sync.Mutex, sync/atomic | chan, select, owner goroutine |
| Effective Go: "Reference counts may be best done by putting a mutex around an integer variable" | Effective Go: "Only one goroutine has access to the value at any given time. Data races cannot occur, by design." |
The analogy we reuse on this page: one shared whiteboard in an office. Several people (goroutines) update numbers on one whiteboard. If two people read "41", each walks to the board and writes "42", one update vanishes: a data race. A marker that only one person may hold (a mutex) fixes it, as long as everyone uses the same marker. Instead, the office can appoint one secretary who alone writes on the board while others pass notes (channel ownership). A race condition is two people who each ask the secretary "is seat 12A free?", get "yes", and then each ask "book 12A": every single message was handled correctly, the sequence was not. A deadlock is two people who each hold one of the two cabinet keys the other needs and wait politely forever. Livelock is both stepping aside in the corridor in the same direction again and again. Concurrency is how the office organises the work; parallelism is how many people are at the board at the same instant. Hiring one person (GOMAXPROCS=1) does not make the notes consistent if that one person can be interrupted between reading and writing.
Three common misunderstandings, up front
- "Small races are harmless; at worst a counter is a bit off." For a single aligned word the memory model limits what you can see, but the compiler may still hoist or remove your reads (a
for !done {}loop "is not guaranteed to finish"), and for strings, slices, interfaces and maps the result can be memory corruption. The lab shows a racing reader observing a string whose pointer and length came from different writes. - "
-racepassed, so the code is race-free." The detector "only finds races that happen at runtime, so it can't find races in code paths that are not executed." It is also blind to race conditions: the booking bug on this page passes-racewhile selling one seat twice. - "The runtime detects deadlocks." Only total ones. If one goroutine anywhere is runnable, sleeping on a timer, or waiting on the network poller (an HTTP server always is), two goroutines can wait for each other forever and nothing is printed. The lab proves it with a pending timer.
Where it comes from
CSP and the Go proverb. Go's channels come from Hoare's Communicating Sequential Processes (1978); Effective Go calls Go's approach "a type-safe generalization of Unix pipes" and condenses it into "Do not communicate by sharing memory; instead, share memory by communicating." Go 1.0 (2012) shipped goroutines, channels, sync, sync/atomic and a first memory model document, plus the runtime's total-deadlock check.
Concurrency is not parallelism (2012–2013). Rob Pike gave the talk Concurrency is not Parallelism at Heroku's Waza conference in January 2012 ("Concurrency is about structure, parallelism is about execution"); Andrew Gerrand's blog post of 16 January 2013 summarised it: "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once."
The race detector (Go 1.1, 2013). Go 1.1 added -race. Dmitry Vyukov and Andrew Gerrand's post Introducing the Go Race Detector (26 June 2013) says it is "based on the C/C++ ThreadSanitizer runtime library", was integrated in September 2012 and had "detected 42 races in the standard library" by then; its conclusion: "It will not issue false positives, so take its warnings seriously."
Maps (Go 1.6, 2016). "The runtime has added lightweight, best-effort detection of concurrent misuse of maps" — the origin of fatal error: concurrent map writes.
The memory model revision (Go 1.19, 2022). Russ Cox's revision (document dated June 6, 2022) formalised happens-before in the style of Boehm and Adve, stated DRF-SC explicitly, defined sync/atomic as sequentially consistent ("the same semantics as C++'s sequentially consistent atomics and Java's volatile variables"), and Go 1.19 added typed atomics such as atomic.Int64 and atomic.Pointer[T].
Recent releases. Go 1.21 added sync.OnceFunc, OnceValue, OnceValues. Go 1.22 made each loop iteration create new variables ("to avoid accidental sharing bugs"; blog Fixing For Loops in Go 1.22, David Chase and Russ Cox, 19 September 2023). Go 1.24 introduced testing/synctest as an experiment behind GOEXPERIMENT=synctest (blog by Damien Neil, 19 February 2025). Go 1.25 made testing/synctest generally available with synctest.Test, added sync.WaitGroup.Go, a vet analyzer waitgroup that "reports misplaced calls to sync.WaitGroup.Add", and container-aware GOMAXPROCS defaults on Linux. Go 1.26 shipped an experimental goroutineleak profile; Go 1.27 made it generally available (also at /debug/pprof/goroutineleak), added synctest.Sleep, and renamed the vet analyzer to waitgroupgo.
This page was checked against the memory model (Version of June 6, 2022), the race detector article and blog post, Effective Go, the FAQ, the release notes 1.1, 1.6, 1.19, 1.21, 1.22 and 1.24–1.27, and the standard library source on go.dev/src (sync, sync/atomic, runtime, runtime/pprof, net/http, testing/synctest). The snippets declare go 1.24 and were built, vetted and tested with Go 1.27.4 on darwin/arm64 (12 CPUs); the testing/synctest test file opts into Go 1.25 with a build constraint, and the goroutineleak output in the lab is from Go 1.27.
The concept catalogue
Each block: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, behaviour per situation, and the fix. Full, tested code is in Solving the classic problems.
Data race Must-know
In plain words: two goroutines use the same variable at the same time, at least one of them writes, and nothing in the program decides which goes first.
Common misunderstanding: "It is only a race if the timing actually overlaps on two CPUs." The definition is about ordering, not wall-clock overlap. Two accesses with no happens-before chain between them are a race even if, in this run, one happened a second after the other on the same core.
Definition: the race detector article: "A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write." The memory model is precise: "A data race is defined as a write to a memory location happening concurrently with another read or write to that same location, unless all the accesses involved are atomic data accesses as provided by the sync/atomic package", where concurrently means unordered by happens-before. Each struct field and each array or slice element is its own memory location; two goroutines writing s[0] and s[1] do not race.
goroutine 1 goroutine 2 shared n = 41
1 load n -> 41
2 load n -> 41
3 add 1 -> 42
4 add 1 -> 42
5 store n = 42
6 store n = 42 n = 42, one increment lostReal scenario: a request counter that reports 921 of 1000 requests (the lab's real output); a "last seen" timestamp in a watchdog read while a heartbeat writes it; a feature flag bool flipped by an admin goroutine while handlers read it; an err variable shared by two goroutines because one used = instead of := (the race detector article's Accidentally shared variable).
| Access pattern | Race? | Why |
|---|---|---|
| Two goroutines read the same variable | No | No write |
| One writes, one reads, no synchronisation | Yes | Unordered write and read |
Both use atomic.Int64 methods | No | All accesses are atomic |
One uses atomic.AddInt64(&n,1), the other reads n plainly | Yes | "unless all the accesses involved are atomic" |
Writes to s[0] and s[1] of one slice | No | Different memory locations |
Writes to m["a"] and m["b"] of one map | Yes | A map is one data structure; inserts touch shared buckets and counters |
Write before go f(), read inside f | No | The go statement is synchronized before f starts |
Write inside a goroutine, read after wg.Wait() | No | Done synchronizes before the Wait it unblocks |
Fix / how to use it: pick one of the six fixes; the default is a sync.Mutex next to the data it guards, with a comment saying so. Then prove it with go test -race.
Undefined behaviour and torn reads Important
In plain words: some Go values are several machine words (a string is pointer + length, a slice is pointer + length + capacity, an interface is type + data). A racing reader can get half of one write and half of another.
Common misunderstanding: "Go is memory-safe, so a race cannot corrupt memory." Go is memory-safe for race-free programs. The memory model: when values "depend on the consistency of internal (pointer, length) or (pointer, type) pairs, as can be the case for interface values, maps, slices, and strings in most Go implementations, such races can in turn lead to arbitrary memory corruption."
Definition: for a single-word location, a racing read "must observe a value actually written to that location ... and not yet overwritten" (so Go is "more like Java or JavaScript ... and less like C and C++, where the meaning of any program with a race is entirely undefined"). For larger values, implementations "may instead treat larger operations as a set of individual machine-word-sized operations in an unspecified order." A torn read is a read that observes such a mixture. Separately, without synchronisation the compiler may keep a value in a register: in the memory model's busy-wait example "there is no guarantee that the write to done will ever be observed by main."
writer reader s (ptr, len)
1 s = "short" -> (p1, 5)
2 s = "a much longer..." -> writes ptr p2 first
3 reads ptr -> p2
4 reads len -> 5 ("a muc"): never written
5 -> then len 26
6 s = "short" -> writes ptr p1
7 reads ptr p1, len 26 reads 21 bytes past "short"Real scenario: a config pointer swapped by a reload goroutine while handlers read cfg.Name and print garbage; an error interface written by one goroutine and type-asserted by another, crashing with a nil-pointer panic in code that "cannot" see nil; a cached []byte replaced while another goroutine slices it, producing slice bounds out of range; a for !stop {} loop that never ends in an optimised build.
| Racing value | What can go wrong | Lab or source |
|---|---|---|
int64 on 64-bit, bool, pointer | Stale or never-visible value; loop hoisted | Memory model, Incorrect synchronization |
string | Pointer from one write, length from another | Lab: 164,241 torn reads in 1,000,000 writes |
[]T | Length larger than the backing array: out-of-bounds or wild memory | Memory model, multi-word data |
interface / error | Type word and data word mismatch: wrong method called | Memory model, (pointer, type) pairs |
map | Runtime crash (concurrent map writes) or corrupted buckets | Go 1.6 map check |
| struct | Fields from different writes | "may be implemented as a read of each individual sub-value" |
Fix / how to use it: never "just read" a shared multi-word value. Publish whole values through atomic.Pointer[T] or under a lock, and treat a race report on a string, slice or interface as a crash waiting to happen.
Race condition vs data race Must-know
In plain words: a race condition is a bug where the result depends on the order in which things happen. A data race is one specific way to get one. You can have a race condition with zero data races.
Common misunderstanding: "I put a mutex around every access, so there are no races." Every access can be safe while the sequence is not: "check availability" and "book" are each locked, but another goroutine can book in the gap between them.
Definition: a race condition is a correctness property: some interleaving of otherwise valid steps violates an invariant. A data race is a memory-model property: two conflicting accesses are unordered. The race detector reports only the second. Race conditions also live outside memory: between two HTTP requests, two processes, two database transactions, a file check and a file open.
buyer A buyer B seat 12A
1 Available("12A") -> true (locked)
2 Available("12A") -> true (locked)
3 assign("12A","ana") (locked) owner = ana
4 assign("12A","bob") (locked) owner = bob
5 both told "booked"; go test -race: PASS, no reportReal scenario: overselling concert seats (the booking snippet reproduces it deterministically); two workers both deciding a job is unclaimed; a rate limiter that reads the counter, decides "under limit", then increments; double charging when a user double-clicks "Pay"; a cache stampede where every goroutine sees a miss and all rebuild.
| Data race | Race condition | |
|---|---|---|
| Level | Memory accesses | Business operations |
Detected by -race | Yes, when executed | No |
| Possible with every access locked | No | Yes |
| Possible across processes/DB | No (separate memory) | Yes, the common case |
| Fix | Synchronise the accesses | Make check and act one atomic step (one critical section, UPDATE ... WHERE, unique constraint, compare-and-swap) |
Fix / how to use it: find the invariant ("a seat has at most one owner"), then make the code that tests it and the code that relies on it run in one critical section, or push it into something atomic: sync.Map.LoadOrStore, atomic.CompareAndSwap, a database unique index, UPDATE ... WHERE status = 'free'.
The race detector Must-know
In plain words: -race builds a special binary that records every memory access and every synchronisation event, and shouts when two accesses are not ordered.
Common misunderstanding: two opposite ones. "It reports false alarms, so I can ignore it" (the Go team: "It will not issue false positives, so take its warnings seriously"). And "a clean run proves there are no races" (it "can detect race conditions only when they are actually triggered by running code").
Definition: with -race "the compiler instruments all memory accesses with code that records when and how the memory was accessed, while the runtime library watches for unsynchronized accesses to shared variables." The runtime is ThreadSanitizer (TSan): it keeps a logical clock per goroutine, advances it on synchronisation, and maps "every aligned 8-byte word of application memory" to a few shadow words (goroutine id, clock, read/write, size); on each access it compares the new access with the stored ones and reports a pair when neither happens before the other. It works on go test, go run, go build and go install, requires cgo, and supports linux/amd64, linux/arm64, darwin/amd64, darwin/arm64, windows/amd64 and other listed platforms (Go 1.26 added linux/riscv64). Building with -race also sets the build tag race. Cost: "memory usage may increase by 5-10x and execution time by 2-20x"; "8 bytes per defer and recover statement" are not reclaimed until the goroutine exits.
1 go test -race ./... compiler inserts race.read/race.write around loads/stores
2 goroutine A: write n shadow word: {goroutine A, clock 17, write}
3 goroutine B: read n B last synchronised with A at A's clock 12
4 TSan: 17 > 12 -> not happens-before -> report "WARNING: DATA RACE"
5 test ends "testing.go: race detected during execution of test" -> FAIL, exit 1
6 plain binary ends exit code 66 (GORACE exitcode)Real scenario: CI runs go test -race ./... on every pull request; a canary instance built with -race takes 1% of traffic (the 2013 post: "deploy a single race-enabled instance within a pool of running servers"); a load test against a -race binary finds a race in a code path no unit test reaches; a flaky test turns out to be a race that -race -count=50 reproduces.
| Situation | What -race does |
|---|---|
| Race on a path the run executes | Reports it, every time the unordered pair is observed (history permitting) |
| Race on a path never executed | Nothing |
| Race condition with locked accesses | Nothing (not a data race) |
| Deadlock | Nothing special (no race) |
Synchronisation through sync, channels, sync/atomic, testing/synctest.Wait | Understood: no report |
Synchronisation through unsafe tricks, external C code without annotations | May be missed or misreported |
Too old history (history_size too small) | Report may say "failed to restore the stack" |
Fix / how to use it: run go test -race ./... in CI on every change; run integration and load tests with -race; set GORACE=halt_on_error=1 when you want the first race to stop the process; never ship -race builds widely (CPU and memory), but one canary is cheap insurance.
Reading a race report Must-know
In plain words: a report has four parts: the access that tripped the alarm, the earlier conflicting access, and where each of the two goroutines was started.
Common misunderstanding: "The first stack is the bug." The two accesses are equally guilty; the fix is usually at the data (which variable, who owns it), not at either line. The "created at" stacks tell you which goroutines should not both have had access.
Definition: "The report contains stack traces for conflicting accesses, as well as stacks where the involved goroutines were created." Real output from this page's lab, built with -trimpath:
==================
WARNING: DATA RACE
Read at 0x00c000012148 by goroutine 12: <- 1. current access, kind, address, goroutine id
main.counter.func1()
academy/race-conditions-deadlocks/racedemo/main.go:44 +0x68
Previous write at 0x00c000012148 by goroutine 8: <- 2. earlier access with no happens-before edge
main.counter.func1()
academy/race-conditions-deadlocks/racedemo/main.go:44 +0x78
Goroutine 12 (running) created at: <- 3. who started goroutine 12
main.counter()
academy/race-conditions-deadlocks/racedemo/main.go:42 +0x6c
Goroutine 8 (finished) created at: <- 4. who started goroutine 8 (it may have exited)
main.counter()
academy/race-conditions-deadlocks/racedemo/main.go:42 +0x6c
==================
want 1000, got 871
Found 2 data race(s) <- summary; process exits with status 66Real scenario: both accesses on the same line (n++ from many goroutines: a missing lock); a read in a handler and a write in init-time setup (a config map mutated after start); a write inside runtime.growslice called from your append (a shared slice); a report whose second stack is in a library (you passed it a value and kept writing to it); the 2013 post's Timer.Reset example where the timer callback read t before main had assigned it.
| Report line | Meaning | Typical action |
|---|---|---|
Read at / Write at | Kind of the access that completed the pair | Locate the variable |
Previous write at / Previous read at | The conflicting access recorded earlier | Same variable, other code path |
by goroutine N | Goroutine ids, matching the "created at" sections | Map to your goroutines |
(running) / (finished) | State of that goroutine at report time | Finished goroutines still count |
created at: | Stack of the go statement | Decide who should own the data |
Found N data race(s) | Count at exit | Fix all, then rerun |
testing.go: race detected during execution of test | Test runner marks the test failed | — |
Fix / how to use it: name the variable, list every goroutine that touches it, choose an owner or a lock, and rerun with -race -count=20. If the report is in a dependency, check whether you shared a value you should have copied.
Six ways to fix a race Must-know
In plain words: either make the accesses take turns (mutex, atomic), or make sure only one goroutine can reach the data at a time (channel ownership, confinement, copying), or make the data impossible to change (immutability).
Common misunderstanding: "Channels are the Go way, mutexes are a smell." Effective Go itself says the slogan "can be taken too far. Reference counts may be best done by putting a mutex around an integer variable", and the FAQ: "Large concurrent programs are likely to borrow from both these toolkits." The sync package doc: "Higher-level synchronization is better done via channels and communication", which is about coordination, not about guarding a map.
Definition:
| Fix | Mechanism | Happens-before edge | Benchmark here (12 CPUs, contended) | Limits |
|---|---|---|---|---|
sync.Mutex | Critical section | Unlock n before Lock n+1 returns | ≈ 111 ns/op | Contention, lock order, must not copy |
sync/atomic | Single hardware read-modify-write | Store observed by Load | ≈ 57–63 ns/op | One word; no invariant across fields |
| Channel ownership | Owner goroutine serialises requests | Send before receive completes | ≈ 420 ns/op | Owner is a bottleneck; must stop it |
| Immutability | Build new value, publish pointer | atomic.Pointer Store/Load | Reads are one atomic load | Writers copy; old readers see old value |
| Confinement | Each goroutine owns its slot; merge after Wait | Done before Wait returns | No sharing at all | Needs a merge step |
| Copying | Pass a value or slices.Clone | go statement | Copy cost | Large values; deep copies |
1 shared map[string]int touched by handlers -> race
2 mutex: mu.Lock(); m[k]++; mu.Unlock() -> one at a time
3 owner: reqs <- k ; owner goroutine does m[k]++ -> only the owner touches m
4 confine: per-worker map, merge after wg.Wait() -> no shared map until the end
5 immut.: build new map, cfg.Store(&Config{m}) -> readers never see a half-built mapReal scenario: per-endpoint counters (atomic or mutex); a connection registry (mutex + map); a rate limiter's token state (mutex: several fields with an invariant); routing tables and feature flags reloaded every minute (immutability with atomic.Pointer); parallel image resizing where each worker writes out[i] (confinement); a batch handed to a background uploader while the caller reuses its buffer (copying).
Fix / how to use it: start with a mutex embedded next to the data; move to atomics only for a single hot word, to immutability for read-mostly configuration, to an owner goroutine when the state has a lifecycle (a connection, a session). The counter snippet implements five of them behind one interface with tests and benchmarks.
Concurrent map writes Must-know
In plain words: Go maps are not safe for concurrent writes. The runtime usually notices and kills the whole process with a message you cannot recover from.
Common misunderstanding: "I can recover from it like a panic." It is a fatal error, not a panic: deferred functions do not run and recover sees nothing. Second one: "reads are fine as long as writes are rare." Any write concurrent with any read is a race.
Definition: the FAQ: "Map access is unsafe only when updates are occurring. As long as all goroutines are only reading ... it is safe for them to access the map concurrently without synchronization." The runtime check (since Go 1.6, "lightweight, best-effort") sets a writing flag during each mutation; another access that sees it calls fatal with one of concurrent map writes, concurrent map read and map write, or concurrent map iteration and map write (texts from internal/runtime/maps in Go 1.27). Best-effort means it can miss races that -race would report.
1 goroutine 1: m[k] = v sets hashWriting flag, mutates bucket
2 goroutine 2: m[j] = w sees hashWriting -> fatal("concurrent map writes")
3 output: "fatal error: concurrent map writes" + stack of the goroutine that noticed
4 process exits with status 2; no defers, no recover, no graceful shutdownReal scenario: an in-memory session store keyed by token, written by login handlers; a "seen IDs" dedup map in a consumer that later got more workers; metrics labels cached in a map at first use; a test helper map shared across t.Parallel() subtests. All of these crash at the worst possible time, under load.
| Option | Use when | Note |
|---|---|---|
map + sync.Mutex | Default | Simple, invariants across map and other fields |
map + sync.RWMutex | Many readers, rare writers, critical sections not tiny | RLock has its own overhead; measure |
sync.Map | Keys written once and read many times, or disjoint key sets per goroutine | Its doc names exactly these two cases |
| Sharded maps (N maps, N locks) | Very hot map, measured contention | More code; see Write Buffering & Sharded Counters |
| Owner goroutine | Map with lifecycle (registry) | Requests through channels |
Copy-on-write + atomic.Pointer | Read-mostly lookups (routing table) | Writers copy the whole map |
Fix / how to use it: wrap the map in a type with an unexported mutex and methods; never return the inner map (return a copy, like Snapshot in the after snippet).
Loop variable capture before Go 1.22 Important
In plain words: before Go 1.22 a for loop had one variable for the whole loop; goroutines started inside the loop all saw that one variable, which the loop kept changing. Since Go 1.22 every iteration has its own.
Common misunderstanding: "This is fixed, I can forget it." The fix applies per module go version and per file: a module whose go.mod says go 1.21 (or a file with //go:build go1.21) still has the old semantics with a 1.27 compiler. The loopvar snippet proves it in one module.
Definition: Go 1.22 release notes: "Previously, the variables declared by a 'for' loop were created once and updated by each iteration. In Go 1.22, each iteration of the loop creates new variables, to avoid accidental sharing bugs." The loopvar blog: "It is also possible to use //go:build lines to control the decision on a per-file basis." Under old semantics, go func() { use(i) }() is both a logic bug and a data race (the loop writes i while goroutines read it); the race detector article shows the classic program that "typically prints 55555, not 01234."
go 1.21 semantics go 1.22+ semantics
1 i := 0 (one variable) iteration 0: i0 := 0
2 go read(&i) <- shares i go read(i0)
3 i++ (write) <- races the read iteration 1: i1 := 1 (copied, then incremented)
4 ... go read(i1)
5 all goroutines see the last i each goroutine sees its own valueReal scenario: a batch sender that sent the last order N times; tests in a for _, tc := range cases loop with t.Parallel() that all tested the last case (silently passing); defer closures in a loop all closing the last file; old vendored code compiled in a module that is still on go 1.20.
| Code | go 1.21 module | go 1.22+ module |
|---|---|---|
for i := 0; i < n; i++ { go f(i) } | Correct (argument copied) | Correct |
for i := 0; i < n; i++ { go func() { f(i) }() } | Bug + data race | Correct |
for _, v := range xs { fs = append(fs, func() { use(v) }) } | All closures see last v | Each sees its own |
i := i shadow copy inside loop | Required idiom | Redundant (harmless) |
vet loopclosure | Reports go/defer at end of body | Silent (no longer a risk) |
Fix / how to use it: keep modules on go 1.22 or later; delete x := x copies only after the module is upgraded; when reading old code, check the go line before judging a loop.
Lazy initialization and sync.Once Important
In plain words: "build it the first time someone asks" must happen exactly once and everyone must see the finished result. A plain if x == nil { x = build() } does neither under concurrency.
Common misunderstanding: double-checked locking: "check without the lock, and only lock if it is nil." The memory model uses exactly this as a counter-example: "there is no guarantee that, in doprint, observing the write to done implies observing the write to a."
Definition: sync.Once: "only one will run f(), and the other calls block until f() has returned"; "The completion of a single call of f() from once.Do(f) is synchronized before the return of any call of once.Do(f)." Go 1.21's sync.OnceValue(f) returns a function that calls f once and returns its value (and OnceValues for value + error); OnceFunc for side effects. If f panics, Do considers it done; OnceValue/OnceFunc re-panic with the same value on every call.
goroutine 1 goroutine 2 stop map
1 if t.stop == nil -> true
2 if t.stop == nil -> true
3 t.stop = build() (write)
4 t.stop = build() (write) two maps, racing writes
5 reads t.stop reads half-published map? race on the map header
---- with stopPaths := sync.OnceValue(build) ----
6 stopPaths() runs build stopPaths() blocks until done one map, fully visibleReal scenario: a lazily compiled regexp or template; a database client created on first request; a JWKS key set fetched on first validation; a singleton logger. In tests, the race detector reports these instantly when two parallel subtests trigger the first use.
| Approach | Correct? | Note |
|---|---|---|
if x == nil { x = build() } | No | Data race, possibly two builds |
| Double-checked locking with a plain flag | No | Memory model counter-example |
sync.Mutex around check and build | Yes | Every call locks |
sync.Once + package variable | Yes | Classic |
sync.OnceValue(build) / OnceValues | Yes | Go 1.21+, returns the value, re-panics |
Package-level var x = build() | Yes | Runs in init, which is single-goroutine and "synchronized before the start of the function main.main" |
Fix / how to use it: prefer eager package-level initialisation when it is cheap and cannot fail; otherwise sync.OnceValue/OnceValues. Do not retry inside Once: if building can fail transiently, use a mutex-guarded "build if nil" instead.
Check-then-act and TOCTOU Must-know
In plain words: you look (is it free? has it expired? does the file exist?) and then you act on the answer, but the world can change between the look and the act.
Common misunderstanding: "I checked time.Now().Before(expires) so the hold is valid." It was valid at the check. A slow payment call after the check, or a second request doing the same check, makes the decision stale. TOCTOU (time of check to time of use) is the name for exactly this.
Definition: check-then-act is a compound operation whose correctness requires the condition to still hold when the action executes; without a single atomic step it is a race condition (with or without a data race). TOCTOU is the special case where the check and the use are separate system or time-based operations: os.Stat then os.Open, an expiry check then a confirmation, a permission check then a write.
request 1 (double click) request 2 hold h1 (expires 12:01)
1 lock; valid = now < exp && !confirmed; unlock -> true
2 lock; valid = ... ; unlock -> true
3 charge card (300 ms) charge card (300 ms) two charges
4 lock; confirmed = true; unlock lock; confirmed = true; unlock seat once, money twice
---- Confirm: claim inside the same critical section ----
5 lock; check; confirmed = true; unlock -> charge
6 lock; sees confirmed -> ErrTakenReal scenario: seat holds and payment confirmation; coupon "used once" checks; if _, err := os.Stat(p); errors.Is(err, fs.ErrNotExist) { os.Create(p) } racing another process (use os.OpenFile with O_CREATE|O_EXCL); "is this user allowed?" checked before a long upload and not at commit; cache "miss then fill" storms.
| Check-then-act | Atomic alternative |
|---|---|
if !m[k] { m[k] = true } from goroutines | Same code inside one Lock/Unlock; or sync.Map.LoadOrStore |
if n.Load() < limit { n.Add(1) } | CompareAndSwap loop |
os.Stat then os.Create | os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) |
SELECT free seat, then UPDATE | UPDATE seats SET owner=$1 WHERE id=$2 AND owner IS NULL + check rows affected, or a unique constraint |
| Expiry check, then slow work, then commit | Claim (state transition) under the lock with one now, re-validate at commit |
Fix / how to use it: make the state transition the atomic step ("free → held → confirming → confirmed"), take the clock reading once and pass it in (now func() time.Time in the booking snippet), and let the second caller observe the claim. Across processes, push the transition into the database; see Optimistic vs Pessimistic Locking.
Append races and slice headers Important
In plain words: append reads the slice header (pointer, length, capacity), maybe allocates a bigger array, and writes a new header back. Two goroutines doing that on one variable lose elements or corrupt memory.
Common misunderstanding: "append is a built-in, so it is atomic." No built-in is atomic. And "if I pre-allocate capacity, appends are safe": both goroutines can still read the same length and write the same index.
Definition: ids = append(ids, x) is a read of ids, possibly a call to runtime.growslice (copying the old array), a write to the element at len, and a write of the new header to ids. Concurrent calls race on the header and on the element. The lab's real output: want 100, got 94, and the race report's second stack is inside runtime.growslice().
goroutine 1 goroutine 2 ids (ptr,len,cap)
1 read ids -> (p,3,4)
2 read ids -> (p,3,4)
3 p[3] = 10
4 p[3] = 20 element overwritten
5 ids = (p,4,4)
6 ids = (p,4,4) length 4, one value lostReal scenario: collecting errors from parallel validators into one []error; gathering search results from shards; building a response list in errgroup goroutines; appending to a shared buffer in a logging hook.
| Pattern | Safe? | Note |
|---|---|---|
results = append(results, r) from many goroutines | No | Header race |
results[i] = r with results := make([]T, n) | Yes | Distinct elements (confinement) |
| Each goroutine sends on a channel, one collector appends | Yes | Channel ownership |
mu.Lock(); results = append(results, r); mu.Unlock() | Yes | Order is arbitrary |
Two goroutines append to sub-slices sharing a backing array | No | They can overwrite each other's elements; see Arrays, Slices & Maps |
Fix / how to use it: pre-size and write by index when you know the count; otherwise send to a channel or lock; use errors.Join on a collected slice after Wait.
Closing shared resources Important
In plain words: closing something (a channel, a connection, a file) while other goroutines still use it, or closing it twice, is a concurrency bug with its own crash messages.
Common misunderstanding: "Whoever finishes last closes the channel." Without coordination nobody knows who is last; two "last" goroutines close twice. The rule is that the sender side owner closes, once, after all sends are done.
Definition: close on a closed channel panics with close of closed channel; on a nil channel, close of nil channel; a send on a closed channel panics with send on closed channel. The race detector article shows that "unsynchronized send and close operations on the same channel can also be a race condition", reported as a data race. Closing an *os.File or net.Conn while another goroutine reads makes that read return an error such as use of closed network connection (net.ErrClosed), which is often the intended way to unblock a reader, if it is coordinated.
producer A producer B consumer
1 ch <- x
2 done; close(ch)
3 ch <- y -> panic: send on closed channel
---- fixed: one owner ----
4 wg.Go(produceA); wg.Go(produceB)
5 go func() { wg.Wait(); close(ch) }() -> close exactly once, after all sends
6 for v := range ch { ... } ends cleanlyReal scenario: fan-in pipelines where each producer closes the output; Shutdown paths that close a quit channel from two signal handlers; a WebSocket hub that closes a client's send channel while a broadcaster sends to it; a database *sql.DB closed by one test while another parallel test uses it.
| Resource | Safe close pattern |
|---|---|
| Channel with one sender | Sender closes when done (defer close(out)) |
| Channel with many senders | WaitGroup + one closer goroutine; or never close, signal via context |
| "Stop" broadcast | close(done) guarded by sync.Once, or context.CancelFunc (idempotent) |
net.Conn read loop | Close the conn from the owner to unblock Read; treat net.ErrClosed as normal |
*sql.DB, *http.Client | Create once, close at program end; never per request |
Fix / how to use it: decide the owner of every closable thing; make "stop" idempotent (context.CancelFunc and sync.Once both are); details in Goroutines & Channels and OS Processes, Signals & Graceful Shutdown.
Channel deadlocks and "all goroutines are asleep" Must-know
In plain words: a goroutine waits on a channel operation that no other goroutine will ever complete. If that leaves every goroutine blocked, the runtime ends the program with a famous message.
Common misunderstanding: "If my program deadlocks, Go will tell me." Only when no goroutine can ever run again and no timer is pending and nothing waits on the network poller. In a server, the HTTP listener is always waiting on the poller, so a deadlocked subset of goroutines is silent forever.
Definition: the runtime's scheduler check (checkdead in runtime/proc.go) calls fatal("all goroutines are asleep - deadlock!") when no OS thread is running Go code and none can be woken by a timer or I/O. It prints each goroutine's stack with its wait reason in brackets ([chan send], [chan receive], [select], [select (no cases)], [sync.Mutex.Lock], [sync.WaitGroup.Wait]) and exits with status 2. Blocking forever on a nil channel is legal Go and reported the same way.
1 main: ch := make(chan int) unbuffered: a send needs a simultaneous receiver
2 main: ch <- 1 blocks; no other goroutine exists
3 runtime: no M running, no timers checkdead
4 "fatal error: all goroutines are asleep - deadlock!"
5 "goroutine 1 [chan send]:" + stack exit status 2Real scenario: a pipeline stage that returns early on error while upstream still sends; for v := range ch where nobody closes ch; a result channel with capacity 0 read only after wg.Wait() (the senders block, Wait never returns); a test that sends on a channel the code under test stopped reading; reading from a nil channel left by a struct that was never initialised.
| Case | Runtime reports it? |
|---|---|
main blocked, no other goroutines | Yes, fatal error: all goroutines are asleep - deadlock! |
All goroutines blocked on channels/locks/WaitGroup | Yes |
| Some goroutines blocked, one runnable or sleeping | No |
A timer or ticker pending (time.After, time.NewTicker) | No (lab step 5) |
| HTTP server listening | No (network poller) |
| Goroutine blocked in a syscall or cgo | No |
main returns while others are blocked | No: the program just exits; they never finish |
Fix / how to use it: give every blocking operation an exit: a case <-ctx.Done() in every select, a single owner that closes each channel, buffered result channels sized to the number of senders when results may be abandoned, and errgroup.WithContext to cancel siblings on the first error (Worker Pools, Pipelines).
Lock-ordering deadlocks Must-know
In plain words: goroutine 1 holds lock A and waits for lock B; goroutine 2 holds B and waits for A. Neither will ever let go.
Common misunderstanding: "This is a database problem." Databases detect cycles and kill one transaction (PostgreSQL 40P01, InnoDB error 1213); Go's sync.Mutex has no detector, no timeout and no victim. The goroutines wait forever and the only symptom is requests that never finish.
Definition: a deadlock requires four conditions (Coffman et al., 1971): mutual exclusion, hold and wait, no preemption, circular wait. sync.Mutex gives you the first three by design, so the only one you control is circular wait. A global lock order (always acquire in ascending ID, or by a fixed hierarchy such as "registry before session before connection") makes a cycle impossible.
goroutine 1: Transfer(a, b) goroutine 2: Transfer(b, a)
1 a.mu.Lock() ok
2 b.mu.Lock() ok
3 b.mu.Lock() waits for 2
4 a.mu.Lock() waits for 1
5 both [sync.Mutex.Lock] forever; the HTTP server keeps accepting; nothing is logged
---- Transfer orders by ID ----
6 lock(min(a,b)) then lock(max(a,b)) goroutine 2 waits on lock 1 holding nothing -> no cycleReal scenario: wallet-to-wallet transfers; moving an item between two in-memory carts; a cache that locks itself and then calls a callback that locks the caller's object; an observer pattern where the subject holds its lock while notifying listeners that call back into the subject; two subsystems each holding their own lock while calling the other.
| Technique | How | Limit |
|---|---|---|
| Global order | Sort by ID or a fixed hierarchy before locking | Every code path must follow it |
| One coarser lock | One mutex for both objects | Less parallelism |
| Never call out while holding a lock | Copy what you need, unlock, then call callbacks | Must re-check state after re-locking |
TryLock and back off | Release and retry on failure | The sync doc: use of TryLock "is often a sign of a deeper problem"; risks livelock |
| Detection in tests | go-deadlock records lock order and reports violations | Mutexes only; extra cost |
| Timeouts | Channel-based or context-aware locks (semaphore.Weighted.Acquire(ctx)) | A timeout reports, it does not undo |
Fix / how to use it: the lockorder snippet orders by account ID and has a test that forces the deadly interleaving with a barrier and catches the hang with a timeout plus goroutine dump. Database-side equivalents are in Deadlocks: Detection & Avoidance.
Recursive locking Important
In plain words: a goroutine that already holds a sync.Mutex and calls Lock again waits for itself, forever.
Common misunderstanding: "Mutexes are owned by a goroutine, like Java's synchronized." They are not: "A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it." So Go cannot know that the second Lock comes from the holder; there are no reentrant mutexes in the standard library.
Definition: Lock: "If the lock is already in use, the calling goroutine blocks until the mutex is available." With RWMutex the trap is subtler: a goroutine holding RLock that calls RLock again can deadlock if a writer is waiting in between, because "a blocked Lock call excludes new readers from acquiring the lock" (sync.RWMutex doc).
1 (s *Store) Put(k, v): s.mu.Lock(); defer s.mu.Unlock()
2 Put calls s.Len() to check capacity
3 (s *Store) Len(): s.mu.Lock() <- same goroutine, lock held -> blocks forever
4 if nothing else runs: "fatal error: all goroutines are asleep - deadlock!" / "goroutine 1 [sync.Mutex.Lock]:"
5 in a server: one request hangs; then every request that needs s.mu hangs behind itReal scenario: an exported method calling another exported method on the same type; a String() method that locks, called from a log line inside a locked section; a callback registered by the user that calls back into the locked object; RWMutex read paths that call helper read paths while a config reload waits for the write lock.
| Pattern | Fix |
|---|---|
| Exported method calls exported method | Split into exported (locks) and unexported lenLocked() (assumes held) |
String()/Error() locks | Format a copy taken before locking, or do not lock in String |
| Callback under lock | Collect callbacks, unlock, then call |
Nested RLock | Take RLock once at the top; helpers assume it is held |
Fix / how to use it: naming convention xxxLocked for helpers that require the lock; one Lock per public method, at the top. go-deadlock reports "duplicate take a lock in a goroutine" in tests.
WaitGroup misuse Important
In plain words: a WaitGroup is a counter. Count wrong and Wait either returns too early (some work still running) or never returns.
Common misunderstanding: "wg.Add(1) inside the goroutine is fine." Then Wait may run before any Add, see zero and return immediately. The sync doc: "calls with a positive delta that occur when the counter is zero must happen before a Wait ... Typically this means the calls to Add should execute before the statement creating the goroutine."
Definition: Add panics with sync: negative WaitGroup counter when the counter goes below zero; reusing it too early panics with sync: WaitGroup is reused before previous Wait has returned; the implementation's sanity check reports sync: WaitGroup misuse: Add called concurrently with Wait. A missing Done (early return, panic without defer) leaves Wait blocked: [sync.WaitGroup.Wait] in dumps. Go 1.25 added wg.Go(f) ("Callers should prefer WaitGroup.Go") and the vet analyzer waitgroup (renamed waitgroupgo in Go 1.27) for misplaced Add. A WaitGroup "must not be copied after first use"; passing it by value is caught by vet's copylocks.
main worker
1 go worker() (not scheduled yet)
2 wg.Wait() -> counter 0 -> returns immediately
3 print results (empty) wg.Add(1) ... works too late
---- other direction ----
4 wg.Add(2); go a(); go b() a: if err != nil { return } <- no Done
5 wg.Wait() -> counter 1 forever [sync.WaitGroup.Wait]Real scenario: a batch import that reports success while half the rows are still being written; a shutdown that hangs because one worker returned early without Done; a worker pool that copies the WaitGroup into each worker by value (each Done decrements a copy); Add inside a loop body that sometimes continues before starting the goroutine.
| Mistake | Symptom | Fix |
|---|---|---|
Add inside the goroutine | Wait returns early | Add before go, or wg.Go |
Done not deferred | Hang on early return/panic | defer wg.Done() first line, or wg.Go |
WaitGroup passed by value | Hang (copy decremented) | Pass *sync.WaitGroup; vet copylocks |
More Done than Add | panic: sync: negative WaitGroup counter | One Add(1) per goroutine |
Reuse while Wait runs | sync: WaitGroup is reused before previous Wait has returned | New WaitGroup per batch |
| Need errors or cancellation | WaitGroup has neither | errgroup.Group |
Fix / how to use it: on Go 1.25+ write wg.Go(func() { ... }) and the counting mistakes disappear (the function "must not panic"); otherwise wg.Add(1) immediately before go and defer wg.Done() as the first statement.
Blocking select and select without default Good to know
In plain words: a select blocks until one of its cases can proceed. If none ever can, the goroutine is stuck, exactly like a single channel operation.
Common misunderstanding: "Adding a default fixes it." default turns the wait into a poll; inside a loop it becomes a CPU-burning spin. The fix is a case that will eventually fire: ctx.Done(), a timer, or a closed done channel.
Definition: select {} blocks forever ([select (no cases)]). A select whose cases are all nil channels also blocks forever. Without default, the goroutine parks with wait reason [select]. The patterns themselves are in select.
1 for { select { case j := <-jobs: run(j); case r := <-results: save(r) } }
2 jobs closed? receive returns zero value forever -> busy loop with j == zero (forgot ok check)
3 jobs set to nil to disable, results nil too -> select blocks forever: [select]
4 fixed: add case <-ctx.Done(): return and check j, ok := <-jobsReal scenario: a worker that never exits on shutdown, holding the process open until Kubernetes sends SIGKILL; a "heartbeat or data" loop that hangs when the upstream connection dies silently; a test that waits on a result channel without a timeout and runs until the global go test -timeout (10 minutes by default) panics with a goroutine dump.
select shape | Behaviour |
|---|---|
| Cases only | Blocks until one is ready |
Cases + default | Never blocks; spins if in a loop |
Cases + <-ctx.Done() | Blocks until ready or cancelled (preferred) |
Cases + <-time.After(d) | Timeout per iteration (allocates a timer each time) |
select {} | Blocks forever |
Fix / how to use it: every long-lived select gets a cancellation case; every test wait gets a timeout.
Body not closed: connection pool exhaustion Important
In plain words: an HTTP response body you never close keeps its TCP connection busy. When the pool runs out, the next request waits, and your service "hangs" without any deadlock in your code.
Common misunderstanding: "I only needed the status code, so I don't need the body." The net/http doc: "If the Body is not both read to EOF and closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection." Second one: "the default client has a timeout." http.Client "Timeout of zero means no timeout", and http.DefaultClient has zero.
Definition: Transport.MaxConnsPerHost "optionally limits the total number of connections per host, including connections in the dialing, active, and idle states. On limit violation, dials will block." With the limit set, unclosed bodies turn into blocked requests; without it, they turn into unbounded connections, ephemeral port exhaustion and file-descriptor limits. DefaultMaxIdleConnsPerHost is 2. The same shape appears with database/sql: an *sql.Rows not closed holds a connection, and with SetMaxOpenConns reached the next query waits (Connection Pooling).
1 req 1: resp, _ := c.Do(req); return resp.StatusCode body open -> conn busy
2 pool: MaxConnsPerHost = 1 reached
3 req 2: c.Do(req) -> dial blocks inside Transport
4 no ctx deadline: waits forever (looks like a deadlock); with deadline: "context deadline exceeded"
5 fix: defer resp.Body.Close(); io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))Real scenario: a webhook sender that checked only resp.StatusCode and froze after N calls; a health checker leaking a connection per probe until the target hit its connection limit; a Kubernetes service whose pods hung after a dependency got slow, because unclosed bodies plus no client timeout held every connection; rows.Next() loops that return early without rows.Close().
| Resource | Must do | Symptom if not |
|---|---|---|
*http.Response.Body | defer resp.Body.Close(); drain bounded | Pool exhaustion, fd leak |
http.Client | Set Timeout or always use a ctx deadline | Requests that wait forever |
*sql.Rows | defer rows.Close(); check rows.Err() | database/sql pool waits (WaitCount in DBStats) |
*sql.Tx | defer tx.Rollback() | Connection pinned, locks held in the DB |
| Goroutine-per-request with no limit | Bound with a semaphore | Memory and downstream overload |
Fix / how to use it: the httpbody snippet reproduces the stall with MaxConnsPerHost = 1 and proves the fix; the linter bodyclose (in golangci-lint, see Project Layout, golangci-lint) catches the pattern statically.
Goroutine leaks Important
In plain words: a goroutine that is blocked forever and will never be woken is a leak: it holds its stack and everything it references, and the count grows with traffic.
Common misunderstanding: "The garbage collector cleans up goroutines nobody can reach." The Code Review Comments wiki: "the garbage collector will not terminate a goroutine even if the channels it is blocked on are unreachable." Go 1.27 can now report such goroutines; it still does not kill them.
Definition: a leak is a partial deadlock: a goroutine parked on a primitive that no running goroutine can signal. The Go 1.26/1.27 goroutineleak profile: "A leaked goroutine is a goroutine blocked on some concurrency primitive (channels, sync.Mutex, sync.Cond, etc) that cannot possibly become unblocked", detected "using the garbage collector: if a goroutine G is blocked on concurrency primitive P, and P is unreachable from any runnable goroutine ..., then P cannot be unblocked." It "may fail to identify leaks caused by blocking on concurrency primitives reachable through global variables or the local variables of runnable goroutines."
1 handler: ch := make(chan result) unbuffered
2 for each item: go func() { ch <- work(it) }()
3 first result is an error -> handler returns
4 remaining goroutines: [chan send] forever ch now reachable only from them
5 goroutineleak profile: lists them; runtime.NumGoroutine() climbs per requestReal scenario: the Go 1.26 release-notes example (early return from a fan-in loop); a time.Ticker-driven goroutine with no stop; a per-connection reader that waits on a channel after the connection closed; context.WithCancel whose cancel is never called, leaving AfterFuncs and children alive.
| Detector | Finds | Misses |
|---|---|---|
runtime.NumGoroutine() metric | Growth over time | Which goroutines |
Goroutine dump (debug=2) | All stacks with wait reason and minutes waiting | Whether they can still be woken |
goroutineleak profile (Go 1.27) | Blocked on primitives unreachable from runnable goroutines | Primitives reachable from globals or runnable goroutines |
go.uber.org/goleak in tests | Goroutines alive after a test | Leaks not exercised by tests |
testing/synctest | Goroutines left blocked when the bubble's root returns ("deadlock" panic) | Code outside the bubble |
Fix / how to use it: every goroutine you start has a documented way to end ("When you spawn goroutines, make it clear when - or whether - they exit"), usually ctx.Done(); buffer result channels to the number of senders when the receiver can leave early; scrape go_goroutines and the leak profile in production.
Livelock and starvation Good to know
In plain words: in a livelock nobody is blocked, everybody is busy, and nothing gets done. In starvation the system makes progress, but one goroutine or one kind of request almost never gets its turn.
Common misunderstanding: "If CPU is high, the service is working." A livelocked service burns CPU retrying. And "sync.Mutex is fair": it is mostly not, by design, though it has a starvation mode.
Definition: livelock: goroutines repeatedly change state in response to each other without progress (two TryLock loops that release and retry in lockstep; two services that retry each other's failures without jitter). Starvation: a waiter is postponed indefinitely. sync.Mutex normally lets a newly arriving goroutine (already on a CPU) beat a woken waiter; if a waiter fails to acquire for more than 1 ms the mutex switches to starvation mode, handing ownership directly to the waiter at the queue head (comments in internal/sync/mutex.go). RWMutex prevents writer starvation: a waiting Lock blocks new readers.
goroutine 1 goroutine 2
1 a.Lock() b.Lock()
2 b.TryLock() -> false a.TryLock() -> false
3 a.Unlock(); retry b.Unlock(); retry <- same timing, same choice
4 a.Lock() ... b.Lock() ... repeat forever: livelock, CPU 100%
5 fix: global lock order, or randomised backoff (jitter)Real scenario: optimistic retry loops on a hot row or key that collide forever under load; a priority queue where low-priority jobs never run; a RWMutex-protected cache where a long read section holds out a reload; a scheduler that always picks the shortest job, starving long ones.
| Problem | Symptom | Fix |
|---|---|---|
| Livelock | High CPU, zero throughput | Lock order, jittered backoff, one coordinator |
| Starvation (locks) | Tail latency on one path | Shorter critical sections; Mutex starvation mode helps; fair queue |
| Starvation (scheduling) | One class of jobs ages forever | Aging, separate pools, weighted fair queues |
| Retry storms | Many clients retry together | Exponential backoff with jitter (Timeouts, Retries & Jitter) |
Fix / how to use it: measure with the mutex and block profiles (runtime.SetMutexProfileFraction, runtime.SetBlockProfileRate; Go 1.22 made mutex profiles "scale contention by the number of goroutines blocked"), keep critical sections short, add jitter to every retry.
Concurrency vs parallelism Must-know
In plain words: concurrency is designing a program as independent pieces that can make progress separately. Parallelism is actually running pieces at the same instant on several cores. A concurrent program on one core is still concurrent, and can still race.
Common misunderstanding: "With GOMAXPROCS=1 there are no races." The scheduler still switches goroutines (at blocking points and, since Go 1.14, by asynchronous preemption), so a goroutine can be paused between the load and the store of n++. The memory model has no single-core exception, and the race detector still reports the race (lab step 3: want 1000, got 1000 and WARNING: DATA RACE in the same run).
Definition: Pike (Waza 2012): "Concurrency is about structure, parallelism is about execution." Effective Go: "Be sure not to confuse the ideas of concurrency—structuring a program as independently executing components—and parallelism—executing calculations in parallel for efficiency on multiple CPUs." GOMAXPROCS "limits the number of operating system threads that can execute user-level Go code simultaneously"; the FAQ: "Setting it to 1 eliminates the possibility of true parallelism, forcing independent goroutines to take turns executing." Since Go 1.25 the default on Linux respects the cgroup CPU limit and is updated periodically.
GOMAXPROCS=1 P0: [G1 load n][G2 load n][G1 store][G2 store] concurrent, interleaved, race
GOMAXPROCS=12 P0: [G1 load n ... store]
P1: [G2 load n ... store] concurrent and parallel, race
same program, same bug; parallelism changes how often you see it, not whether it existsReal scenario: a service that "only fails on the big machines" because more parallelism made a latent race frequent; a CPU-bound job that got slower with more goroutines (the FAQ: "programs that spend more time synchronizing or communicating than doing useful computation may experience performance degradation"); a container throttled because GOMAXPROCS (before 1.25) used the node's 64 CPUs under a 2-CPU limit.
| Concurrency | Parallelism | |
|---|---|---|
| Is about | Structure: independent tasks | Execution: simultaneous tasks |
| Needs several cores | No | Yes |
| Go mechanism | goroutines, channels, select | GOMAXPROCS threads running goroutines |
| Speeds up | I/O-bound latency, responsiveness | CPU-bound throughput (if divisible) |
| Data races possible | Yes | Yes (more frequent) |
GOMAXPROCS=1 | Still concurrent | No parallelism |
Fix / how to use it: design for concurrency, measure for parallelism; never use GOMAXPROCS=1 as a correctness fix. In containers on Go 1.25+, leave the default or set the env var explicitly.
The Go memory model in one page Must-know
In plain words: the memory model is the contract that says when a write in one goroutine is guaranteed to be seen by a read in another. The answer is always "when a chain of synchronisation orders them."
Common misunderstanding: "Reads see the latest write." There is no "latest" without synchronisation. In the memory model's example, a goroutine writing a = 1; b = 2 can be observed by another as b == 2 and a == 0.
Definition: happens before is "the transitive closure of the union of the sequenced before and synchronized before relations." A race-free program gets DRF-SC: "data-race-free programs execute in a sequentially consistent manner", as if "all the goroutines were multiplexed onto a single processor." The synchronising operations (each line is a "synchronized before" edge):
| Operation | Edge |
|---|---|
Package init | "completion of all init functions is synchronized before the start of the function main.main" |
go statement | "synchronized before the start of the goroutine's execution" |
| Goroutine exit | "not guaranteed to be synchronized before any event" |
| Send on channel | "synchronized before the completion of the corresponding receive" |
close(ch) | "synchronized before a receive that returns a zero value because the channel is closed" |
| Receive on unbuffered channel | "synchronized before the completion of the corresponding send" |
| Buffered channel, capacity C | "The kth receive ... is synchronized before the completion of the k+Cth send" (semaphores) |
Mutex/RWMutex | "call n of l.Unlock() is synchronized before call m of l.Lock() returns" (n < m) |
TryLock | Success = Lock; failure has "no synchronizing effect at all" |
Once | completion of f "is synchronized before the return of any call of once.Do(f)" |
sync/atomic | "If the effect of an atomic operation A is observed by atomic operation B, then A is synchronized before B"; all atomics are sequentially consistent |
WaitGroup | "a call to Done 'synchronizes before' the return of any Wait call that it unblocks" (sync doc) |
runtime.SetFinalizer | "A call to SetFinalizer(x, f) is synchronized before the finalization call f(x)" |
goroutine f goroutine main
1 a = "hello, world" (sequenced before)
2 c <- 0 ---- synchronized before ----> <-c completes
3 print(a) guaranteed "hello, world"
---- broken ----
4 a = "hello"; done = true (plain bool) for !done {} may spin forever; may print ""Real scenario: a "ready" flag set by an init goroutine and polled by handlers; publishing a struct pointer after filling its fields; a sync.Cond-free hand-rolled wait loop; a test asserting a value written by a goroutine without waiting on anything.
Fix / how to use it: follow the memory model's own advice: "To serialize access, protect the data with channel operations or other synchronization primitives such as those in the sync and sync/atomic packages." If you need to argue about reorderings to prove your code correct, rewrite it.
Go
Before
A page-view tracker shared by every HTTP handler goroutine. It compiles, go vet is silent, and its only test is sequential, so go test -race passes. Under real traffic it has five bugs: lazy init without Once, a check-then-act on the distinct-path limit, an unsynchronised map write (fatal error: concurrent map writes), a racy multi-word string write, and an inconsistent two-field read in Top.
// Package before is a page-view tracker that compiles, passes a
// single-goroutine test, and is wrong as soon as two requests arrive at once.
package before
import "strings"
// Tracker counts views per path and remembers the most viewed path.
type Tracker struct {
views map[string]int
top string
stop map[string]bool // lazily built on first use
limit int
used int
}
// New returns a tracker that accepts at most limit distinct paths.
func New(limit int) *Tracker {
return &Tracker{views: make(map[string]int), limit: limit}
}
// Record is called from every HTTP handler goroutine.
func (t *Tracker) Record(path string) bool {
if t.stop == nil { // lazy init without sync.Once: two goroutines may both build it
t.stop = map[string]bool{"/healthz": true, "/metrics": true}
}
if t.stop[strings.ToLower(path)] {
return false
}
if _, seen := t.views[path]; !seen {
if t.used >= t.limit { // check ...
return false
}
t.used++ // ... then act: another goroutine can pass the check in between
}
t.views[path]++ // unsynchronised map write: "fatal error: concurrent map writes"
if t.views[path] > t.views[t.top] {
t.top = path // multi-word string header written without synchronisation
}
return true
}
// Top returns the most viewed path and its count.
func (t *Tracker) Top() (string, int) {
return t.top, t.views[t.top]
}package before
import "testing"
// The happy-path test is sequential, so neither go test nor go test -race
// sees a problem. The bug lives in code paths the test never runs concurrently.
func TestRecordSequential(t *testing.T) {
tr := New(2)
for _, p := range []string{"/a", "/a", "/b", "/c", "/healthz"} {
tr.Record(p)
}
if path, n := tr.Top(); path != "/a" || n != 2 {
t.Fatalf("Top() = %q, %d; want /a, 2", path, n)
}
}After
One sync.Mutex guards every shared field, the limit check and the insert are one critical section, the stop list is built once with sync.OnceValue, Top reads both values under one lock, and Snapshot returns a copy instead of the inner map. The test hammers it from 32 goroutines and passes go test -race -count=20.
// Package after is the same tracker with one mutex guarding every field the
// goroutines share, sync.OnceValue for lazy initialisation, and the
// check-then-act sequence inside a single critical section.
package after
import (
"strings"
"sync"
)
// stopPaths is built once, on first use, by exactly one goroutine; every
// caller sees the fully built map (Once completion happens before Do returns).
var stopPaths = sync.OnceValue(func() map[string]bool {
return map[string]bool{"/healthz": true, "/metrics": true}
})
// Tracker counts views per path. The zero value is not usable; call New.
type Tracker struct {
mu sync.Mutex // guards everything below
views map[string]int
top string
limit int
}
// New returns a tracker that accepts at most limit distinct paths.
func New(limit int) *Tracker {
return &Tracker{views: make(map[string]int), limit: limit}
}
// Record is safe for concurrent use.
func (t *Tracker) Record(path string) bool {
if stopPaths()[strings.ToLower(path)] { // read-only after init: no lock needed
return false
}
t.mu.Lock()
defer t.mu.Unlock()
if _, seen := t.views[path]; !seen && len(t.views) >= t.limit {
return false // check and act happen under the same lock
}
t.views[path]++
if t.views[path] > t.views[t.top] {
t.top = path
}
return true
}
// Top returns a consistent snapshot: path and count read under one lock.
func (t *Tracker) Top() (string, int) {
t.mu.Lock()
defer t.mu.Unlock()
return t.top, t.views[t.top]
}
// Snapshot returns a copy, so callers can range over it without the lock.
func (t *Tracker) Snapshot() map[string]int {
t.mu.Lock()
defer t.mu.Unlock()
out := make(map[string]int, len(t.views))
for k, v := range t.views {
out[k] = v
}
return out
}package after
import (
"fmt"
"sync"
"testing"
)
// Run with: go test -race -count=20 ./after
func TestRecordConcurrent(t *testing.T) {
const workers, perWorker, limit = 32, 500, 10
tr := New(limit)
var wg sync.WaitGroup
for w := range workers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range perWorker {
tr.Record(fmt.Sprintf("/p%d", (w+i)%20)) // 20 paths, limit 10
tr.Record("/healthz")
}
}()
}
wg.Wait()
snap := tr.Snapshot()
if len(snap) != limit {
t.Fatalf("distinct paths = %d; want exactly %d (limit)", len(snap), limit)
}
if _, ok := snap["/healthz"]; ok {
t.Fatal("stop path was counted")
}
path, n := tr.Top()
if snap[path] != n {
t.Fatalf("Top() = %q,%d but snapshot says %d: inconsistent read", path, n, snap[path])
}
}The Go angle
The standard library documents its concurrency contract per type, and you should read those lines before sharing a value: *http.Client and *http.Transport are safe for concurrent use and meant to be reused; *sql.DB is a pool "safe for concurrent use by multiple goroutines", while *sql.Tx and *sql.Rows are not; a *rand.Rand over its own Source is not (a Source "is not safe for concurrent use by multiple goroutines"), while the top-level math/rand/v2 functions are; bytes.Buffer and strings.Builder are not; a log/slog handler must be, because "Any of the Handler's methods may be called concurrently with itself"; a compiled regexp.Regexp is. The sync package says "Values containing the types defined in this package should not be copied", which go vet's copylocks enforces, and Go 1.24's vet reports a loop whose variable copies a sync.Locker each iteration. Every synchronising type documents its happens-before edge in memory-model terms ("synchronizes before"). The toolchain adds -race for every command, GOTRACEBACK and SIGQUIT dumps, runtime/pprof profiles (goroutine, goroutineleak, block, mutex), runtime/trace and its Go 1.25 FlightRecorder, and testing/synctest for deterministic tests.
Mechanics
Runtime, sync and detector messages, verbatim Must-know
| Message | Kind | Source / cause | Recoverable? |
|---|---|---|---|
fatal error: all goroutines are asleep - deadlock! | fatal | runtime.checkdead: no goroutine can run, no timers | No, exit 2 |
fatal error: no goroutines (main called runtime.Goexit) - deadlock! | fatal | main called runtime.Goexit and nothing is left | No |
fatal error: concurrent map writes | fatal | internal/runtime/maps writing flag seen by another writer | No |
fatal error: concurrent map read and map write | fatal | Reader saw the writing flag | No |
fatal error: concurrent map iteration and map write | fatal | range over a map being written | No |
fatal error: sync: unlock of unlocked mutex | fatal | Unlock without Lock (internal/sync) | No |
fatal error: sync: RUnlock of unlocked RWMutex / sync: Unlock of unlocked RWMutex | fatal | Unbalanced RWMutex | No |
panic: sync: negative WaitGroup counter | panic | More Done than Add | Yes (but a bug) |
panic: sync: WaitGroup is reused before previous Wait has returned | panic | Add on a group still being waited on | Yes |
panic: sync: WaitGroup misuse: Add called concurrently with Wait | panic | Sanity check in Add/Wait | Yes |
panic: send on closed channel | panic | Send after close | Yes |
panic: close of closed channel / panic: close of nil channel | panic | Double close / nil | Yes |
WARNING: DATA RACE | detector | -race build saw an unordered pair | Process continues unless halt_on_error=1; exit 66 |
testing.go:NNNN: race detected during execution of test | test | Race during a test | Test fails |
panic: test timed out after 10m0s | test | go test -timeout (default 10m) expired; prints all goroutines | No |
context deadline exceeded | error | A blocked operation's context expired | Yes: the diagnosis for an apparent hang |
SIGQUIT: quit | signal | kill -QUIT / Ctrl-\: dump all goroutines, exit 2 | No |
How the race detector works
The compiler, when -race is set, inserts calls such as racefuncenter, raceread and racewrite around memory accesses and function entries; the sync, channel and atomic implementations call raceacquire/racerelease to tell the detector about happens-before edges (the WaitGroup source even contains the comment "Need to model this as a read, because there can be several concurrent wg.counter transitions from 0"). The ThreadSanitizer runtime keeps each goroutine's logical clock and, for "every aligned 8-byte word of application memory", N shadow words recording recent accesses; when a new access conflicts with a stored one and the stored one does not happen before it, it reports. Consequences you can see:
| Fact | Consequence |
|---|---|
| Dynamic, happens-before based | No false positives for code using Go's primitives; misses unexecuted paths |
| Shadow memory + history per goroutine | "memory usage may increase by 5-10x"; old accesses can be evicted |
history_size (0–7, default 1) | "32K * 2**history_size elements" per goroutine; raise it when reports say "failed to restore the stack" |
| Reports at most once per pair of PCs | Fix the first report and rerun to see the next |
| Needs cgo, supported platform | Not available on every GOOS/GOARCH |
Build tag race | //go:build !race can exclude a known-slow test, but never to hide a race |
defer/recover allocate 8 bytes under -race | Long-lived goroutines with frequent defers grow memory under -race only |
GORACE options
| Option | Default | Use |
|---|---|---|
log_path | stderr | Write reports to log_path.pid (useful for a canary) |
exitcode | 66 | Exit status after a detected race |
strip_path_prefix | "" | Shorter paths in reports |
history_size | 1 | More history, fewer "failed to restore the stack" |
halt_on_error | 0 | 1 = exit after the first race |
atexit_sleep_ms | 1000 | Delay before exit so late reports are printed |
Example: GORACE="halt_on_error=1 strip_path_prefix=/src/" go test -race ./....
How the runtime detects (only total) deadlock
checkdead runs when an OS thread goes idle. It counts threads running Go code; if none are running, it checks for goroutines that could still be woken. A pending timer, a goroutine in a system call, or a non-empty network poller means "maybe later", so no report. Only when nothing at all can happen does it print all goroutines are asleep - deadlock! with every goroutine's stack. That is why the same lock-order bug produces a crash in a 20-line demo and silence in a server: the HTTP listener goroutine is waiting on the poller. Mutex, channel, WaitGroup and Cond waits all count as "asleep"; the dump shows which.
Goroutine dumps: SIGQUIT, GOTRACEBACK, pprof, runtime.Stack
| Method | Output | Process | When |
|---|---|---|---|
kill -QUIT <pid> / Ctrl-\ | SIGQUIT: quit, then every goroutine (GOTRACEBACK=all behaviour), exit 2 | Dies | Hung process you will restart anyway |
GOTRACEBACK=all / system / crash | Controls detail of fatal dumps; crash raises SIGABRT for a core dump | Dies | Set in the service env so a fatal error shows all goroutines |
/debug/pprof/goroutine?debug=2 | Same format as a panic dump, "in the same form that a Go program uses when dying due to an unrecovered panic" | Keeps running | Production diagnosis (import net/http/pprof on an internal port) |
/debug/pprof/goroutine?debug=1 | Goroutines grouped by identical stack with counts | Keeps running | "500 goroutines in the same place" |
/debug/pprof/goroutineleak | Leaked goroutines only (Go 1.27) | Keeps running | Leak hunting |
pprof.Lookup("goroutine").WriteTo(w, 2) | Same as debug=2 | Keeps running | Watchdogs, test helpers |
runtime.Stack(buf, true) | "If all is true, Stack formats stack traces of all other goroutines into buf"; stops the world | Keeps running | Watchdog in dump.Within |
go test -timeout expiry | panic: test timed out + all goroutines | Test binary dies | Hanging tests |
A goroutine header reads goroutine 34 gp=0x... m=nil [sync.Mutex.Lock]: in a SIGQUIT dump (GOTRACEBACK=all adds gp/m), or goroutine 34 [sync.Mutex.Lock, 12 minutes]: in a panic-style dump once the wait is long; since Go 1.27, modules on go 1.27 also print pprof goroutine labels in that header. The wait reasons you will see most:
| Wait reason | Means |
|---|---|
[chan send] / [chan receive] | Blocked on one channel operation |
[chan send (nil chan)] / [chan receive (nil chan)] | Operation on a nil channel: blocks forever |
[select] / [select (no cases)] | Blocked in select / select {} |
[sync.Mutex.Lock] / [sync.RWMutex.Lock] / [sync.RWMutex.RLock] | Waiting for a lock |
[sync.WaitGroup.Wait] | Waiting for Dones |
[sync.Cond.Wait] | Waiting for Signal/Broadcast |
[IO wait] | Network poller (normal for listeners and idle connections) |
[semacquire] | Other runtime semaphores (e.g. older toolchains for mutexes) |
[sleep] | time.Sleep |
[running] / [runnable] | On a CPU / ready to run |
Map concurrent-access check
Each Swiss-table map (Go 1.24+) has a writing flag in its header. A write sets it, mutates, clears it; any concurrent access that observes the flag calls fatal. Since the flag is checked only at specific points, the check is "best-effort": two writes can interleave without being caught, and a read concurrent with a write may silently return garbage. fatal (not panic) is deliberate: after map corruption no code can be trusted to run, so neither defers nor recover get a chance.
GOMAXPROCS and the scheduler
The scheduler multiplexes goroutines (G) onto OS threads (M) through GOMAXPROCS logical processors (P). Goroutines switch at channel operations, locks, system calls, function prologues and, since Go 1.14, through asynchronous preemption signals, so a tight loop is not safe from interruption. Defaults: number of logical CPUs at start; on Go 1.25+ on Linux, capped by the cgroup CPU bandwidth limit and updated periodically (containermaxprocs=0, updatemaxprocs=0 GODEBUGs disable this; setting GOMAXPROCS explicitly disables both). Threads blocked in syscalls do not count against GOMAXPROCS. For races the number does not matter; for throughput it does.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Shared counter loses updates | Mutex or atomic | counter.Mutex, counter.Atomic | Exact | Contention at high core counts |
| Shared state with a lifecycle | Owner goroutine | counter.Owner | No locks in callers | Slower per op; must Close |
| Parallel work with results | Confinement | results[i], merge after Wait | No sharing | Needs known n |
| Read-mostly config | Immutable snapshot | atomic.Pointer[Config] | Lock-free reads | Writers copy |
| Map crash under load | Mutex-wrapped map | after.Tracker | Simple | One lock |
| Lazy singleton | sync.OnceValue | stopPaths() | Exactly once, visible | No retry on failure |
| Double booking | One critical section / DB constraint | booking.Book | Invariant holds | Lock or constraint scope |
| Double charge on retry | Claim state transition | booking.Confirm | Idempotent | State machine to maintain |
| Two locks, two orders | Global lock order | lockorder.Transfer | Cycle impossible | Discipline everywhere |
| Silent hang | Timeout + goroutine dump | dump.Within | Evidence in logs | Does not unblock |
| HTTP client stalls | Close + drain body, ctx deadline | httpbody.Status | Connections reused | — |
| Time-based tests are slow/flaky | testing/synctest | watchdog test | Instant, deterministic | Go 1.25+; no real I/O |
| Old loop semantics | Upgrade module to go 1.22+ | loopvar | Per-iteration vars | Check per-file build lines |
One counter, five fixes
Racy is the bug, never exercised concurrently in tests (the lab runs it under -race). Mutex, Atomic and Owner are hammered by 16 goroutines; Sharded shows confinement; Store shows immutability with atomic.Pointer; FuzzSharded is a fuzz target whose seeds run with every go test. Benchmarks on this host (12 CPUs, RunParallel): mutex ≈ 111 ns/op, atomic ≈ 57–63 ns/op, owner goroutine ≈ 420 ns/op; under -race the same benchmarks took 378, 334 and 863 ns/op.
// Package counter shows the same shared counter fixed five ways: mutex,
// atomic, channel ownership, confinement (sharding) and immutability.
package counter
import (
"sync"
"sync/atomic"
)
// Counter is what every implementation offers.
type Counter interface {
Add(n int64)
Value() int64
}
// Racy is the bug: n++ is a read, an add and a write; two goroutines interleave.
type Racy struct{ n int64 }
func (c *Racy) Add(n int64) { c.n += n }
func (c *Racy) Value() int64 { return c.n }
// Mutex serialises access: the simplest correct fix and the default choice.
type Mutex struct {
mu sync.Mutex
n int64
}
func (c *Mutex) Add(n int64) {
c.mu.Lock()
c.n += n
c.mu.Unlock()
}
func (c *Mutex) Value() int64 {
c.mu.Lock()
defer c.mu.Unlock()
return c.n
}
// Atomic uses one hardware read-modify-write; fine for a single word only.
type Atomic struct{ n atomic.Int64 }
func (c *Atomic) Add(n int64) { c.n.Add(n) }
func (c *Atomic) Value() int64 { return c.n.Load() }
// Owner confines the integer to one goroutine; others send it messages.
type Owner struct {
add chan int64
read chan chan int64
done chan struct{}
}
// NewOwner starts the owning goroutine. Call Close to stop it.
func NewOwner() *Owner {
o := &Owner{add: make(chan int64), read: make(chan chan int64), done: make(chan struct{})}
go func() {
var n int64 // only this goroutine ever touches n
for {
select {
case d := <-o.add:
n += d
case reply := <-o.read:
reply <- n
case <-o.done:
return
}
}
}()
return o
}
func (o *Owner) Add(n int64) { o.add <- n }
func (o *Owner) Value() int64 {
reply := make(chan int64)
o.read <- reply
return <-reply
}
// Close stops the owner goroutine so it does not leak.
func (o *Owner) Close() { close(o.done) }
// Sharded confines work per goroutine: each worker owns one slot and the
// slots are merged once, after a happens-before edge (wg.Wait).
func Sharded(workers int, work func(worker int) int64) int64 {
slots := make([]int64, workers)
var wg sync.WaitGroup
for w := range workers {
wg.Add(1)
go func() {
defer wg.Done()
slots[w] = work(w) // distinct elements are distinct variables: no race
}()
}
wg.Wait()
var total int64
for _, v := range slots {
total += v
}
return total
}
// Config is published as an immutable snapshot: writers build a new value
// and swap the pointer; readers never see a half-written struct.
type Config struct {
Limits map[string]int // never mutated after Publish
}
// Store holds the current *Config.
type Store struct{ p atomic.Pointer[Config] }
// Publish copies the input so later caller edits cannot leak in.
func (s *Store) Publish(limits map[string]int) {
cp := make(map[string]int, len(limits))
for k, v := range limits {
cp[k] = v
}
s.p.Store(&Config{Limits: cp})
}
// Load returns the current snapshot (nil before the first Publish).
func (s *Store) Load() *Config { return s.p.Load() }package counter
import (
"sync"
"testing"
)
func hammer(c Counter, goroutines, perG int) {
var wg sync.WaitGroup
for range goroutines {
wg.Add(1)
go func() {
defer wg.Done()
for range perG {
c.Add(1)
}
}()
}
wg.Wait()
}
// The racy type is deliberately not exercised concurrently here, so
// go test -race stays green; the lab runs it under -race to see the report.
func TestCorrectCounters(t *testing.T) {
const g, n = 16, 2000
owner := NewOwner()
defer owner.Close()
for name, c := range map[string]Counter{"mutex": &Mutex{}, "atomic": &Atomic{}, "owner": owner} {
t.Run(name, func(t *testing.T) {
hammer(c, g, n)
if got := c.Value(); got != g*n {
t.Fatalf("Value() = %d; want %d", got, g*n)
}
})
}
}
func TestSharded(t *testing.T) {
got := Sharded(8, func(w int) int64 {
var local int64
for range 1000 {
local++
}
return local + int64(w)
})
if want := int64(8*1000 + 28); got != want {
t.Fatalf("Sharded = %d; want %d", got, want)
}
}
func TestStoreSnapshotIsImmutable(t *testing.T) {
var s Store
in := map[string]int{"rps": 100}
s.Publish(in)
in["rps"] = 1 // caller edits its own map afterwards
var wg sync.WaitGroup
for range 8 {
wg.Add(1)
go func() {
defer wg.Done()
for range 1000 {
if v := s.Load().Limits["rps"]; v != 100 && v != 200 {
t.Errorf("saw %d", v)
return
}
}
}()
}
s.Publish(map[string]int{"rps": 200})
wg.Wait()
}
// FuzzSharded checks the merge for arbitrary worker counts and loads.
// go test runs the seeds; go test -fuzz=FuzzSharded explores further.
func FuzzSharded(f *testing.F) {
f.Add(uint8(1), uint16(0))
f.Add(uint8(7), uint16(1000))
f.Fuzz(func(t *testing.T, workers uint8, per uint16) {
w := int(workers%32) + 1
got := Sharded(w, func(int) int64 { return int64(per) })
if want := int64(w) * int64(per); got != want {
t.Fatalf("Sharded(%d, %d) = %d; want %d", w, per, got, want)
}
})
}
func benchCounter(b *testing.B, c Counter) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
c.Add(1)
}
})
}
func BenchmarkMutex(b *testing.B) { benchCounter(b, &Mutex{}) }
func BenchmarkAtomic(b *testing.B) { benchCounter(b, &Atomic{}) }
func BenchmarkOwner(b *testing.B) {
o := NewOwner()
defer o.Close()
benchCounter(b, o)
}Reproducing races on purpose
Four scenarios for the lab: lost updates, concurrent map writes, append from goroutines, and torn string reads.
// Command racedemo reproduces the classic races on purpose. Run it with and
// without -race to see the difference between a silent bug and a report:
//
// go run ./racedemo counter
// go run -race ./racedemo counter
// go run ./racedemo map // fatal error: concurrent map writes
// go run -race ./racedemo append
package main
import (
"fmt"
"os"
"sync"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: racedemo counter|map|append|header")
os.Exit(2)
}
switch os.Args[1] {
case "counter":
counter()
case "map":
mapWrites()
case "append":
appendRace()
case "header":
header()
default:
fmt.Fprintln(os.Stderr, "unknown scenario")
os.Exit(2)
}
}
// counter: n++ from many goroutines loses updates.
func counter() {
var n int
var wg sync.WaitGroup
for range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
n++ // read-modify-write, not atomic
}()
}
wg.Wait()
fmt.Println("want 1000, got", n)
}
// mapWrites: the runtime's cheap check usually crashes the process.
func mapWrites() {
m := map[int]int{}
var wg sync.WaitGroup
for g := range 8 {
wg.Add(1)
go func() {
defer wg.Done()
for i := range 100_000 {
m[i%64] = g
}
}()
}
wg.Wait()
fmt.Println("survived this time, len =", len(m))
}
// appendRace: append reads and writes the slice header of a shared variable.
func appendRace() {
var ids []int
var wg sync.WaitGroup
for i := range 100 {
wg.Add(1)
go func() {
defer wg.Done()
ids = append(ids, i)
}()
}
wg.Wait()
fmt.Println("want 100, got", len(ids))
}
// header: a string is a (pointer, length) pair; a racing reader can see a
// pointer from one write and a length from another (a torn read).
func header() {
s := "short"
done := make(chan struct{})
go func() {
for i := 0; i < 1_000_000; i++ {
if i%2 == 0 {
s = "short"
} else {
s = "a much longer string value"
}
}
close(done)
}()
torn := 0
for {
select {
case <-done:
fmt.Println("torn reads observed:", torn)
return
default:
if v := s; v != "short" && v != "a much longer string value" {
torn++
}
}
}
}Lock ordering, proven by a test
TransferUnordered deadlocks when a barrier forces both goroutines to hold their first lock; the test detects the hang with dump.Within and checks that the dump shows sync.Mutex.Lock. Transfer orders by ID and survives the same pressure plus a 300-goroutine stress test that also checks money is conserved.
// Package lockorder shows the lock-ordering deadlock and its fix: always
// acquire several locks in one global order (here: by account ID).
package lockorder
import (
"errors"
"sync"
)
// ErrInsufficient is returned when the source balance is too low.
var ErrInsufficient = errors.New("insufficient funds")
// Account is a balance guarded by its own mutex.
type Account struct {
ID int
mu sync.Mutex
balance int64
}
// NewAccount returns an account with an opening balance.
func NewAccount(id int, balance int64) *Account { return &Account{ID: id, balance: balance} }
// Balance reads under the lock.
func (a *Account) Balance() int64 {
a.mu.Lock()
defer a.mu.Unlock()
return a.balance
}
// TransferUnordered locks from, then to. Transfer(a,b) running at the same
// time as Transfer(b,a) can leave each goroutine holding one lock and
// waiting for the other forever. No runtime message appears while any other
// goroutine (an HTTP listener, a ticker) is alive.
func TransferUnordered(from, to *Account, amount int64) error {
return transferUnordered(from, to, amount, nil)
}
// between lets a test widen the window between the two Lock calls.
func transferUnordered(from, to *Account, amount int64, between func()) error {
from.mu.Lock()
defer from.mu.Unlock()
if between != nil {
between()
}
to.mu.Lock()
defer to.mu.Unlock()
return move(from, to, amount)
}
// Transfer locks the lower ID first, so every goroutine agrees on the order
// and a cycle in the wait-for graph cannot form.
func Transfer(from, to *Account, amount int64) error {
return transfer(from, to, amount, nil)
}
func transfer(from, to *Account, amount int64, between func()) error {
if from == to {
return nil
}
first, second := from, to
if second.ID < first.ID {
first, second = second, first
}
first.mu.Lock()
defer first.mu.Unlock()
if between != nil {
between()
}
second.mu.Lock()
defer second.mu.Unlock()
return move(from, to, amount)
}
func move(from, to *Account, amount int64) error {
if from.balance < amount {
return ErrInsufficient
}
from.balance -= amount
to.balance += amount
return nil
}package lockorder
import (
"errors"
"strings"
"sync"
"testing"
"time"
"academy/race-conditions-deadlocks/dump"
)
// barrier makes both transfers take their first lock before either takes
// its second: the interleaving that a busy server hits once a week.
func barrier() func() {
var arrived sync.WaitGroup
arrived.Add(2)
return func() {
arrived.Done()
arrived.Wait()
}
}
func TestUnorderedDeadlocks(t *testing.T) {
between := barrier()
a, b := NewAccount(1, 100), NewAccount(2, 100)
err := dump.Within(200*time.Millisecond, func() {
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); _ = transferUnordered(a, b, 10, between) }()
go func() { defer wg.Done(); _ = transferUnordered(b, a, 10, between) }()
wg.Wait()
})
if !errors.Is(err, dump.ErrStuck) {
t.Fatalf("expected a deadlock, got %v", err)
}
if !strings.Contains(err.Error(), "sync.Mutex.Lock") {
t.Fatalf("dump should show goroutines in sync.Mutex.Lock:\n%s", err)
}
// The two goroutines stay blocked until the test binary exits: a
// deadlocked goroutine cannot be cancelled or killed.
}
func TestOrderedNeverDeadlocks(t *testing.T) {
// A barrier would never open here: with ordering, the second transfer
// waits for lock 1 before it can reach the hook. Widen the window instead.
between := func() { time.Sleep(20 * time.Millisecond) }
a, b := NewAccount(1, 100), NewAccount(2, 100)
err := dump.Within(2*time.Second, func() {
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); _ = transfer(a, b, 10, between) }()
go func() { defer wg.Done(); _ = transfer(b, a, 10, between) }()
wg.Wait()
})
if err != nil {
t.Fatal(err)
}
if got := a.Balance() + b.Balance(); got != 200 {
t.Fatalf("money created or destroyed: total %d", got)
}
}
func TestOrderedStress(t *testing.T) {
accts := []*Account{NewAccount(1, 1000), NewAccount(2, 1000), NewAccount(3, 1000)}
var wg sync.WaitGroup
for i := range 300 {
wg.Add(1)
go func() {
defer wg.Done()
from, to := accts[i%3], accts[(i+1+i/3)%3]
_ = Transfer(from, to, 7)
}()
}
if err := dump.Within(5*time.Second, wg.Wait); err != nil {
t.Fatal(err)
}
var total int64
for _, a := range accts {
total += a.Balance()
}
if total != 3000 {
t.Fatalf("total = %d; want 3000", total)
}
}Turning a hang into evidence
AllStacks grows its buffer until runtime.Stack fits; Profile returns the debug=2 goroutine profile; Within runs a function with a deadline and returns ErrStuck plus a full dump. It cannot stop the stuck goroutine: Go has no way to kill one.
// Package dump captures goroutine stacks for deadlock diagnosis: the same
// information SIGQUIT prints, but on demand and without killing the process.
package dump
import (
"bytes"
"errors"
"fmt"
"runtime"
"runtime/pprof"
"time"
)
// ErrStuck reports that an operation did not finish in time.
var ErrStuck = errors.New("operation did not finish")
// AllStacks returns runtime.Stack(buf, true), growing buf until it fits.
// It stops the world briefly; call it on a diagnosis path, not per request.
func AllStacks() []byte {
buf := make([]byte, 64<<10)
for {
n := runtime.Stack(buf, true)
if n < len(buf) {
return buf[:n]
}
buf = make([]byte, 2*len(buf))
}
}
// Profile returns the goroutine profile in the panic-style format (debug=2),
// identical to what /debug/pprof/goroutine?debug=2 serves.
func Profile() []byte {
var b bytes.Buffer
_ = pprof.Lookup("goroutine").WriteTo(&b, 2)
return b.Bytes()
}
// Within runs f in a new goroutine and waits up to d. If f is still running,
// it returns ErrStuck wrapped with a full goroutine dump. f keeps running:
// Go cannot kill a goroutine, so a timeout is a diagnosis, not a cure.
func Within(d time.Duration, f func()) error {
done := make(chan struct{})
go func() {
defer close(done)
f()
}()
t := time.NewTimer(d)
defer t.Stop()
select {
case <-done:
return nil
case <-t.C:
return fmt.Errorf("%w after %v\n%s", ErrStuck, d, AllStacks())
}
}package dump
import (
"bytes"
"errors"
"testing"
"time"
)
func TestWithinFinishes(t *testing.T) {
if err := Within(time.Second, func() {}); err != nil {
t.Fatal(err)
}
}
func TestWithinReportsStuckGoroutine(t *testing.T) {
block := make(chan struct{})
defer close(block) // release the goroutine so the test does not leak it
err := Within(50*time.Millisecond, func() { <-block })
if !errors.Is(err, ErrStuck) {
t.Fatalf("err = %v; want ErrStuck", err)
}
if !bytes.Contains([]byte(err.Error()), []byte("[chan receive]")) {
t.Fatalf("dump does not show the blocked receive:\n%s", err)
}
}
func TestProfileHasGoroutineHeader(t *testing.T) {
if p := Profile(); !bytes.Contains(p, []byte("goroutine ")) {
t.Fatalf("unexpected profile: %.200s", p)
}
}The HTTP "deadlock" that is pool exhaustion
With MaxConnsPerHost = 1, one unclosed body blocks the next request until its context deadline; closing and draining the body lets 20 sequential requests share one connection.
// Package httpbody shows the "hang" that is not a deadlock: response bodies
// that are never closed keep their connections busy until the pool is empty.
package httpbody
import (
"context"
"io"
"net/http"
)
// NewClient returns a client with a small per-host connection cap, the
// setting that turns a leak into an obvious stall instead of a slow drift.
func NewClient(maxConnsPerHost int) *http.Client {
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxConnsPerHost = maxConnsPerHost // "On limit violation, dials will block."
return &http.Client{Transport: t} // no Client.Timeout: callers pass a ctx deadline
}
// StatusLeaky returns the status code and forgets the body. The connection
// stays checked out; with MaxConnsPerHost reached, the next request waits.
func StatusLeaky(ctx context.Context, c *http.Client, url string) (int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
resp, err := c.Do(req)
if err != nil {
return 0, err
}
return resp.StatusCode, nil // BUG: resp.Body is never closed
}
// Status drains a bounded amount and closes the body, which returns the
// connection to the idle pool for reuse.
func Status(ctx context.Context, c *http.Client, url string) (int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
resp, err := c.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
return resp.StatusCode, nil
}package httpbody
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func server(t *testing.T) *httptest.Server {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(strings.Repeat("x", 4096)))
}))
t.Cleanup(func() {
srv.CloseClientConnections()
srv.Close()
})
return srv
}
func TestLeakyClientStalls(t *testing.T) {
srv := server(t)
c := NewClient(1)
if _, err := StatusLeaky(context.Background(), c, srv.URL); err != nil {
t.Fatal(err)
}
// The only allowed connection is still owned by the unread first body.
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
_, err := StatusLeaky(ctx, c, srv.URL)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("second request: err = %v; want context deadline exceeded", err)
}
}
func TestClosingClientReusesConnection(t *testing.T) {
srv := server(t)
c := NewClient(1)
for i := range 20 {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
code, err := Status(ctx, c, srv.URL)
cancel()
if err != nil || code != http.StatusOK {
t.Fatalf("request %d: code=%d err=%v", i, code, err)
}
}
}Race-free race conditions: booking and TOCTOU
Every access in booking is locked, so -race is silent, yet BookCheckThenAct sells a seat twice and ConfirmTOCTOU charges twice when tests force the interleaving. Book and Confirm make the check and the state change one step; the clock is injected so the expiry decision is testable.
// Package booking shows a race condition that is not a data race: every
// field access is locked, the race detector is silent, and seats still get
// sold twice because the check and the act are two critical sections.
package booking
import (
"errors"
"sync"
"time"
)
// Errors returned by the safe API.
var (
ErrTaken = errors.New("seat already booked")
ErrExpired = errors.New("hold expired")
ErrNoHold = errors.New("no such hold")
)
// Hold reserves a seat for a user until Expires.
type Hold struct {
Seat, User string
Expires time.Time
Confirmed bool
}
// Inventory is safe for concurrent use; each method locks mu.
type Inventory struct {
mu sync.Mutex
owner map[string]string // seat -> user
holds map[string]*Hold // hold ID -> hold
}
// New returns an empty inventory.
func New() *Inventory {
return &Inventory{owner: map[string]string{}, holds: map[string]*Hold{}}
}
// Available is correctly locked, but its answer is stale the moment the
// lock is released.
func (inv *Inventory) Available(seat string) bool {
inv.mu.Lock()
defer inv.mu.Unlock()
_, taken := inv.owner[seat]
return !taken
}
// assign is the unconditional write used by the buggy path.
func (inv *Inventory) assign(seat, user string) {
inv.mu.Lock()
defer inv.mu.Unlock()
inv.owner[seat] = user
}
// BookCheckThenAct is the bug: check (locked), gap, act (locked).
// between lets a test hold the gap open; production passes nil.
func (inv *Inventory) BookCheckThenAct(seat, user string, between func()) bool {
if !inv.Available(seat) {
return false
}
if between != nil {
between()
}
inv.assign(seat, user) // a second buyer may have passed the same check
return true
}
// Book checks and writes inside one critical section.
func (inv *Inventory) Book(seat, user string) error {
inv.mu.Lock()
defer inv.mu.Unlock()
if _, taken := inv.owner[seat]; taken {
return ErrTaken
}
inv.owner[seat] = user
return nil
}
// Owner reports who owns seat.
func (inv *Inventory) Owner(seat string) string {
inv.mu.Lock()
defer inv.mu.Unlock()
return inv.owner[seat]
}
// PutHold registers a hold (setup helper).
func (inv *Inventory) PutHold(id string, h Hold) {
inv.mu.Lock()
defer inv.mu.Unlock()
inv.holds[id] = &h
}
// ConfirmTOCTOU checks expiry with one clock reading, then does slow work,
// then confirms: time of check is not time of use, and two confirms of the
// same hold can both succeed.
func (inv *Inventory) ConfirmTOCTOU(id string, now func() time.Time, charge func()) error {
inv.mu.Lock()
h, ok := inv.holds[id]
valid := ok && now().Before(h.Expires) && !h.Confirmed
inv.mu.Unlock()
if !valid {
return ErrExpired
}
charge() // payment call: hundreds of milliseconds, the hold may expire meanwhile
inv.mu.Lock()
h.Confirmed = true
inv.owner[h.Seat] = h.User
inv.mu.Unlock()
return nil
}
// Confirm makes the state transition atomic: claim the hold (Held ->
// Confirming) under the lock, charge outside it, and let a second caller see
// that the hold is already claimed. The expiry decision is taken once.
func (inv *Inventory) Confirm(id string, now func() time.Time, charge func() error) error {
inv.mu.Lock()
h, ok := inv.holds[id]
switch {
case !ok:
inv.mu.Unlock()
return ErrNoHold
case h.Confirmed:
inv.mu.Unlock()
return ErrTaken
case !now().Before(h.Expires):
inv.mu.Unlock()
return ErrExpired
}
h.Confirmed = true // claimed: nobody else can confirm this hold
inv.mu.Unlock()
if err := charge(); err != nil {
inv.mu.Lock()
h.Confirmed = false // release the claim; the hold is still time-bounded
inv.mu.Unlock()
return err
}
inv.mu.Lock()
defer inv.mu.Unlock()
inv.owner[h.Seat] = h.User
return nil
}package booking
import (
"errors"
"sync"
"sync/atomic"
"testing"
"time"
)
func barrier(n int) func() {
var wg sync.WaitGroup
wg.Add(n)
return func() { wg.Done(); wg.Wait() }
}
// Passes under -race: there is no data race. The test proves the logical
// race by forcing both buyers through the gap.
func TestCheckThenActDoubleSells(t *testing.T) {
inv := New()
between := barrier(2)
var sold atomic.Int32
var wg sync.WaitGroup
for _, u := range []string{"ana", "bob"} {
wg.Add(1)
go func() {
defer wg.Done()
if inv.BookCheckThenAct("12A", u, between) {
sold.Add(1)
}
}()
}
wg.Wait()
if sold.Load() != 2 {
t.Fatalf("sold %d; the forced interleaving should sell the seat twice", sold.Load())
}
}
// Stress loop: many buyers, one seat, exactly one winner, every run.
func TestBookExactlyOnce(t *testing.T) {
for range 200 {
inv := New()
var wins atomic.Int32
var wg sync.WaitGroup
for range 16 {
wg.Add(1)
go func() {
defer wg.Done()
if inv.Book("12A", "someone") == nil {
wins.Add(1)
}
}()
}
wg.Wait()
if wins.Load() != 1 {
t.Fatalf("wins = %d; want 1", wins.Load())
}
}
}
func TestConfirmTOCTOUDoubleCharges(t *testing.T) {
inv := New()
base := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
inv.PutHold("h1", Hold{Seat: "12A", User: "ana", Expires: base.Add(time.Minute)})
now := func() time.Time { return base }
between := barrier(2)
var charges atomic.Int32
var wg sync.WaitGroup
for range 2 { // a double-click, or a client retry after a timeout
wg.Add(1)
go func() {
defer wg.Done()
_ = inv.ConfirmTOCTOU("h1", now, func() { between(); charges.Add(1) })
}()
}
wg.Wait()
if charges.Load() != 2 {
t.Fatalf("charges = %d; the TOCTOU version should charge twice here", charges.Load())
}
}
func TestConfirmChargesOnce(t *testing.T) {
inv := New()
base := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
inv.PutHold("h1", Hold{Seat: "12A", User: "ana", Expires: base.Add(time.Minute)})
now := func() time.Time { return base }
var charges atomic.Int32
var wg sync.WaitGroup
errs := make([]error, 8)
for i := range 8 {
wg.Add(1)
go func() {
defer wg.Done()
errs[i] = inv.Confirm("h1", now, func() error { charges.Add(1); return nil })
}()
}
wg.Wait()
if charges.Load() != 1 || inv.Owner("12A") != "ana" {
t.Fatalf("charges=%d owner=%q", charges.Load(), inv.Owner("12A"))
}
taken := 0
for _, err := range errs {
if errors.Is(err, ErrTaken) {
taken++
}
}
if taken != 7 {
t.Fatalf("ErrTaken returned %d times; want 7", taken)
}
late := func() time.Time { return base.Add(2 * time.Minute) }
inv.PutHold("h2", Hold{Seat: "12B", User: "bob", Expires: base.Add(time.Minute)})
if err := inv.Confirm("h2", late, func() error { return nil }); !errors.Is(err, ErrExpired) {
t.Fatalf("late confirm: %v; want ErrExpired", err)
}
}Loop variables: both semantics in one module
loopvar.go follows the module's go 1.24; legacy.go starts with //go:build go1.21, which downgrades that file to the old semantics. The test proves [0 1 2] versus [3 3 3] with the same compiler.
// Package loopvar shows the Go 1.22 change: each iteration of a for loop
// now has its own variable. This file follows the module (go 1.24).
package loopvar
// Collect returns closures that each remember their own iteration.
func Collect(n int) []func() int {
var fs []func() int
for i := 0; i < n; i++ {
fs = append(fs, func() int { return i }) // a fresh i per iteration
}
return fs
}//go:build go1.21
// The build line above downgrades THIS file to Go 1.21 language semantics,
// the per-file control described in "Fixing For Loops in Go 1.22".
package loopvar
// CollectLegacy is the same code with pre-1.22 semantics: one i shared by
// every iteration, so every closure sees the final value. With "go f()"
// instead of a stored closure this was also a data race on i.
func CollectLegacy(n int) []func() int {
var fs []func() int
for i := 0; i < n; i++ {
fs = append(fs, func() int { return i })
}
return fs
}package loopvar
import (
"slices"
"testing"
)
func values(fs []func() int) []int {
var out []int
for _, f := range fs {
out = append(out, f())
}
return out
}
func TestPerIterationVariable(t *testing.T) {
if got := values(Collect(3)); !slices.Equal(got, []int{0, 1, 2}) {
t.Fatalf("go1.22+ semantics: got %v; want [0 1 2]", got)
}
}
func TestLegacySharedVariable(t *testing.T) {
if got := values(CollectLegacy(3)); !slices.Equal(got, []int{3, 3, 3}) {
t.Fatalf("go1.21 semantics: got %v; want [3 3 3]", got)
}
}Deterministic time with testing/synctest
The race detector article's Watchdog, fixed with atomic.Int64 and given a context so its goroutine ends. The test runs 37 seconds of fake time instantly. Our first version used a plain bool for fired, as the synctest blog does; go test -race reported a data race, because synctest.Wait orders the other goroutines' earlier writes before the caller's reads, but nothing ordered the test's first read before the watchdog's later write. The file starts with //go:build go1.25 because synctest.Test is a Go 1.25 API while the module stays on go 1.24.
// Package watchdog is the race detector article's Watchdog, fixed with
// sync/atomic and given a lifetime (context) so its goroutine cannot leak.
package watchdog
import (
"context"
"sync/atomic"
"time"
)
// Watchdog calls OnTimeout once if KeepAlive is not called for Timeout.
type Watchdog struct {
Timeout time.Duration
Every time.Duration
OnTimeout func()
last atomic.Int64 // unix nanos; written by KeepAlive, read by the loop
}
// KeepAlive may be called from any goroutine.
func (w *Watchdog) KeepAlive() { w.last.Store(time.Now().UnixNano()) }
// Run blocks until ctx is done or the timeout fires.
func (w *Watchdog) Run(ctx context.Context) {
w.KeepAlive()
t := time.NewTicker(w.Every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
if now.UnixNano()-w.last.Load() > int64(w.Timeout) {
w.OnTimeout()
return
}
}
}
}//go:build go1.25
// testing/synctest is generally available from Go 1.25 (an experiment in
// 1.24). This file opts into 1.25 while the module stays on go 1.24.
package watchdog
import (
"context"
"sync/atomic"
"testing"
"testing/synctest"
"time"
)
func TestWatchdogFiresAfterSilence(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
// A plain bool races here: Wait orders the other goroutines' writes
// before our reads, but nothing orders our first read before the
// watchdog's later write. go test -race reported exactly that.
var fired atomic.Bool
w := &Watchdog{Timeout: 10 * time.Second, Every: time.Second, OnTimeout: func() { fired.Store(true) }}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
go w.Run(ctx)
for range 5 { // 25 fake seconds of regular keepalives
time.Sleep(5 * time.Second)
w.KeepAlive()
}
synctest.Wait()
if fired.Load() {
t.Fatal("fired while keepalives were arriving")
}
time.Sleep(12 * time.Second) // silence: instant in fake time
synctest.Wait()
if !fired.Load() {
t.Fatal("did not fire after 12s of silence")
}
})
}
func TestWatchdogStopsOnCancel(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
w := &Watchdog{Timeout: time.Hour, Every: time.Second, OnTimeout: func() { t.Error("fired") }}
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() { w.Run(ctx); close(done) }()
time.Sleep(3 * time.Second)
cancel()
<-done // if Run leaked, synctest.Test would report a deadlock here
})
}Every deadlock message
// Command deadlockdemo reproduces each classic deadlock so you can read the
// runtime's message (or notice its silence):
//
// go run ./deadlockdemo chan // unbuffered send with no receiver
// go run ./deadlockdemo wg // Add(2) but only one Done
// go run ./deadlockdemo recursive // sync.Mutex locked twice by one goroutine
// go run ./deadlockdemo select // select {} with nothing else alive
// go run ./deadlockdemo lockorder // A->B vs B->A; a live timer hides it
// go run ./deadlockdemo hang // same, forever; inspect with kill -QUIT
package main
import (
"fmt"
"os"
"runtime/pprof"
"sync"
"time"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: deadlockdemo chan|wg|recursive|select|lockorder|hang")
os.Exit(2)
}
switch os.Args[1] {
case "chan":
ch := make(chan int)
ch <- 1 // nobody will ever receive
case "wg":
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done() }()
wg.Wait() // counter stays at 1 forever
case "recursive":
var mu sync.Mutex
mu.Lock()
helper := func() {
mu.Lock() // Go mutexes are not reentrant
defer mu.Unlock()
}
helper()
case "select":
select {}
case "lockorder":
lockOrder()
case "hang":
hang()
default:
fmt.Fprintln(os.Stderr, "unknown scenario")
os.Exit(2)
}
}
func lockOrder() {
var a, b sync.Mutex
ready := make(chan struct{}, 2)
go func() {
a.Lock()
ready <- struct{}{}
time.Sleep(10 * time.Millisecond)
b.Lock() // waits for the other goroutine forever
}()
go func() {
b.Lock()
ready <- struct{}{}
time.Sleep(10 * time.Millisecond)
a.Lock()
}()
<-ready
<-ready
// The pending timer below keeps the runtime's checkdead from firing,
// exactly as a listening HTTP server or a ticker would in production.
<-time.After(500 * time.Millisecond)
fmt.Fprintln(os.Stderr, "watchdog: still blocked after 500ms; goroutine dump follows")
_ = pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
// Go 1.27+: the goroutineleak profile names goroutines blocked on
// primitives no runnable goroutine can reach. Lookup returns nil on
// older toolchains, so the program still builds and runs there.
if leak := pprof.Lookup("goroutineleak"); leak != nil {
_ = leak.WriteTo(os.Stderr, 1)
}
os.Exit(3)
}
// hang is the production shape: the deadlocked pair plus a ticker that keeps
// the runtime from ever declaring a deadlock. Only a dump reveals it.
func hang() {
var a, b sync.Mutex
go func() { a.Lock(); time.Sleep(10 * time.Millisecond); b.Lock() }()
go func() { b.Lock(); time.Sleep(10 * time.Millisecond); a.Lock() }()
t := time.NewTicker(time.Hour)
defer t.Stop()
fmt.Fprintf(os.Stderr, "pid %d: send SIGQUIT (kill -QUIT) for a goroutine dump\n", os.Getpid())
for range t.C {
}
}Testing concurrent code
A concurrency test is only useful if it fails when the code is wrong. Timing-based tests ("sleep 10 ms, then assert") are, in the synctest blog's words, slow or flaky, and "we can't make it both fast and reliable." The techniques, from cheapest to strongest:
| Technique | Command / code | Finds | Note |
|---|---|---|---|
| Race detector on all tests | go test -race ./... | Data races on executed paths | Run in CI on every change |
| Repetition | go test -race -count=50 -run TestX ./pkg | Rare interleavings | -count also disables the test cache |
| Different parallelism | go test -race -cpu=1,2,8 | Bugs that need (or hide under) parallelism | Sets GOMAXPROCS per run |
| Stress loops | for range 200 { ... 16 goroutines ... } in one test | Invariant violations (TestBookExactlyOnce) | Assert the invariant, not timing |
| Forced interleaving | Barrier/hook between check and act | Race conditions deterministically | TestCheckThenActDoubleSells |
| Timeouts with dumps | dump.Within(d, f) or go test -timeout 30s | Deadlocks, leaks | The dump is the diagnosis |
| Fuzzing | go test -fuzz=FuzzSharded ./counter | Inputs that break invariants (worker counts, sizes) | Seeds run in normal go test |
testing/synctest | synctest.Test(t, func(t *testing.T) { ... }) | Time-dependent logic, "all blocked" deadlocks | Go 1.25+; mutex and I/O waits are not "durably blocking" |
| Lock-order checking | Swap sync.Mutex for deadlock.Mutex in test builds | A→B / B→A even when it did not hang | Third-party (sasha-s/go-deadlock); mutexes only |
| Leak checks | goleak.VerifyNone(t), goroutineleak profile | Goroutines left running | Third-party / Go 1.27 |
Canary under -race | One -race instance in production | Races only real traffic triggers | 2–20× CPU on that instance |
testing/synctest rules worth memorising, from its package doc: inside a bubble "the time package uses a fake clock" starting at midnight UTC 2000-01-01; time advances only "when every goroutine in the bubble is durably blocked"; durably blocking operations are channel operations on bubble channels, select over bubble channels, sync.Cond.Wait, sync.WaitGroup.Wait (when Add ran in the bubble) and time.Sleep; "locking a sync.Mutex or sync.RWMutex", I/O and system calls are not. If everyone is durably blocked and no timer can fire, "there is a deadlock and Test panics" — a deterministic deadlock detector for tests. Go 1.27 added synctest.Sleep (sleep plus Wait) and an in-memory fake-network httptest server for bubbles.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Counter or gauge, one word | atomic.Int64 | Shard per CPU if very hot | Cheapest correct option |
| Several fields with an invariant | sync.Mutex in the struct | xxxLocked helpers | One lock = one invariant |
| Read-mostly config, reloaded | atomic.Pointer[T] snapshot | Copy on write | Lock-free reads |
| Map shared by handlers | Mutex + map behind methods | sync.Map only for its two documented cases | Simple and correct |
| Work with a lifecycle (connection, session) | Owner goroutine + channels | ctx.Done() case | Ownership makes races impossible |
| Parallel computation | Confinement, merge after Wait | errgroup | No sharing |
| Two or more locks | Global order | go-deadlock in tests | Prevents cycles |
| Check-then-act on shared state | One critical section / CAS | DB constraint across processes | Atomic decision |
| Production hang | /debug/pprof/goroutine?debug=2, group by wait reason | goroutineleak, SIGQUIT if restarting anyway | Evidence before restart |
| Flaky time-based test | testing/synctest | Inject clocks elsewhere | Deterministic |
| Every PR | go test -race ./... | -count, -cpu for concurrency packages | Catches executed races |
| Before release | Load test with -race binary | One -race canary | Exercises real paths |
For PHP/Laravel developers
Classic PHP under PHP-FPM ("FastCGI Process Manager") is shared-nothing: each request runs in a worker process with its own memory, and nothing survives the request. That is why a PHP developer rarely meets a data race: two requests never touch the same PHP variable. Go servers are the opposite: one process, thousands of goroutines, one heap. A package-level map in Go is shared by every request at once, which is what a static property would be if PHP ran all requests in one process.
Shared-nothing removes memory races, not race conditions. Two FPM workers can still read the same row, both decide the seat is free, and both write: the race simply moved into the database or the cache. Laravel's answer is the same as Go's at that level: an atomic primitive outside the process. The Laravel cache docs: "Atomic locks allow for the manipulation of distributed locks without worrying about race conditions." Laravel Octane changes the PHP model toward Go's: it "boots your application once and keeps it in memory while serving requests", so static state persists across requests, and the docs warn about leaks via "a statically maintained array".
| PHP / Laravel | Go | Note |
|---|---|---|
| FPM worker per request, no shared memory | Goroutine per request, shared heap | Go needs sync; PHP needs it only under Octane/Swoole |
| Static property / singleton per request | Package variable shared by all requests | Package vars are global across goroutines |
Cache::lock('seat:12A', 10)->get(...) | sync.Mutex in-process; Redis/DB lock across processes | Same race condition, different scope |
DB::transaction + lockForUpdate() | tx.QueryRow("... FOR UPDATE") | Database owns cross-process races (Locks & Concurrency Control) |
| Unique index violation as "already booked" | Same | The most reliable check-then-act fix |
| Queue job runs twice | Goroutine/consumer redelivery | Idempotency is the fix in both (Idempotent Consumers) |
| No deadlocks in PHP code itself (single thread) | Mutex/channel deadlocks possible | Both can deadlock in the database (40P01, 1213) |
<?php
// Laravel: no memory race (each request has its own memory), but a race condition
// between two requests on the same seat. Fixed with an atomic cache lock.
use Illuminate\Support\Facades\Cache;
function book(string $seat, int $userId): bool
{
return Cache::lock("seat:{$seat}", 10)->get(function () use ($seat, $userId) {
if (Booking::where('seat', $seat)->exists()) { // check ...
return false;
}
Booking::create(['seat' => $seat, 'user_id' => $userId]); // ... act, under the lock
return true;
}) ?? false;
}In Go the in-process equivalent is booking.Book; across several Go processes you would use the same database constraint or a distributed lock (Distributed Locking).
In architecture: from a single process to a distributed system
The same three bugs (unordered access, check-then-act, circular wait) reappear at every scale; only the primitive that fixes them changes. A goroutine's mutex protects memory in one process. Once two processes share a row, a cache key or a queue, sync.Mutex protects nothing, and the race detector sees nothing.
Monolith: one process, one database
All memory races live here and all of them are found by -race in tests, if tests exercise them. Rules: every package-level variable is either immutable after init, guarded by a mutex in the same file, or atomic; every goroutine has an owner and a stop signal; lock order is documented. Business race conditions still exist between requests and are fixed in the database, because the database is the only shared thing that survives a second instance. The seat example as a constraint, which makes double booking impossible regardless of Go code:
-- The invariant "one owner per seat" enforced where every process meets.
CREATE TABLE seat_bookings (
event_id bigint NOT NULL,
seat text NOT NULL,
user_id bigint NOT NULL,
hold_id uuid NOT NULL UNIQUE, -- idempotency for double clicks / retries
booked_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (event_id, seat) -- second INSERT fails: SQLSTATE 23505
);
-- Check-then-act as one statement: claim a hold only if it is still valid.
UPDATE seat_holds
SET status = 'confirming'
WHERE id = $1 AND status = 'held' AND expires_at > now()
RETURNING seat, user_id; -- 0 rows = expired or already claimed
-- Diagnosing a "hang" that is really lock waits inside PostgreSQL:
SELECT pid, state, wait_event_type, wait_event, now() - query_start AS waiting, left(query, 60)
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';Modular monolith and multiple databases
Module boundaries are also lock boundaries. A module that exposes a type with an internal mutex must never call back into another module while holding it (recursive and cross-module lock cycles start exactly there), and must not return references to its guarded maps. Each module owns its goroutines and stops them in its own Shutdown. With one database per module, a check in module A and an act in module B are two transactions: the race condition is now between databases, solved with a state machine and an outbox rather than a lock (Saga Pattern).
Microservices
Memory races stay inside each service; between services you get distributed race conditions. Example flow: the cart service calls POST /holds on inventory, then POST /charges on payments, then POST /holds/{id}/confirm. A client retry after a timeout repeats the charge unless the payment API is idempotent (API Idempotency); two cart instances confirming the same hold need the conditional UPDATE above in inventory's database. Deadlocks become distributed waits: service A calls B synchronously while B calls A for enrichment, and with bounded worker pools on both sides each waits for a worker the other holds. The Go-level symptom is goroutines in [IO wait] or blocked in net/http dials; the cure is deadlines on every call (context.WithTimeout), no synchronous call cycles, and bounded concurrency per dependency.
Distributed data: replicas, caches, queues and multi-region
A read replica turns check-then-act into "check on stale data, act on the primary": a seat that looks free on a lagging replica is not. Caches give the stampede race (every instance misses at once); golang.org/x/sync/singleflight collapses it inside one process, a short lock in Redis across processes. Queues give at-least-once delivery, so two consumers can process the same message concurrently after a redelivery: the inbox table with a unique message ID is the cross-process sync.Once (Idempotent Consumers & the Inbox Pattern). Distributed locks need fencing tokens because a paused process (GC, network) may still believe it holds an expired lease (Distributed Locking). Time-based checks across machines (TOCTOU with time.Now) are worse than in one process: clocks differ, so expiry decisions belong to one authority (the database's now()).
Scaling path: 1×, 10×, 100×
At 1× a mutex around each shared structure and go test -race in CI are enough; production hangs are diagnosed with /debug/pprof/goroutine?debug=2. At 10× contention appears in mutex and block profiles: shard hot maps and counters (Write Buffering & Sharded Counters), move read-mostly config to atomic.Pointer snapshots, scrape go_goroutines and alert on growth, run one -race canary, set GOMAXPROCS correctly for container limits. At 100× in-process locks are no longer the bottleneck worth optimising; the race conditions that matter are between instances (hot rows, hot keys, retries in lockstep): partition ownership so each key has one owner (the distributed form of channel ownership), use conditional writes instead of locks, add jitter to every retry, and capture goroutineleak and goroutine profiles automatically when latency SLOs burn.
Lab
All commands run from docs/snippets/go/race-conditions-deadlocks. Steps 1–8 were run on the host (Go 1.27.4, darwin/arm64, 12 CPUs, binaries built with -trimpath so no local paths appear); the output below is real, trimmed where marked. Step 9 needs a running HTTP service and is expected, not run.
1. Every test under the race detector.
go vet ./... && go test -race -count=1 ./...ok academy/race-conditions-deadlocks/after 1.988s
ok academy/race-conditions-deadlocks/before 1.956s
ok academy/race-conditions-deadlocks/booking 1.976s
ok academy/race-conditions-deadlocks/counter 2.020s
? academy/race-conditions-deadlocks/deadlockdemo [no test files]
ok academy/race-conditions-deadlocks/dump 2.019s
ok academy/race-conditions-deadlocks/httpbody 2.349s
ok academy/race-conditions-deadlocks/lockorder 2.242s
ok academy/race-conditions-deadlocks/loopvar 1.989s
? academy/race-conditions-deadlocks/racedemo [no test files]
ok academy/race-conditions-deadlocks/watchdog 1.989sNote that before passes: its test is sequential. booking passes too: its bugs are race conditions, not data races.
2. A silent bug, then a report.
go run ./racedemo counter # three runs
go run -race ./racedemo counter; echo "exit $?"want 1000, got 974
want 1000, got 962
want 1000, got 966
==================
WARNING: DATA RACE
Read at 0x00c000012148 by goroutine 12:
main.counter.func1()
academy/race-conditions-deadlocks/racedemo/main.go:44 +0x68
Previous write at 0x00c000012148 by goroutine 8:
main.counter.func1()
academy/race-conditions-deadlocks/racedemo/main.go:44 +0x78
... (created-at stacks, second report trimmed)
want 1000, got 871
Found 2 data race(s)
exit 66GORACE="halt_on_error=1" stops after the first report (also exit 66).
3. GOMAXPROCS=1 hides the symptom, not the race.
for i in 1 2 3; do GOMAXPROCS=1 go run ./racedemo counter; done
GOMAXPROCS=1 go run -race ./racedemo counter 2>&1 | grep -E 'WARNING|Found|want'want 1000, got 1000
want 1000, got 1000
want 1000, got 1000
WARNING: DATA RACE
want 1000, got 1000
Found 1 data race(s)4. Maps crash the process; append loses elements; strings tear.
go run ./racedemo map; echo "exit $?"
go run -race ./racedemo append 2>&1 | grep -E 'growslice|want'
go run ./racedemo headerfatal error: concurrent map writes
goroutine 20 [running]:
internal/runtime/maps.fatal({0x1000e7c7b?, 0x0?})
runtime/panic.go:1197 +0x20
main.mapWrites.func1()
academy/race-conditions-deadlocks/racedemo/main.go:60 +0x6c
created by main.mapWrites in goroutine 1
academy/race-conditions-deadlocks/racedemo/main.go:57 +0x50
exit 2
runtime.growslice()
want 100, got 94
torn reads observed: 164241The last line counts reads of s that were neither "short" nor the long string: pointer and length from different writes, exactly the multi-word corruption the memory model warns about.
5. Every deadlock message, and the one that stays silent.
for s in chan wg recursive select; do go run ./deadlockdemo $s; echo "exit $?"; done
go run ./deadlockdemo lockorder; echo "exit $?"fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
academy/race-conditions-deadlocks/deadlockdemo/main.go:28 +0x160
exit 2
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [sync.WaitGroup.Wait]:
... (runtime frames trimmed)
main.main()
academy/race-conditions-deadlocks/deadlockdemo/main.go:33 +0x10c
exit 2
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [sync.Mutex.Lock]:
... (runtime frames trimmed)
main.main.func2()
academy/race-conditions-deadlocks/deadlockdemo/main.go:38 +0x78
exit 2
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [select (no cases)]:
main.main()
academy/race-conditions-deadlocks/deadlockdemo/main.go:43 +0x2b8
exit 2
watchdog: still blocked after 500ms; goroutine dump follows
goroutine profile: total 3
# 0x1006a09c7 main.lockOrder+0x187 academy/race-conditions-deadlocks/deadlockdemo/main.go:75
# 0x1006a0e60 main.lockOrder.func2+0xa0 academy/race-conditions-deadlocks/deadlockdemo/main.go:67
# 0x1006a0f70 main.lockOrder.func1+0xa0 academy/race-conditions-deadlocks/deadlockdemo/main.go:61
goroutineleak profile: total 2
# 0x1006a0e60 main.lockOrder.func2+0xa0 academy/race-conditions-deadlocks/deadlockdemo/main.go:67
# 0x1006a0f70 main.lockOrder.func1+0xa0 academy/race-conditions-deadlocks/deadlockdemo/main.go:61
exit 3The lock-order deadlock produced no runtime message because of one pending timer; the Go 1.27 goroutineleak profile named exactly the two deadlocked goroutines (lines 61 and 67 are the second Lock calls).
6. SIGQUIT on a process that hangs forever.
go build -o /tmp/dd ./deadlockdemo && /tmp/dd hang &
kill -QUIT %1pid NNNN: send SIGQUIT (kill -QUIT) for a goroutine dump
SIGQUIT: quit
PC=0x19722450c m=0 sigcode=0
... (idle runtime goroutines trimmed)
goroutine 1 gp=0x4a8b56f81e0 m=nil [chan receive]:
... main.hang() (ticker loop)
goroutine 3 gp=0x4a8b56f90e0 m=nil [sync.Mutex.Lock]:
... (runtime frames trimmed)
sync.(*Mutex).Lock(...)
sync/mutex.go:46
main.hang.func1()
academy/race-conditions-deadlocks/deadlockdemo/main.go:89 +0xc8 fp=0x4a8b57577d0 sp=0x4a8b57577b0 pc=0x104cf91c8
created by main.hang in goroutine 1
academy/race-conditions-deadlocks/deadlockdemo/main.go:89 +0x80
goroutine 4 gp=0x4a8b56f92c0 m=nil [sync.Mutex.Lock]:
... main.hang.func2() at main.go:90
exit status 27. The cost of each fix, and of -race.
go test -run '^$' -bench . -count 3 ./counter
go test -race -run '^$' -bench . ./counterBenchmarkMutex-12 11076288 110.7 ns/op
BenchmarkAtomic-12 39394869 56.62 ns/op
BenchmarkOwner-12 2817259 421.2 ns/op
---- with -race ----
BenchmarkMutex-12 3093732 377.6 ns/op
BenchmarkAtomic-12 3677836 334.0 ns/op
BenchmarkOwner-12 1421410 863.2 ns/op(One representative line of three per benchmark.) The owner goroutine is about 4× the mutex per operation; it buys ownership, not speed.
8. Fuzzing the merge.
go test -run '^$' -fuzz=FuzzSharded -fuzztime=5s ./counterfuzz: elapsed: 3s, execs: 2086846 (695597/sec), new interesting: 5 (total: 7)
fuzz: elapsed: 5s, execs: 3457303 (652335/sec), new interesting: 5 (total: 7)
PASS
ok academy/race-conditions-deadlocks/counter 5.648s9. A goroutine dump from a running service (expected, not run). In a service that imports net/http/pprof on an internal listener (localhost:6060):
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=1' | head -20 # grouped counts
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=2' > goroutines.txt # full stacks
grep -o '\[[a-zA-Z. ()]*\(, [0-9]* minutes\)\?\]' goroutines.txt | sort | uniq -c | sort -rn
curl -s 'http://localhost:6060/debug/pprof/goroutineleak?debug=1' | head # Go 1.27+# expected shape for the httpbody bug under load
412 [select]
398 [IO wait]
250 [select, 3 minutes] <- requests waiting for a connection inside net/http
2 [sync.Mutex.Lock, 14 minutes]
1 [chan receive]Common misconceptions
| Belief | Reality |
|---|---|
A race on an int is harmless | The compiler may hoist the read; "the loop in main is not guaranteed to finish" |
| Races on strings or slices just give old values | Multi-word races "can lead to arbitrary memory corruption"; the lab tore 164,241 string reads |
go test -race passing means race-free | Only executed paths are checked |
| The race detector has false positives | "It will not issue false positives" for code using Go's primitives |
| Every access locked means no race conditions | Check-then-act across two critical sections still double-books |
GOMAXPROCS=1 prevents races | Preemption interleaves goroutines; -race still reports |
| The runtime detects deadlocks | Only when every goroutine is blocked and no timer or poller is active |
sync.Mutex is reentrant | Locking twice from one goroutine deadlocks; mutexes are not owned by goroutines |
| Concurrent map reads with rare writes are fine | Any write concurrent with any access is a race; often fatal error |
A fatal error can be recovered | Not a panic; no defers run |
wg.Add(1) inside the goroutine is fine | Wait can see zero and return early |
| Channels are always better than mutexes | Effective Go: a mutex around a counter is often best; use channels for ownership and coordination |
default in select prevents deadlocks | It turns a wait into a busy loop |
| Only the status code matters, skip the body | Unclosed bodies exhaust the connection pool |
| The GC frees blocked goroutines | It never terminates goroutines; Go 1.27 only reports them |
| A timeout fixes a deadlock | It reports one; the stuck goroutines stay stuck |
| Loop variable capture is fixed everywhere | Only in modules or files on Go 1.22+ |
| Double-checked locking with a bool is fast and safe | The memory model's own counter-example |
Cheat sheet
| Topic | Remember |
|---|---|
| Data race | Two accesses, one write, no happens-before; a bug, not a style issue |
| Race condition | Order-dependent outcome; may have zero data races; fix the invariant |
| Memory model | Unlock→Lock, send→receive, close→receive, go→start, Done→Wait, Once, atomics |
| DRF-SC | No data races ⇒ sequentially consistent behaviour |
| Detector | go test -race ./... in CI; 5–10× memory, 2–20× time; exit 66; no false positives |
| GORACE | halt_on_error=1, log_path, history_size, exitcode, strip_path_prefix |
| Report | current access, previous access, two "created at" stacks; fix the data's ownership |
| Fixes | mutex (default), atomic (one word), owner goroutine, immutable snapshot, confinement, copy |
| Maps | not concurrent-safe for writes; fatal error: concurrent map writes |
| Lazy init | sync.OnceValue/OnceValues; never double-checked locking |
| Check-then-act | one critical section, CAS, conditional UPDATE, unique constraint |
| Loop vars | per-iteration since Go 1.22 (module/file version) |
| Deadlock messages | all goroutines are asleep - deadlock! only when everything is blocked |
| Lock order | global order by ID/hierarchy; no callbacks under a lock; no re-locking |
| WaitGroup | wg.Go (1.25+), or Add before go + defer Done; never copy |
| HTTP | defer resp.Body.Close(), drain bounded, ctx deadline or Client.Timeout |
| Dumps | kill -QUIT, /debug/pprof/goroutine?debug=2, goroutineleak (1.27), runtime.Stack |
| Testing | -race -count=N -cpu=1,2,8, forced interleavings, fuzzing, testing/synctest |
| Parallelism | GOMAXPROCS changes frequency of bugs, never their existence |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Two goroutines write cfg.Name and cfg.Port (different fields of one struct) without locks; a third reads both. Which pairs race? Important
Answer
Answer: The two writers do not race with each other: different fields are different memory locations. The reader races with each writer (write and read of the same field, unordered). The reader can also see a new Name with an old Port: an inconsistent snapshot even after the races are fixed per field. Guard the struct with one mutex or publish whole snapshots with atomic.Pointer. See Data race.
2 — go test -race ./... passes, yet production double-books seats. Name two reasons. Must-know
Answer
Answer: The detector only checks executed paths, and the tests may never run booking concurrently. More likely, the bug is a race condition with every access locked (check and act in separate critical sections), which is not a data race at all. Fix the invariant in one critical section or a database constraint. See Race condition vs data race.
3 — What do the four sections of a race report tell you, and where is the fix usually? Important
Answer
Answer: The current access (kind, address, goroutine, stack), the previous conflicting access, and where each goroutine was created. The fix is usually at the data: decide which goroutine owns it or which lock guards it, rather than patching one of the two lines. See Reading a race report.
4 — A service with an HTTP server hangs. Two goroutines are in [sync.Mutex.Lock, 40 minutes]. Why did Go not print "all goroutines are asleep"? Important
Answer
Answer: The runtime only reports a total deadlock. The HTTP listener is waiting on the network poller (and timers may be pending), so the runtime cannot prove nothing will ever happen. Partial deadlocks are silent; you find them in goroutine dumps or with the goroutineleak profile. See Mechanics.
5 — Why is if once == false { mu.Lock(); if !once { init(); once = true }; mu.Unlock() } wrong in Go? Must-know
Answer
Answer: The first read of once is unsynchronised and races with the write. Even if a goroutine observes once == true, the memory model gives no guarantee that it also observes the writes init made ("observing the write to done implies observing the write to a" is not guaranteed). Use sync.Once or sync.OnceValue. See Lazy initialization.
6 — Transfer(from, to) locks from then to. Give the deadlocking schedule and two fixes. Must-know
Answer
Answer: G1 runs Transfer(a,b) and locks a; G2 runs Transfer(b,a) and locks b; each waits for the other's lock forever. Fixes: always lock the lower ID first (global order), or use one lock for both accounts. In a database, use SELECT ... FOR UPDATE ordered by ID or rely on deadlock detection plus retry. See Lock ordering.
7 — A worker pool sometimes finishes "too early" and sometimes hangs at wg.Wait(). What two mistakes cause each? Must-know
Answer
Answer: Too early: wg.Add(1) inside the goroutine, so Wait can observe zero before any Add. Hang: a worker returns early or panics without Done (no defer), or the WaitGroup was passed by value so Done decremented a copy. Use wg.Go on Go 1.25+, or Add before go and defer wg.Done(). See WaitGroup misuse.
8 — An HTTP client starts timing out after a few hundred requests, while the upstream is healthy. What do you look for in the code and in a goroutine dump? Important
Answer
Answer: Response bodies that are not closed (for example, only resp.StatusCode is read), which keep connections checked out until MaxConnsPerHost or other limits block new dials. In the dump, many goroutines are waiting inside net/http transport code ([select] with long durations) and connections in [IO wait]. Fix with defer resp.Body.Close() and a bounded drain. See Body not closed.
9 — Does GOMAXPROCS=1 make n++ from 1000 goroutines safe? What did the lab show? Must-know
Answer
Answer: No. The scheduler can still switch goroutines between the load and the store (blocking points, asynchronous preemption), and the memory model has no single-core exception. The lab printed want 1000, got 1000 three times under GOMAXPROCS=1, and the -race build still reported WARNING: DATA RACE. See Concurrency vs parallelism.
10 — In a synctest.Test, a test reads a plain bool before calling time.Sleep and the code under test writes it after the fake time advances. Why does -race complain even though the blog uses a plain bool? Good to know
Answer
Answer: synctest.Wait creates edges from the other goroutines' completed work to the caller's subsequent reads. Here the test's read came first and the other goroutine's write came later, with no edge from the read to the write: an unordered read-write pair. Use an atomic.Bool (or a channel) for values touched on both sides of a time advance. See Deterministic time with testing/synctest.
11 — Which of these are race-free: (a) workers write results[i] and main reads after wg.Wait(); (b) workers append to results under no lock; (c) workers send on a channel and one collector appends? Must-know
Answer
Answer: (a) and (c). In (a) each worker writes a distinct element and Done is synchronized before Wait returns; in (c) only the collector touches the slice. (b) races on the slice header and elements; the lab lost 6 of 100 elements. See Append races.
Glossary
| Term | Meaning |
|---|---|
| Data race | Two accesses to one memory location, at least one a write, not ordered by happens-before |
| Race condition | A bug where correctness depends on the relative timing of operations; may involve no data race |
| Undefined behaviour | Go limits it for single words but multi-word races can corrupt memory; such programs are incorrect |
| Torn read | Observing parts of a multi-word value from different writes |
| Memory model | Go's contract for when writes in one goroutine are visible to reads in another |
| Happens-before | Transitive closure of sequenced-before and synchronized-before |
| Synchronized before | Edge created by a synchronising operation (Unlock→Lock, send→receive, ...) |
| DRF-SC | Data-race-free programs behave sequentially consistently |
| Sequential consistency | Results explainable by one interleaving of all goroutines' operations |
| Race detector | -race instrumentation plus ThreadSanitizer runtime |
go test -race | Runs tests with the race detector; also go build/run/install -race |
| ThreadSanitizer (TSan) | The C/C++ race-detection runtime the Go detector is built on |
| Shadow word | TSan's record of a recent access to an 8-byte word |
| False positive | A report about a non-existent race; the Go detector does not produce them |
| GORACE | Environment variable with detector options |
| Race report | WARNING: DATA RACE block with access, previous write/read and goroutine created at stacks |
WARNING: DATA RACE | Header line of a race report |
| Previous write | The earlier conflicting access in a report |
| Goroutine created at | Stack of the go statement that started a goroutine in a report |
| Mutex | sync.Mutex: mutual exclusion lock; not reentrant, not owned by a goroutine |
| Channel ownership | One goroutine owns state; others communicate with it |
| Atomic | sync/atomic operations; sequentially consistent, synchronising |
| Immutability | Values never changed after publication; replaced as a whole |
| Confinement | Data accessible to one goroutine only (per-worker slots) |
| Copying | Giving a goroutine its own copy of data instead of a reference |
| Concurrent map writes | Runtime fatal error when map writes overlap |
| Loop variable capture | Pre-1.22 sharing of one loop variable by all iterations' closures |
| Lazy initialization | Building a value on first use; needs sync.Once |
sync.Once / OnceValue | Run a function once; completion synchronized before every Do/call returns |
| Double-checked locking | Unsynchronised fast-path check; incorrect in Go |
| Check-then-act | Compound operation whose condition can change before the action |
| TOCTOU | Time of check to time of use: a check that is stale by the time it is used |
| Append race | Concurrent append to one slice variable |
| Deadlock | Goroutines waiting for each other forever |
| All goroutines are asleep | The runtime's total-deadlock message |
| Partial deadlock | A deadlocked subset while other goroutines run; never reported by the runtime |
| Lock ordering | A global order of acquisition that prevents circular wait |
| Circular wait | The Coffman condition you can break in Go code |
| Recursive lock | A goroutine locking a mutex it already holds; deadlocks in Go |
| WaitGroup misuse | Add after Wait started, missing Done, copies, negative counter |
wg.Go | Go 1.25 method that adds, starts and marks done |
| Body not closed | resp.Body left open, keeping its connection busy |
| Connection pool exhaustion | All pooled connections checked out; new requests wait |
MaxConnsPerHost | http.Transport limit; "dials will block" when reached |
| Goroutine leak | A goroutine blocked forever |
goroutineleak profile | Go 1.27 profile of goroutines blocked on unreachable primitives |
| SIGQUIT | Signal that makes a Go program dump all goroutines and exit 2 |
| Goroutine dump | Every goroutine's stack and wait reason |
GOTRACEBACK | Controls traceback detail on fatal errors (single, all, system, crash) |
| pprof goroutine | The goroutine profile; debug=2 gives panic-style stacks |
runtime.Stack | Writes the current (or all) goroutine stacks into a buffer |
| Wait reason | Bracketed state in a dump: [chan receive], [sync.Mutex.Lock], ... |
go-deadlock | github.com/sasha-s/go-deadlock: drop-in mutexes that report lock-order violations and long waits |
| Livelock | Goroutines active but making no progress |
| Starvation | A waiter postponed indefinitely while others progress |
| Starvation mode | sync.Mutex mode after a waiter waits > 1 ms: direct hand-off |
| Concurrency vs parallelism | Structure of independent tasks vs simultaneous execution |
GOMAXPROCS | Max threads running Go code at once; GOMAXPROCS=1 removes parallelism, not races |
| Asynchronous preemption | Since Go 1.14, the scheduler can interrupt tight loops |
| Stress test | Many goroutines and iterations asserting an invariant |
-count | go test flag to repeat tests (and bypass the cache) |
-cpu | go test flag to run tests under several GOMAXPROCS values |
| Fuzzing | go test -fuzz: generated inputs against a property |
testing/synctest | Go 1.25 package: bubbles with fake time and durable-block detection |
| Bubble | synctest isolation scope for goroutines, channels and timers |
| Durably blocked | Blocked on something only the bubble can unblock |
| Shared-nothing | Model (PHP-FPM) where requests share no memory |
| FPM | PHP FastCGI Process Manager: one worker process per concurrent request |
| Database race | A race condition between transactions or processes, fixed with constraints, conditional updates or locks |
| Fencing token | Monotonic number that lets storage reject a stale lock holder |
References
- The Go Memory Model (Version of June 6, 2022): Advice, Informal Overview, Memory Model, Implementation Restrictions for Programs Containing Data Races, Synchronization, Incorrect synchronization, Incorrect compilation
- Data Race Detector (Usage, Report Format, Options, Typical Data Races, Requirements, Runtime Overhead); Introducing the Go Race Detector, Dmitry Vyukov and Andrew Gerrand, 26 June 2013
- ThreadSanitizer: Clang ThreadSanitizer documentation; ThreadSanitizer algorithm (google/sanitizers wiki)
- Effective Go (Concurrency: Share by communicating, Parallelization); Go FAQ (Why are map operations not defined to be atomic?, What operations are atomic?, Why doesn't my program run faster with more CPUs?, How can I control the number of CPUs?); Go Code Review Comments (Goroutine Lifetimes); Go specification (Go statements, Channel types, For statements)
- Rob Pike, Concurrency is not Parallelism (Waza, January 2012); Andrew Gerrand, Concurrency is not parallelism (16 January 2013); Go Concurrency Patterns: Pipelines and cancellation
- Fixing For Loops in Go 1.22, David Chase and Russ Cox, 19 September 2023; Testing concurrent code with testing/synctest, Damien Neil, 19 February 2025; Testing Time (and other asynchronicities), Damien Neil, 26 August 2025
- Release notes: Go 1.1, Go 1.6, Go 1.14, Go 1.19, Go 1.21, Go 1.22, Go 1.24, Go 1.25, Go 1.26, Go 1.27
- Standard library source (package docs; pkg.go.dev returned 403 to the fetcher, so the same doc comments were read from source and
go docwith Go 1.27.4): sync/mutex.go, sync/rwmutex.go, internal/sync/mutex.go, sync/waitgroup.go, sync/once.go, sync/oncefunc.go, sync/map.go, sync/atomic/doc.go, testing/synctest/synctest.go, runtime/pprof/pprof.go, runtime/mprof.go (Stack), runtime/extern.go (GOTRACEBACK, GOMAXPROCS, GORACE), runtime/proc.go (checkdead), runtime/chan.go, runtime/runtime2.go (wait reasons), internal/runtime/maps/map.go, os/signal/doc.go, net/http/client.go, net/http/transport.go, net/http/pprof/pprof.go; Diagnostics - github.com/sasha-s/go-deadlock (README read from raw Readme.md); go.uber.org/goleak
- PHP: FastCGI Process Manager (FPM); Laravel 13 Cache: Atomic Locks, Octane