Skip to content

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 forGo to
The whole topic in a few tablesEverything in one minute
Why Go lets you write races at allWhy it exists
Go 1.1 race detector to Go 1.27 leak profileWhere it comes from
What exactly a data race isData race
Torn reads, corrupted interfaces and slicesUndefined behaviour and torn reads
Timing bugs with no data raceRace condition vs data race
-race, ThreadSanitizer, cost, CIThe race detector
Reading WARNING: DATA RACEReading a race report
Mutex, channel ownership, atomics, immutability, confinement, copyingSix ways to fix a race
fatal error: concurrent map writesConcurrent map writes
Closures in loops before and after Go 1.22Loop variable capture
Lazy init, double-checked locking, sync.OnceLazy initialization
Check-then-act, TOCTOU, time.Now checksCheck-then-act and TOCTOU
append from goroutinesAppend races
Double close, send on closed, closing a conn in useClosing shared resources
all goroutines are asleep - deadlock!Channel deadlocks
A→B vs B→ALock ordering
Locking a sync.Mutex twiceRecursive locking
Add/Done/Wait mistakesWaitGroup misuse
select that can never proceedBlocking select
HTTP client hangsBody not closed
Goroutines blocked forever without a crashGoroutine leaks
Busy but no progress; one caller never servedLivelock and starvation
Pike's talk, GOMAXPROCS=1Concurrency vs parallelism
Happens-before, DRF-SC, what atomics promiseThe memory model
Bad code and the fixGo
Exact messages, detector and runtime internalsMechanics
Tested solutionsSolving the classic problems
Stress tests, -count, fuzzing, testing/synctestTesting concurrent code
Which tool for which symptomChoosing
PHP-FPM's shared-nothing model comparedFor PHP/Laravel developers
The same bugs across processes and servicesIn architecture
Run every failure yourselfLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The bug families. Every row is unpacked in the concept catalogue.

BugIn plain wordsTiny exampleWho finds it
Data raceTwo goroutines touch the same variable, one writes, nothing orders themgo func() { n++ }() twicego test -race (only on executed paths)
Race conditionThe result depends on who runs first, even if every access is lockedif Available(s) { Book(s) }Tests that force the interleaving; review
Deadlock (total)Every goroutine is blockedch <- 1 with no receiver in mainRuntime: fatal error: all goroutines are asleep - deadlock!
Deadlock (partial)Some goroutines wait for each other forever; the rest keep runningTransfer A→B and B→ANobody automatically; goroutine dump, go-deadlock
Goroutine leakA goroutine blocks forever on something nobody will ever signalEarly return leaves senders on an unbuffered channelgoroutineleak profile (Go 1.27), dumps, NumGoroutine metric
Pool exhaustionLooks like a deadlock; resources are checked out and never returnedresp.Body not closedDump shows goroutines waiting in net/http dials
LivelockEveryone is busy reacting to everyone else; nothing completesTwo retriers that back off and retry in lockstepCPU profile + no progress metric
StarvationWork flows, but one kind of request never gets the resourceA writer behind a stream of readersLatency percentiles, mutex/block profiles

The toolbox.

ToolWhat it tells youCostSince
go test -race, go build -raceData races that actually happened in this run, with both stacks5–10× memory, 2–20× timeGo 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 patternsCompile-timewaitgroup Go 1.25, renamed Go 1.27
fatal error: concurrent map writesBest-effort runtime check on mapsAlways on, nearly freeGo 1.6
kill -QUIT <pid> / Ctrl-\Every goroutine's stack and wait reason, then exit 2Kills the processGo 1.0
/debug/pprof/goroutine?debug=2Same dump, process keeps runningStops the world brieflynet/http/pprof
goroutineleak profileGoroutines blocked on primitives no runnable goroutine can reachGC-basedExperiment 1.26, GA 1.27
runtime.Stack(buf, true)Dump from inside the program (watchdog)Stops the worldGo 1.0
testing/synctestDeterministic tests with fake time and "everyone is blocked" detectionTest-onlyExperiment 1.24, GA 1.25
github.com/sasha-s/go-deadlockLock-order violations and long waits on mutexesWraps every lockThird-party

The fixes.

