Skip to content

Lesson 8 of 9 · 23m

Race Detection and Concurrency Observability

Use the race detector, execution traces, pprof, and targeted tests to expose real synchronization failures instead of hoping load reveals them.

The Go race detector is one of the best reasons to write concurrent Go. It is also routinely ignored because teams run it once in CI, see a flaky test unrelated to their change, and disable it. That is backwards. Race reports are memory-model evidence. Treat them like compiler errors that happen to arrive at runtime.

Exercise real concurrency

go test -race ./...

That is the minimum. Better is a race-enabled integration test that exercises request concurrency, background workers, cancellation, and shutdown. A unit test that calls functions sequentially can be race-free even when the production design is not.

Read reports outward from the invariant

A report shows two unsynchronized accesses to the same memory, at least one a write:

WARNING: DATA RACE
Write at 0x00c000... by goroutine 18:
  internal/cache.(*Cache).set()
Previous read at 0x00c000... by goroutine 7:
  internal/cache.(*Cache).get()

Do not patch the first line and move on. Identify the invariant both operations participate in. Often the right fix is narrower ownership, immutable snapshots, or removing shared state entirely.

Use pprof for parked goroutines

curl -s http://127.0.0.1:6060/debug/pprof/goroutine?debug=2 > goroutines.txt

Look for repeated stacks with large counts and long durations. Hundreds of goroutines in chan send usually mean downstream consumption stopped. Hundreds waiting for work may be normal. Counts, state, and age tell the story together.

Traces show scheduling reality

runtime/trace records scheduling, goroutine lifecycle, blocking, and syscalls:

f, _ := os.Create("trace.out")
trace.Start(f)
defer trace.Stop()
runScenario()

Inspect it with go tool trace trace.out when behavior is technically correct but latency spikes from descheduling, serialization, or garbage-collection interactions.

Field notes

  • The race detector finds races that execute; it does not prove untested paths correct.
  • time.Sleep changes timing but does not create memory synchronization. Never use it as a race fix.
  • A race can corrupt behavior far from the reported line because unsynchronized memory invalidates broad assumptions.
  • Publish goroutine count and queue depth. They are often the first production sign of a lifecycle bug.

Was this lesson helpful?

Sign in to rate