/golang:go-race-and-memory-modelfrom golang
Guides what a data race actually is in Go and how to detect it — a data race (two goroutines touch the same memory concurrently, at least one writing, with no happens-before edge) is undefined behavior, not a stale read; happens-before comes only from channels, mutexes, Once, WaitGroup, and atomics, never from a plain shared variable or a time.Sleep; "it passed once" is not proof; the race detector (go test/build/run -race) has no false positives but only catches races that actually execute, so run it in CI; and testing/synctest (1.25) gives deterministic concurrency tests with a fake clock. Auto-invokes when writing or editing concurrent access to shared variables, maps, or slices, reviewing goroutines for safety, or on "is this a data race" / "why does this only fail sometimes" / "concurrent map writes" / "set up -race in CI" requests. Owns the race concept and -race; routes fixes to go-sync-primitives, go-channels-select, and go-context.
Ships in golang. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
"Programs that modify data being simultaneously accessed by multiple goroutines must serialize such access." — The Go Memory Model
"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
"It will not issue false positives, so take its warnings seriously." — Introducing the Go Race Detector
A data race is not a style problem or a "sometimes-stale value." It is undefined behavior: the Go memory model gives a program with a race no guarantees at all. This skill owns two things — what a data race is (the memory model: happens-before, why "it passed once" proves nothing) and how to catch it (go test -race, CI, testing/synctest). It does not own the fixes: the locking primitives are go-sync-primitives, the channel handoff is go-channels-select, and cancellation is go-context.
Every rule below is a hard fact of the memory model or the race detector's documented behavior, not a preference.
| Rule | The mechanic | Source |
|---|---|---|
| Serialize shared access | Concurrent access to shared data must go through a synchronization primitive | "Programs that modify data being simultaneously accessed by multiple goroutines must serialize such access" (Memory Model) |
| A data race is UB | A racy program is incorrect, not "eventually consistent" | "Programs with races are incorrect and can exhibit non-sequentially consistent executions" (Memory Model) |
| Definition of a data race | Concurrent read/write or write/write, at least one non-synchronizing, unordered by happens-before | "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" (Memory Model) |
| Happens-before is the only ordering | Two ops are ordered only if a synchronization edge connects them | "The happens before relation is defined as the transitive closure of the union of the sequenced before and synchronized before relations" (Memory Model) |
| Channels synchronize | A send is ordered before the corresponding receive completes | "A send on a channel is synchronized before the completion of the corresponding receive from that channel" (Memory Model) |
| Mutexes synchronize | Unlock n is ordered before Lock m returns | "call n of l.Unlock() is synchronized before call m of l.Lock() returns" (Memory Model) |
| Atomics synchronize | An observed atomic op is ordered before the observer | "if the effect of an atomic operation A is observed by atomic operation B, then A synchronizes before B" (sync/atomic) |
-race has no false positives | Every warning is a real race | "It will not issue false positives, so take its warnings seriously" (Race Detector) |
-race only finds executed races | It is a dynamic tool; coverage matters | "The race detector only finds races that happen at runtime, so it can't find races in code paths that are not executed" (Race Detector article) |
The spec's definition 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" (Memory Model). Three conditions, all required: same location, concurrent (unordered by happens-before, §3), and at least one write.
The dangerous misconception is that a race just gives a slightly stale read. It does not. A racy Go program is incorrect and the runtime owes it nothing: "Programs with races are incorrect and can exhibit non-sequentially consistent executions. In particular, note that a read r may observe the value written by any write w that executes concurrently with r. Even if this occurs, it does not imply that reads happening after r will observe writes that happened before w" (Memory Model). The implementation is even allowed to abort: "An implementation may always react to a data race by reporting the race and terminating the program" (Memory Model). Two goroutines racing on a map do exactly that — fatal error: concurrent map writes, an unrecoverable crash.
So the memory model's headline guidance is blunt — serialize, and stop being clever: "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" (Memory Model). The fix is never "reorder the reads" or "add a time.Sleep"; it is "put a synchronization edge between the accesses."
// WRONG — two goroutines write the same int with no synchronization; this is a data race,
// undefined behavior, NOT "an int that's occasionally a bit behind"
var n int
go func() { n++ }()
go func() { n++ }()
// RIGHT — an atomic makes both writes synchronizing; the accesses are now ordered
var n atomic.Int64
go func() { n.Add(1) }()
go func() { n.Add(1) }()
The detector confirms this exact n++ is a race — see §5 for the captured WARNING: DATA RACE.
Two memory accesses are "concurrent" unless a happens-before edge orders them: "The happens before relation is defined as the transitive closure of the union of the sequenced before and synchronized before relations" (Memory Model). Within one goroutine, program order gives you that ordering for free. Across goroutines, only a synchronization operation does. The complete list of edge-makers:
go-channels-select.sync.Mutex or sync.RWMutex variable l and n < m, call n of l.Unlock() is synchronized before call m of l.Lock() returns" (Memory Model).sync.Once — "The completion of a single call of f() from once.Do(f) is synchronized before the return of any call of once.Do(f)" (Memory Model).sync.WaitGroup — a Wait that returns is ordered after the Done calls that released it.What does not establish happens-before, no matter how it looks:
bool flag another goroutine wrote, or an int, is not synchronization — the read may never observe the write, or may observe a torn value.time.Sleep. Sleeping "long enough" for the other goroutine to finish creates no ordering edge; it only makes the race less likely to be observed, which is strictly worse than failing loudly.fmt.Println or any incidental call. Side effects are not synchronization.// WRONG — the writer sets a plain bool; the reader has no happens-before edge to it,
// so it may spin forever or read a half-written value. time.Sleep does not fix this.
var done bool
go func() { work(); done = true }()
for !done { // racy read of done
time.Sleep(time.Millisecond) // makes it "usually work" — not a synchronization edge
}
// RIGHT — a channel receive is synchronized-before the send that closed it
done := make(chan struct{})
go func() { work(); close(done) }()
<-done // happens-before edge: work() is visible after this returns
A data race is timing-dependent, so a racy program can pass tests thousands of times and corrupt memory on the run that matters. "Works on my machine" and "the test is green" are evidence of nothing about race-freedom — a different CPU count, scheduler decision, compiler version, or production load can reorder the accesses and expose the bug. The memory model says the racy program was incorrect the whole time; you simply hadn't observed the failure yet.
This is why the standard of proof for concurrent code is not "the test passed" but "the test passed under -race, with the concurrent paths actually exercised." A green test without -race tells you the happy interleaving works; it says nothing about the others. Treat any "why does this only fail sometimes / only in CI / only under load" report as a race until -race clears it.
-raceGo ships a dynamic race detector. Add -race to the build, test, or run command:
go test -race ./... # test packages with the detector on
go build -race ./... # build an instrumented binary
go run -race main.go # run a source file instrumented
Its two defining properties make it trustworthy but not a proof of absence:
WARNING: DATA RACE is always a real bug — never wave one away.Running the racy counter from §2 under -race produces (captured from go test -race, Go 1.26):
==================
WARNING: DATA RACE
Read at 0x00c00010e338 by goroutine 11:
raceverify.(*RacyCounter).Inc()
.../counter.go:14 +0x7e
Previous write at 0x00c00010e338 by goroutine 9:
raceverify.(*RacyCounter).Inc()
.../counter.go:14 +0x90
...
testing.go:1712: race detected during execution of test
--- FAIL: TestRacyCounter (0.00s)
Replacing the plain int with a sync.Mutex or an atomic.Int64 (the §2 fix) makes the same test pass -race clean — --- PASS: TestMutexCounter / --- PASS: TestAtomicCounter. The detector reports the exact file:line of both conflicting accesses, which is why it is the fastest way to localize a race.
-race Is a Test/CI Tool, Not a Production SettingInstrumentation is not free: "for a typical program, memory usage may increase by 5-10x and execution time by 2-20x" (Race Detector article); "race-enabled binaries can use ten times the CPU and memory, so it is impractical to enable the race detector all the time" (Race Detector). So the policy is:
go test -race ./... in CI as a required gate. It is the single highest-value concurrency check you can automate. Wiring it into the pipeline is owned by go-tooling-and-static-analysis.testing/synctest for Deterministic Concurrency Tests (Go 1.25)The reason concurrency tests are flaky is usually a real-time time.Sleep standing in for synchronization. testing/synctest removes the wall clock from the equation. It "provides support for testing concurrent code" (testing/synctest), graduated to stable in 1.25 — "This package was first available in Go 1.24 under GOEXPERIMENT=synctest ... The experiment has now graduated to general availability" (Go 1.25).
synctest.Test(t, f) runs f in an isolated bubble where "time is virtualized: time package functions operate on a fake clock and the clock moves forward instantaneously if all goroutines in the bubble are blocked" (Go 1.25). synctest.Wait() "blocks until every goroutine within the current bubble, other than the current goroutine, is durably blocked" (testing/synctest) — so you wait for a state, not a duration.
// RIGHT — a test that exercises a 1-hour timeout with NO real sleep and NO flake
func TestTimeout(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
done := make(chan struct{})
go func() { time.Sleep(time.Hour); close(done) }() // fake clock: instant
synctest.Wait() // wait until the goroutine is durably blocked in Sleep
<-done
})
}
This skill owns synctest only as the answer to flaky-sleep race tests; go-testing-advanced owns it as a general testing facility (alongside fuzzing and benchmarks). Use them together: synctest makes the interleaving deterministic, -race proves that interleaving is race-free.
Each is a way the code looks synchronized but is not. Depth and wrong/right code in references/common-mistakes.md:
map is not a race that returns garbage, it is a fatal error: concurrent map writes crash you cannot recover.time.Sleep as synchronization — sleeping to "let the goroutine finish" creates no happens-before edge (§3); it hides the race instead of fixing it.c.n++ from many goroutines is the canonical race (§2, §5).bool/int read is not atomic and not ordered; use atomic.Bool or a channel.-race prove nothing (§4).-race in CI — the one automated check that finds these, left off.append races on the length and the backing array.sync.Once or an atomic.The victim is never the author at write time, because the racy run usually isn't theirs:
fatal error: concurrent map writes — a crash that only triggers under production concurrency, never reproduced locally, with a stack trace pointing at a map the author "knew" was single-writer.time.Sleep did for the author who shipped it."Don't be clever" (Memory Model) is the empathy rule here: the clever lock-free shortcut, or the time.Sleep that "fixes" the flake, offloads an undefined-behavior bug onto whoever is on call when the scheduler finally interleaves it the wrong way. Serialize the access and let -race keep you honest.
This skill owns the race concept and the -race detector. The fixes and the surrounding tooling live elsewhere:
go-idiomatic-discipline — the policy root; racing on shared state is the "fighting Go / not correct" failure this skill detects.go-sync-primitives — the fix by locking: sync.Mutex/RWMutex, sync.Once, and the typed sync/atomic values that make an access synchronizing.go-channels-select — the fix by communication: why a send/receive is a happens-before edge, and "share memory by communicating."go-context — cancellation as the way to stop the goroutine whose shared access would otherwise race.go-concurrency-goroutines — goroutine lifetime/ownership; a leaked goroutine is often the unexpected second writer.go-testing-advanced — owns testing/synctest as a testing facility (and fuzz/benchmarks); this skill owns it only as the deterministic-race-test answer. Cross-link, don't duplicate.go-tooling-and-static-analysis — wiring go test -race into CI, plus go vet analyzers (e.g. waitgroup) that catch some races statically.High-frequency false-confidence patterns in LLM-generated concurrent Go, each with wrong/right code and citations:
Source provenance for every claim in this skill:
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub ctoth/golang-skills-plugin --plugin golang25 skills in this plugin
/go-channels-selectGuides Go channel mechanics — declare directionality in signatures (chan less than - send-only, less than -chan receive-only), let only the sender close and only when sends are done (closing is a broadcast, not cleanup), read the comma-ok / range-ends-on-close idiom so a closed channel's zero value is not mistaken for data, choose unbuffered (synchronization) vs buffered (decoupling) deliberately, use chan struct{} for pure signals, and drive select with default for non-blocking and the nil-channel trick to disable a case. Auto-invokes when writing or editing channels, chan declarations, close(), select statements, or buffered channels, and on "send on closed channel panic" / "why does this select block" / "why does my range over a channel never end" requests. The depth behind the policy root's "don't fight Go" for the communication primitive./go-concurrency-goroutinesGuides goroutine lifetime and ownership — never start a goroutine you can't stop, give every goroutine a defined exit (context cancellation, a closed channel, or bounded work), avoid the blocked-forever leak, use sync.WaitGroup correctly (Add before the go, or wg.Go in 1.25) and golang.org/x/sync/errgroup for fallible fan-out and SetLimit worker pools, and keep library functions synchronous so the caller owns concurrency. Auto-invokes when writing or editing `go` statements, goroutines, sync.WaitGroup, errgroup, worker pools, or on "is this goroutine leaking" / "how do I wait for these" requests. The depth behind the policy root's "never start a goroutine you can't stop."/go-contextGuides Go context.Context discipline — pass it as the first parameter named ctx and never store it in a struct, derive children with WithCancel/WithTimeout/WithDeadline and ALWAYS defer cancel() (go vet's lostcancel flags a missing one), check ctx.Done()/ctx.Err() in loops and before expensive work, start from context.Background() at entry points and context.TODO() when you don't have one yet, attach reasons with WithCancelCause/Cause and decouple with WithoutCancel/AfterFunc (1.20/1.21), and carry only request-scoped values behind an unexported key type. Auto-invokes when writing or editing functions taking context.Context, WithCancel/WithTimeout/WithValue, ctx.Done()/Err(), or on "where should ctx go" / "is this context leaking" requests. The propagation-and-cancellation depth behind the policy root's "never start a goroutine you can't stop."/go-defer-panic-recoverGuides Go's defer, panic, and recover — the LIFO ordering and arguments-evaluated-at-the-defer-statement semantics, why defer is near-free since open-coded defers (so don't avoid it except in tight loops), the loop-defer handle-leak pitfall, panic only for programmer bugs and unrecoverable states (not ordinary failure), and recover only inside a deferred function at a boundary to convert a panic into an error. Auto-invokes when writing or editing defer, panic, recover, or deferred cleanup, and on "why does this defer run in the wrong order", "should this panic", or "how do I stop a panic from crashing the process". Routes ordinary error-as-value handling to go-error-handling./go-error-handlingGuides Go error handling as values — wrap with fmt.Errorf and %w to preserve the chain, inspect with errors.Is (sentinel) and errors.As / errors.AsType (typed) instead of string-matching, choose sentinel vs custom error types and when they become API, combine with errors.Join, write lowercase un-punctuated messages, handle each error exactly once, and decorate or close-with-error via named returns and defer. Auto-invokes when writing or editing error returns, fmt.Errorf, errors.Is/As, custom error types, or on "handle this error" / "why is this error not matching" requests. The depth behind the policy root's "errors are values, never silently discarded."/go-genericsGuides Go generics restraint and constraint design — reach for a type parameter only when you would otherwise write the exact same code for multiple types (a container, or an algorithm over a slice/map/channel element type like map/filter/reduce), never when you only call a method on the value (that is an interface), and prefer the stdlib slices/maps/cmp helpers over hand-rolled generics. Covers constraints (any, comparable, cmp.Ordered, the ~T underlying-type element, unions like int | int64), type inference, generic type aliases (1.24), and self-referential constraints (1.26). Auto-invokes when writing or editing type parameters ([T any]), type constraints, generic functions or types, and on "should this be generic", "generic or interface here", or "make this generic". A type parameter earns its place only on real duplication; clarity first.