FixWhenExample
MutexDefault for shared state with invariants across fieldsmu.Lock(); m[k]++; mu.Unlock()
Channel ownershipOne goroutine owns the state; others send requestsadd <- 1, owner does n += d
AtomicOne word, no invariant with other fieldsvar hits atomic.Int64; hits.Add(1)
ImmutabilityReaders dominate; writers replace the whole valueatomic.Pointer[Config].Store(&newCfg)
ConfinementEach goroutine works on its own slot, merge after Waitresults[i] = f(i)
CopyingHand a goroutine its own copy instead of a shared referencego 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 locksMessage passing (channels)
State lives in one place; goroutines take turnsState 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 orderBugs: 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/atomicchan, 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 ​

  1. "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.
  2. "-race passed, 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 -race while selling one seat twice.
  3. "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.

text
     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 lost
n++ is three steps: load, add, storeData race: lost updategoroutine 1goroutine 2load n = 41load n = 41add: 42add: 42store n = 42store n = 42two increments, n moved by one;no edge orders the accesses: -race reports itWith a mutex: orderedgoroutine 1goroutine 2mu.Lock()load 41, addstore 42mu.Unlock()mu.Lock() waitsLock returnsload 42, addstore 43mu.Unlock()Unlock (n) synchronizes beforeLock (n+1) returns: happens-beforeevery access is ordered; result is exact;same picture for atomic.Int64.Add

Real 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 patternRace?Why
Two goroutines read the same variableNoNo write
One writes, one reads, no synchronisationYesUnordered write and read
Both use atomic.Int64 methodsNoAll accesses are atomic
One uses atomic.AddInt64(&n,1), the other reads n plainlyYes"unless all the accesses involved are atomic"
Writes to s[0] and s[1] of one sliceNoDifferent memory locations
Writes to m["a"] and m["b"] of one mapYesA map is one data structure; inserts touch shared buckets and counters
Write before go f(), read inside fNoThe go statement is synchronized before f starts
Write inside a goroutine, read after wg.Wait()NoDone 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."

text
     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 valueWhat can go wrongLab or source
int64 on 64-bit, bool, pointerStale or never-visible value; loop hoistedMemory model, Incorrect synchronization
stringPointer from one write, length from anotherLab: 164,241 torn reads in 1,000,000 writes
[]TLength larger than the backing array: out-of-bounds or wild memoryMemory model, multi-word data
interface / errorType word and data word mismatch: wrong method calledMemory model, (pointer, type) pairs
mapRuntime crash (concurrent map writes) or corrupted bucketsGo 1.6 map check
structFields 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.

text
     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 report

Real 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 raceRace condition
LevelMemory accessesBusiness operations
Detected by -raceYes, when executedNo
Possible with every access lockedNoYes
Possible across processes/DBNo (separate memory)Yes, the common case
FixSynchronise the accessesMake 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.

text
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.

SituationWhat -race does
Race on a path the run executesReports it, every time the unordered pair is observed (history permitting)
Race on a path never executedNothing
Race condition with locked accessesNothing (not a data race)
DeadlockNothing special (no race)
Synchronisation through sync, channels, sync/atomic, testing/synctest.WaitUnderstood: no report
Synchronisation through unsafe tricks, external C code without annotationsMay 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:

text
==================
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 66

Real 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 lineMeaningTypical action
Read at / Write atKind of the access that completed the pairLocate the variable
Previous write at / Previous read atThe conflicting access recorded earlierSame variable, other code path
by goroutine NGoroutine ids, matching the "created at" sectionsMap to your goroutines
(running) / (finished)State of that goroutine at report timeFinished goroutines still count
created at:Stack of the go statementDecide who should own the data
Found N data race(s)Count at exitFix all, then rerun
testing.go: race detected during execution of testTest 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:

FixMechanismHappens-before edgeBenchmark here (12 CPUs, contended)Limits
sync.MutexCritical sectionUnlock n before Lock n+1 returns≈ 111 ns/opContention, lock order, must not copy
sync/atomicSingle hardware read-modify-writeStore observed by Load≈ 57–63 ns/opOne word; no invariant across fields
Channel ownershipOwner goroutine serialises requestsSend before receive completes≈ 420 ns/opOwner is a bottleneck; must stop it
ImmutabilityBuild new value, publish pointeratomic.Pointer Store/LoadReads are one atomic loadWriters copy; old readers see old value
ConfinementEach goroutine owns its slot; merge after WaitDone before Wait returnsNo sharing at allNeeds a merge step
CopyingPass a value or slices.Clonego statementCopy costLarge values; deep copies
text
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 map

Real 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.

text
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 shutdown

Real 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.

