Skip to content

Catching data races in Go with -race in tests and CI

Use go test -race to detect data races in concurrent Go code, interpret the report, fix the four common race patterns, and wire -race into CI without paying for it in prod builds.

Go’s value proposition for concurrent services is goroutines + channels, but the language does not prevent data races — two goroutines reading and writing the same memory without synchronization is undefined behavior that surfaces as flaky tests and the occasional 3 AM corruption. go test -race finds those before they ship. This article shows how Stack Harbor wires the race detector into CI and how to read its reports.

How to verify

Run the test suite under -race and inspect the output:

go test -race ./...
go test -race -count=3 ./internal/queue
GOEXPERIMENT=loopvar go test -race -short ./...
go build -race -o /tmp/api-race ./cmd/api
./tmp/api-race --config=test.yaml

If the suite passes silently, no races are visible to the detector with the test workload. The race report only fires on observed conflicts — increasing -count or running stress tests under -race can surface races that single passes miss.

What’s happening

The race detector instruments memory accesses at compile time, then watches at runtime for two goroutines that touch the same address where at least one access is a write and there is no happens-before relationship (channel send, mutex unlock, etc.) ordering them. When it sees one, it prints the two stacks and the variable.

The detector has overhead: 5-10x CPU, ~10x memory. You don’t run it in production. You run it in tests, in CI, and occasionally against staging to catch races that only manifest under realistic load.

Goroutine-safe data structures in stdlib (sync.Mutex, sync.RWMutex, sync.Map, channels, atomic.Int64) all carry happens-before semantics. The detector treats them as synchronization points. A race report means you bypassed every one of them.

The four most common race patterns we find in audits:

  1. Sharing a map without sync.Mutex or sync.Map.
  2. Sharing a struct field across goroutines without atomic or mutex.
  3. for i, v := range items { go work(v) } before Go 1.22 — v is shared across iterations.
  4. Closing a channel and reading from it concurrently.

The procedure

  1. Run the whole suite under -race. This is non-negotiable:

    go test -race -timeout 5m -count=1 ./...

    -count=1 defeats the test cache so you actually re-run.

  2. Reading a race report. Sample output:

    WARNING: DATA RACE
    Read at 0x00c00009c198 by goroutine 8:
      main.(*counter).Get()
          /app/counter.go:14 +0x44
      main_test.TestCounter.func2()
          /app/counter_test.go:22 +0x6c
    Previous write at 0x00c00009c198 by goroutine 7:
      main.(*counter).Inc()
          /app/counter.go:10 +0x66
      main_test.TestCounter.func1()
          /app/counter_test.go:18 +0x5e

    The two stacks tell you the read site and the write site. The variable is at memory address 0x00c00009c198 — usually the same field. Fix: add a mutex around access or convert the field to atomic.Int64.

  3. Fix pattern A — shared map.

    // Race:
    type cache struct { m map[string]string }
    func (c *cache) Get(k string) string { return c.m[k] }
    func (c *cache) Set(k, v string) { c.m[k] = v }
    
    // Fix:
    type cache struct {
        mu sync.RWMutex
        m  map[string]string
    }
    func (c *cache) Get(k string) string {
        c.mu.RLock(); defer c.mu.RUnlock()
        return c.m[k]
    }
    func (c *cache) Set(k, v string) {
        c.mu.Lock(); defer c.mu.Unlock()
        c.m[k] = v
    }
  4. Fix pattern B — shared counter.

    // Race:
    type counter struct { n int64 }
    func (c *counter) Inc() { c.n++ }
    func (c *counter) Get() int64 { return c.n }
    
    // Fix:
    type counter struct { n atomic.Int64 }
    func (c *counter) Inc() { c.n.Add(1) }
    func (c *counter) Get() int64 { return c.n.Load() }
  5. Fix pattern C — loop variable capture (Go < 1.22).

    // Race (and bug, even without race detector):
    for _, item := range items {
        go process(item)
    }
    
    // Fix Go 1.21 and earlier:
    for _, item := range items {
        item := item   // shadow into per-iteration var
        go process(item)
    }

    Go 1.22 changed range semantics so each iteration has its own v — the race goes away on 1.22+. Keep the shadow line as documentation, or rely on the toolchain version in go.mod.

  6. Fix pattern D — close + send race. Closing a channel while a goroutine still sends is a panic AND a race:

    // Race:
    close(ch)
    ch <- v  // panic + data race
    
    // Fix: only the sender closes; coordinate with done channel
    done := make(chan struct{})
    go func() {
        defer close(ch)
        for v := range work() {
            select {
            case ch <- v:
            case <-done: return
            }
        }
    }()
  7. Wire -race into CI. A separate stage so the regular go test stays fast:

    # .github/workflows/test.yml
    jobs:
      race:
        runs-on: ubuntu-22.04
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-go@v5
            with: { go-version: '1.22.5' }
          - run: go test -race -timeout 10m -count=1 ./...

    The race job tends to take 3-5x as long as the non-race suite. Run it on PRs and main; consider nightly stress runs.

Common pitfalls

  • The race detector only reports observed races. Code can be racy and pass -race until someone runs the right workload. Augment with stress tests and -count=N.
  • -race increases memory. Tests that fit in 1 GiB without -race may need 4 GiB with it. Tune CI runner sizes accordingly.
  • go run -race works. Useful for ad-hoc reproduction against integration suites that drive a real server.
  • Some races report from third-party code. That is still a race in your binary. Either patch the dep, add synchronization at the boundary, or report it upstream.
  • -race is not available for every platform. windows/arm64 and some embedded targets do not support it. The detector requires C TSan support in the toolchain.

Stack Harbor runs go test -race on every PR for every Go service we maintain, and on a nightly stress harness for the high-concurrency ones. See how that fits into our managed operations practice when concurrency bugs become recurring incidents.