OptionUse whenNote
map + sync.MutexDefaultSimple, invariants across map and other fields
map + sync.RWMutexMany readers, rare writers, critical sections not tinyRLock has its own overhead; measure
sync.MapKeys written once and read many times, or disjoint key sets per goroutineIts doc names exactly these two cases
Sharded maps (N maps, N locks)Very hot map, measured contentionMore code; see Write Buffering & Sharded Counters
Owner goroutineMap with lifecycle (registry)Requests through channels
Copy-on-write + atomic.PointerRead-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."

text
     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 value

Real 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.

Codego 1.21 modulego 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 raceCorrect
for _, v := range xs { fs = append(fs, func() { use(v) }) }All closures see last vEach sees its own
i := i shadow copy inside loopRequired idiomRedundant (harmless)
vet loopclosureReports go/defer at end of bodySilent (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.

text
     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 visible

Real 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.

ApproachCorrect?Note
if x == nil { x = build() }NoData race, possibly two builds
Double-checked locking with a plain flagNoMemory model counter-example
sync.Mutex around check and buildYesEvery call locks
sync.Once + package variableYesClassic
sync.OnceValue(build) / OnceValuesYesGo 1.21+, returns the value, re-panics
Package-level var x = build()YesRuns 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.

text
     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 -> ErrTaken

Real 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-actAtomic alternative
if !m[k] { m[k] = true } from goroutinesSame code inside one Lock/Unlock; or sync.Map.LoadOrStore
if n.Load() < limit { n.Add(1) }CompareAndSwap loop
os.Stat then os.Createos.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
SELECT free seat, then UPDATEUPDATE seats SET owner=$1 WHERE id=$2 AND owner IS NULL + check rows affected, or a unique constraint
Expiry check, then slow work, then commitClaim (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().

text
     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 lost

Real 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.

PatternSafe?Note
results = append(results, r) from many goroutinesNoHeader race
results[i] = r with results := make([]T, n)YesDistinct elements (confinement)
Each goroutine sends on a channel, one collector appendsYesChannel ownership
mu.Lock(); results = append(results, r); mu.Unlock()YesOrder is arbitrary
Two goroutines append to sub-slices sharing a backing arrayNoThey 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.

text
     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 cleanly

Real 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.

ResourceSafe close pattern
Channel with one senderSender closes when done (defer close(out))
Channel with many sendersWaitGroup + one closer goroutine; or never close, signal via context
"Stop" broadcastclose(done) guarded by sync.Once, or context.CancelFunc (idempotent)
net.Conn read loopClose the conn from the owner to unblock Read; treat net.ErrClosed as normal
*sql.DB, *http.ClientCreate 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.

text
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 2

Real 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.

CaseRuntime reports it?
main blocked, no other goroutinesYes, fatal error: all goroutines are asleep - deadlock!
All goroutines blocked on channels/locks/WaitGroupYes
Some goroutines blocked, one runnable or sleepingNo
A timer or ticker pending (time.After, time.NewTicker)No (lab step 5)
HTTP server listeningNo (network poller)
Goroutine blocked in a syscall or cgoNo
main returns while others are blockedNo: 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.

text
     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 cycle
Lock-ordering deadlock and the fixTransfer(a,b) || Transfer(b,a)goroutine 1[sync.Mutex.Lock]goroutine 2[sync.Mutex.Lock]lock Alock Bheld byheld bywaits forcycle in the wait-for graph = deadlockruntime is silent if anything else is alive;find it in a goroutine dump (SIGQUIT, pprof)Global order: lower ID firstgoroutine 1holds A, takes Bgoroutine 2holds nothinglock A (id 1)lock B (id 2)waits for Agoroutine 2 waits while holding nothing,so no cycle; goroutine 1 finishes, unlocks,and goroutine 2 proceeds

Real 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.

TechniqueHowLimit
Global orderSort by ID or a fixed hierarchy before lockingEvery code path must follow it
One coarser lockOne mutex for both objectsLess parallelism
Never call out while holding a lockCopy what you need, unlock, then call callbacksMust re-check state after re-locking
TryLock and back offRelease and retry on failureThe sync doc: use of TryLock "is often a sign of a deeper problem"; risks livelock
Detection in testsgo-deadlock records lock order and reports violationsMutexes only; extra cost
TimeoutsChannel-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).

text
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 it

Real 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.

PatternFix
Exported method calls exported methodSplit into exported (locks) and unexported lenLocked() (assumes held)
String()/Error() locksFormat a copy taken before locking, or do not lock in String
Callback under lockCollect callbacks, unlock, then call
Nested RLockTake 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.

text
     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.

MistakeSymptomFix
Add inside the goroutineWait returns earlyAdd before go, or wg.Go
Done not deferredHang on early return/panicdefer wg.Done() first line, or wg.Go
WaitGroup passed by valueHang (copy decremented)Pass *sync.WaitGroup; vet copylocks
More Done than Addpanic: sync: negative WaitGroup counterOne Add(1) per goroutine
Reuse while Wait runssync: WaitGroup is reused before previous Wait has returnedNew WaitGroup per batch
Need errors or cancellationWaitGroup has neithererrgroup.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.

text
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 := <-jobs

Real 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 shapeBehaviour
Cases onlyBlocks until one is ready
Cases + defaultNever 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).

text
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().

ResourceMust doSymptom if not
*http.Response.Bodydefer resp.Body.Close(); drain boundedPool exhaustion, fd leak
http.ClientSet Timeout or always use a ctx deadlineRequests that wait forever
*sql.Rowsdefer rows.Close(); check rows.Err()database/sql pool waits (WaitCount in DBStats)
*sql.Txdefer tx.Rollback()Connection pinned, locks held in the DB
Goroutine-per-request with no limitBound with a semaphoreMemory 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."

text
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 request

Real 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.

DetectorFindsMisses
runtime.NumGoroutine() metricGrowth over timeWhich goroutines
Goroutine dump (debug=2)All stacks with wait reason and minutes waitingWhether they can still be woken
goroutineleak profile (Go 1.27)Blocked on primitives unreachable from runnable goroutinesPrimitives reachable from globals or runnable goroutines
go.uber.org/goleak in testsGoroutines alive after a testLeaks not exercised by tests
testing/synctestGoroutines 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.

text
     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.

ProblemSymptomFix
LivelockHigh CPU, zero throughputLock order, jittered backoff, one coordinator
Starvation (locks)Tail latency on one pathShorter critical sections; Mutex starvation mode helps; fair queue
Starvation (scheduling)One class of jobs ages foreverAging, separate pools, weighted fair queues
Retry stormsMany clients retry togetherExponential 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.

Concurrency is structure; parallelism is executionGOMAXPROCS=1: concurrent, not parallelP0G1G2G3G1G2G3G1switch between load and storeone at a time,interleavedGOMAXPROCS=4: concurrent and parallelP0G1P1G2P2G3P3idle / othersame instant: G1, G2, G3 all touch nRace on n exists in BOTH rows:the memory model has no "single core" mode;preemption can split n++ anywhere.Lab: GOMAXPROCS=1 printed 1000/1000 three timesand -race still reported WARNING: DATA RACE.
text
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 exists

Real 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.

ConcurrencyParallelism
Is aboutStructure: independent tasksExecution: simultaneous tasks
Needs several coresNoYes
Go mechanismgoroutines, channels, selectGOMAXPROCS threads running goroutines
Speeds upI/O-bound latency, responsivenessCPU-bound throughput (if divisible)
Data races possibleYesYes (more frequent)
GOMAXPROCS=1Still concurrentNo 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):

OperationEdge
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)
TryLockSuccess = Lock; failure has "no synchronizing effect at all"
Oncecompletion 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)"
Happens-before edges the Go memory model gives youin goroutine A (write side)in goroutine B (read side)go f()f starts runningch <- v (send)v := <-ch completesclose(ch)receive returns zero, ok=falsemu.Unlock() (call n)mu.Lock() returns (call n+1)once.Do(f): f returnsany once.Do(f) returnswg.Done()wg.Wait() it unblocks returnsx.Store(1) (sync/atomic)x.Load() observes 1synchronized beforeNo edge: goroutine exit, time.Sleep, a plain bool flag, receive-to-send on a buffered channel.A write before the left box is visible after the right box; without a chain of edges it is a data race.
text
     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.

go
// 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]
}
go
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.

go
// 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
}
go
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 ​

MessageKindSource / causeRecoverable?
fatal error: all goroutines are asleep - deadlock!fatalruntime.checkdead: no goroutine can run, no timersNo, exit 2
fatal error: no goroutines (main called runtime.Goexit) - deadlock!fatalmain called runtime.Goexit and nothing is leftNo
fatal error: concurrent map writesfatalinternal/runtime/maps writing flag seen by another writerNo
fatal error: concurrent map read and map writefatalReader saw the writing flagNo
fatal error: concurrent map iteration and map writefatalrange over a map being writtenNo
fatal error: sync: unlock of unlocked mutexfatalUnlock without Lock (internal/sync)No
fatal error: sync: RUnlock of unlocked RWMutex / sync: Unlock of unlocked RWMutexfatalUnbalanced RWMutexNo
panic: sync: negative WaitGroup counterpanicMore Done than AddYes (but a bug)
panic: sync: WaitGroup is reused before previous Wait has returnedpanicAdd on a group still being waited onYes
panic: sync: WaitGroup misuse: Add called concurrently with WaitpanicSanity check in Add/WaitYes
panic: send on closed channelpanicSend after closeYes
panic: close of closed channel / panic: close of nil channelpanicDouble close / nilYes
WARNING: DATA RACEdetector-race build saw an unordered pairProcess continues unless halt_on_error=1; exit 66
testing.go:NNNN: race detected during execution of testtestRace during a testTest fails
panic: test timed out after 10m0stestgo test -timeout (default 10m) expired; prints all goroutinesNo
context deadline exceedederrorA blocked operation's context expiredYes: the diagnosis for an apparent hang
SIGQUIT: quitsignalkill -QUIT / Ctrl-\: dump all goroutines, exit 2No

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:

FactConsequence
Dynamic, happens-before basedNo 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 PCsFix the first report and rerun to see the next
Needs cgo, supported platformNot 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 -raceLong-lived goroutines with frequent defers grow memory under -race only

GORACE options ​

OptionDefaultUse
log_pathstderrWrite reports to log_path.pid (useful for a canary)
exitcode66Exit status after a detected race
strip_path_prefix""Shorter paths in reports
history_size1More history, fewer "failed to restore the stack"
halt_on_error01 = exit after the first race
atexit_sleep_ms1000Delay 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 ​

MethodOutputProcessWhen
kill -QUIT <pid> / Ctrl-\SIGQUIT: quit, then every goroutine (GOTRACEBACK=all behaviour), exit 2DiesHung process you will restart anyway
GOTRACEBACK=all / system / crashControls detail of fatal dumps; crash raises SIGABRT for a core dumpDiesSet in the service env so a fatal error shows all goroutines
/debug/pprof/goroutine?debug=2Same format as a panic dump, "in the same form that a Go program uses when dying due to an unrecovered panic"Keeps runningProduction diagnosis (import net/http/pprof on an internal port)
/debug/pprof/goroutine?debug=1Goroutines grouped by identical stack with countsKeeps running"500 goroutines in the same place"
/debug/pprof/goroutineleakLeaked goroutines only (Go 1.27)Keeps runningLeak hunting
pprof.Lookup("goroutine").WriteTo(w, 2)Same as debug=2Keeps runningWatchdogs, test helpers
runtime.Stack(buf, true)"If all is true, Stack formats stack traces of all other goroutines into buf"; stops the worldKeeps runningWatchdog in dump.Within
go test -timeout expirypanic: test timed out + all goroutinesTest binary diesHanging 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 reasonMeans
[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 ​

ProblemSolutionHowAdvantageCost / limitation
Shared counter loses updatesMutex or atomiccounter.Mutex, counter.AtomicExactContention at high core counts
Shared state with a lifecycleOwner goroutinecounter.OwnerNo locks in callersSlower per op; must Close
Parallel work with resultsConfinementresults[i], merge after WaitNo sharingNeeds known n
Read-mostly configImmutable snapshotatomic.Pointer[Config]Lock-free readsWriters copy
Map crash under loadMutex-wrapped mapafter.TrackerSimpleOne lock
Lazy singletonsync.OnceValuestopPaths()Exactly once, visibleNo retry on failure
Double bookingOne critical section / DB constraintbooking.BookInvariant holdsLock or constraint scope
Double charge on retryClaim state transitionbooking.ConfirmIdempotentState machine to maintain
Two locks, two ordersGlobal lock orderlockorder.TransferCycle impossibleDiscipline everywhere
Silent hangTimeout + goroutine dumpdump.WithinEvidence in logsDoes not unblock
HTTP client stallsClose + drain body, ctx deadlinehttpbody.StatusConnections reused—
Time-based tests are slow/flakytesting/synctestwatchdog testInstant, deterministicGo 1.25+; no real I/O
Old loop semanticsUpgrade module to go 1.22+loopvarPer-iteration varsCheck 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.

go
// 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() }
go
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.

go
// 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.

go
// 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
}
go
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.

go
// 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())
	}
}
go
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.

go
// 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
}
go
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.

go
// 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
}
go
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.

go
// 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
//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
}
go
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.

go
// 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
//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 ​

go
// 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:

TechniqueCommand / codeFindsNote
Race detector on all testsgo test -race ./...Data races on executed pathsRun in CI on every change
Repetitiongo test -race -count=50 -run TestX ./pkgRare interleavings-count also disables the test cache
Different parallelismgo test -race -cpu=1,2,8Bugs that need (or hide under) parallelismSets GOMAXPROCS per run
Stress loopsfor range 200 { ... 16 goroutines ... } in one testInvariant violations (TestBookExactlyOnce)Assert the invariant, not timing
Forced interleavingBarrier/hook between check and actRace conditions deterministicallyTestCheckThenActDoubleSells
Timeouts with dumpsdump.Within(d, f) or go test -timeout 30sDeadlocks, leaksThe dump is the diagnosis
Fuzzinggo test -fuzz=FuzzSharded ./counterInputs that break invariants (worker counts, sizes)Seeds run in normal go test
testing/synctestsynctest.Test(t, func(t *testing.T) { ... })Time-dependent logic, "all blocked" deadlocksGo 1.25+; mutex and I/O waits are not "durably blocking"
Lock-order checkingSwap sync.Mutex for deadlock.Mutex in test buildsA→B / B→A even when it did not hangThird-party (sasha-s/go-deadlock); mutexes only
Leak checksgoleak.VerifyNone(t), goroutineleak profileGoroutines left runningThird-party / Go 1.27
Canary under -raceOne -race instance in productionRaces only real traffic triggers2–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 ​

Something is stuck: from symptom to causerequests hang / job never endsprocess died: "fatal error: all goroutinesare asleep - deadlock!" (exit 2)read the stacks it printedprocess alive, no progress: take a dumpkill -QUIT, /debug/pprof/goroutine?debug=2,goroutineleak profile (Go 1.27)group goroutines by [wait reason][sync.Mutex.Lock]lock order, missing Unlock, re-lock[chan send] / [chan receive]no partner, nobody closes, nil channel[sync.WaitGroup.Wait]Add without Done (early return, panic)[select]no case can fire; no ctx.Done case[IO wait] / dial in net/httppool exhausted: Body not closedall [running], CPU highlivelock: retry loops without backoffOne kind of work never served while others flow: starvation (fairness, priorities, a hot lock held too long)
SituationRecommendationExtra techniqueReason
Counter or gauge, one wordatomic.Int64Shard per CPU if very hotCheapest correct option
Several fields with an invariantsync.Mutex in the structxxxLocked helpersOne lock = one invariant
Read-mostly config, reloadedatomic.Pointer[T] snapshotCopy on writeLock-free reads
Map shared by handlersMutex + map behind methodssync.Map only for its two documented casesSimple and correct
Work with a lifecycle (connection, session)Owner goroutine + channelsctx.Done() caseOwnership makes races impossible
Parallel computationConfinement, merge after WaiterrgroupNo sharing
Two or more locksGlobal ordergo-deadlock in testsPrevents cycles
Check-then-act on shared stateOne critical section / CASDB constraint across processesAtomic decision
Production hang/debug/pprof/goroutine?debug=2, group by wait reasongoroutineleak, SIGQUIT if restarting anywayEvidence before restart
Flaky time-based testtesting/synctestInject clocks elsewhereDeterministic
Every PRgo test -race ./...-count, -cpu for concurrency packagesCatches executed races
Before releaseLoad test with -race binaryOne -race canaryExercises 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 / LaravelGoNote
FPM worker per request, no shared memoryGoroutine per request, shared heapGo needs sync; PHP needs it only under Octane/Swoole
Static property / singleton per requestPackage variable shared by all requestsPackage vars are global across goroutines
Cache::lock('seat:12A', 10)->get(...)sync.Mutex in-process; Redis/DB lock across processesSame 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"SameThe most reliable check-then-act fix
Queue job runs twiceGoroutine/consumer redeliveryIdempotency is the fix in both (Idempotent Consumers)
No deadlocks in PHP code itself (single thread)Mutex/channel deadlocks possibleBoth can deadlock in the database (40P01, 1213)
php
<?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:

sql
-- 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.

bash
go vet ./... && go test -race -count=1 ./...
text
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.989s

Note 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.

bash
go run ./racedemo counter            # three runs
go run -race ./racedemo counter; echo "exit $?"
text
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 66

GORACE="halt_on_error=1" stops after the first report (also exit 66).

3. GOMAXPROCS=1 hides the symptom, not the race.

bash
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'
text
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.

bash
go run ./racedemo map; echo "exit $?"
go run -race ./racedemo append 2>&1 | grep -E 'growslice|want'
go run ./racedemo header
text
fatal 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: 164241

The 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.

bash
for s in chan wg recursive select; do go run ./deadlockdemo $s; echo "exit $?"; done
go run ./deadlockdemo lockorder; echo "exit $?"
text
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 3

The 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.

bash
go build -o /tmp/dd ./deadlockdemo && /tmp/dd hang &
kill -QUIT %1
text
pid 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 2

7. The cost of each fix, and of -race.

bash
go test -run '^$' -bench . -count 3 ./counter
go test -race -run '^$' -bench . ./counter
text
BenchmarkMutex-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.

bash
go test -run '^$' -fuzz=FuzzSharded -fuzztime=5s ./counter
text
fuzz: 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.648s

9. A goroutine dump from a running service (expected, not run). In a service that imports net/http/pprof on an internal listener (localhost:6060):

bash
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+
text
# 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 ​

BeliefReality
A race on an int is harmlessThe compiler may hoist the read; "the loop in main is not guaranteed to finish"
Races on strings or slices just give old valuesMulti-word races "can lead to arbitrary memory corruption"; the lab tore 164,241 string reads
go test -race passing means race-freeOnly 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 conditionsCheck-then-act across two critical sections still double-books
GOMAXPROCS=1 prevents racesPreemption interleaves goroutines; -race still reports
The runtime detects deadlocksOnly when every goroutine is blocked and no timer or poller is active
sync.Mutex is reentrantLocking twice from one goroutine deadlocks; mutexes are not owned by goroutines
Concurrent map reads with rare writes are fineAny write concurrent with any access is a race; often fatal error
A fatal error can be recoveredNot a panic; no defers run
wg.Add(1) inside the goroutine is fineWait can see zero and return early
Channels are always better than mutexesEffective Go: a mutex around a counter is often best; use channels for ownership and coordination
default in select prevents deadlocksIt turns a wait into a busy loop
Only the status code matters, skip the bodyUnclosed bodies exhaust the connection pool
The GC frees blocked goroutinesIt never terminates goroutines; Go 1.27 only reports them
A timeout fixes a deadlockIt reports one; the stuck goroutines stay stuck
Loop variable capture is fixed everywhereOnly in modules or files on Go 1.22+
Double-checked locking with a bool is fast and safeThe memory model's own counter-example

Cheat sheet ​

TopicRemember
Data raceTwo accesses, one write, no happens-before; a bug, not a style issue
Race conditionOrder-dependent outcome; may have zero data races; fix the invariant
Memory modelUnlock→Lock, send→receive, close→receive, go→start, Done→Wait, Once, atomics
DRF-SCNo data races ⇒ sequentially consistent behaviour
Detectorgo test -race ./... in CI; 5–10× memory, 2–20× time; exit 66; no false positives
GORACEhalt_on_error=1, log_path, history_size, exitcode, strip_path_prefix
Reportcurrent access, previous access, two "created at" stacks; fix the data's ownership
Fixesmutex (default), atomic (one word), owner goroutine, immutable snapshot, confinement, copy
Mapsnot concurrent-safe for writes; fatal error: concurrent map writes
Lazy initsync.OnceValue/OnceValues; never double-checked locking
Check-then-actone critical section, CAS, conditional UPDATE, unique constraint
Loop varsper-iteration since Go 1.22 (module/file version)
Deadlock messagesall goroutines are asleep - deadlock! only when everything is blocked
Lock orderglobal order by ID/hierarchy; no callbacks under a lock; no re-locking
WaitGroupwg.Go (1.25+), or Add before go + defer Done; never copy
HTTPdefer resp.Body.Close(), drain bounded, ctx deadline or Client.Timeout
Dumpskill -QUIT, /debug/pprof/goroutine?debug=2, goroutineleak (1.27), runtime.Stack
Testing-race -count=N -cpu=1,2,8, forced interleavings, fuzzing, testing/synctest
ParallelismGOMAXPROCS changes frequency of bugs, never their existence

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Data raceTwo accesses to one memory location, at least one a write, not ordered by happens-before
Race conditionA bug where correctness depends on the relative timing of operations; may involve no data race
Undefined behaviourGo limits it for single words but multi-word races can corrupt memory; such programs are incorrect
Torn readObserving parts of a multi-word value from different writes
Memory modelGo's contract for when writes in one goroutine are visible to reads in another
Happens-beforeTransitive closure of sequenced-before and synchronized-before
Synchronized beforeEdge created by a synchronising operation (Unlock→Lock, send→receive, ...)
DRF-SCData-race-free programs behave sequentially consistently
Sequential consistencyResults explainable by one interleaving of all goroutines' operations
Race detector-race instrumentation plus ThreadSanitizer runtime
go test -raceRuns 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 wordTSan's record of a recent access to an 8-byte word
False positiveA report about a non-existent race; the Go detector does not produce them
GORACEEnvironment variable with detector options
Race reportWARNING: DATA RACE block with access, previous write/read and goroutine created at stacks
WARNING: DATA RACEHeader line of a race report
Previous writeThe earlier conflicting access in a report
Goroutine created atStack of the go statement that started a goroutine in a report
Mutexsync.Mutex: mutual exclusion lock; not reentrant, not owned by a goroutine
Channel ownershipOne goroutine owns state; others communicate with it
Atomicsync/atomic operations; sequentially consistent, synchronising
ImmutabilityValues never changed after publication; replaced as a whole
ConfinementData accessible to one goroutine only (per-worker slots)
CopyingGiving a goroutine its own copy of data instead of a reference
Concurrent map writesRuntime fatal error when map writes overlap
Loop variable capturePre-1.22 sharing of one loop variable by all iterations' closures
Lazy initializationBuilding a value on first use; needs sync.Once
sync.Once / OnceValueRun a function once; completion synchronized before every Do/call returns
Double-checked lockingUnsynchronised fast-path check; incorrect in Go
Check-then-actCompound operation whose condition can change before the action
TOCTOUTime of check to time of use: a check that is stale by the time it is used
Append raceConcurrent append to one slice variable
DeadlockGoroutines waiting for each other forever
All goroutines are asleepThe runtime's total-deadlock message
Partial deadlockA deadlocked subset while other goroutines run; never reported by the runtime
Lock orderingA global order of acquisition that prevents circular wait
Circular waitThe Coffman condition you can break in Go code
Recursive lockA goroutine locking a mutex it already holds; deadlocks in Go
WaitGroup misuseAdd after Wait started, missing Done, copies, negative counter
wg.GoGo 1.25 method that adds, starts and marks done
Body not closedresp.Body left open, keeping its connection busy
Connection pool exhaustionAll pooled connections checked out; new requests wait
MaxConnsPerHosthttp.Transport limit; "dials will block" when reached
Goroutine leakA goroutine blocked forever
goroutineleak profileGo 1.27 profile of goroutines blocked on unreachable primitives
SIGQUITSignal that makes a Go program dump all goroutines and exit 2
Goroutine dumpEvery goroutine's stack and wait reason
GOTRACEBACKControls traceback detail on fatal errors (single, all, system, crash)
pprof goroutineThe goroutine profile; debug=2 gives panic-style stacks
runtime.StackWrites the current (or all) goroutine stacks into a buffer
Wait reasonBracketed state in a dump: [chan receive], [sync.Mutex.Lock], ...
go-deadlockgithub.com/sasha-s/go-deadlock: drop-in mutexes that report lock-order violations and long waits
LivelockGoroutines active but making no progress
StarvationA waiter postponed indefinitely while others progress
Starvation modesync.Mutex mode after a waiter waits > 1 ms: direct hand-off
Concurrency vs parallelismStructure of independent tasks vs simultaneous execution
GOMAXPROCSMax threads running Go code at once; GOMAXPROCS=1 removes parallelism, not races
Asynchronous preemptionSince Go 1.14, the scheduler can interrupt tight loops
Stress testMany goroutines and iterations asserting an invariant
-countgo test flag to repeat tests (and bypass the cache)
-cpugo test flag to run tests under several GOMAXPROCS values
Fuzzinggo test -fuzz: generated inputs against a property
testing/synctestGo 1.25 package: bubbles with fake time and durable-block detection
Bubblesynctest isolation scope for goroutines, channels and timers
Durably blockedBlocked on something only the bubble can unblock
Shared-nothingModel (PHP-FPM) where requests share no memory
FPMPHP FastCGI Process Manager: one worker process per concurrent request
Database raceA race condition between transactions or processes, fixed with constraints, conditional updates or locks
Fencing tokenMonotonic number that lets storage reject a stale lock holder

References ​

Built by Morteza Negahi