Learning center

How do you read a Go DATA RACE report and choose the fix?

Find the variable both stacks touch, then ask which goroutine owns it: the fix follows the synchronization the rest of the code already uses for it. A clean -race run proves nothing about paths the tests never ran.

What the report contains#

The Go race detector instruments memory accesses while the program runs. Its article defines the bug it looks for: "A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write." It also describes the report, which "contains stack traces for conflicting accesses, as well as stacks where the involved goroutines were created." So a report has four stacks, in this order: the current access, the previous access, and where each of the two goroutines was started. The first two say which lines collide. The last two say who launched the concurrent work, which is usually where the ownership decision was made.

This constructed rate limiter guards its counter with a mutex in Allow, and refills it from a background goroutine:

func (l *Limiter) Allow() bool {
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.count >= l.limit {
		return false
	}
	l.count++                 // line 23
	return true
}

func (l *Limiter) reset() {
	l.count = 0               // line 28
}

// StartRefill resets the count every interval until stop is closed.
func (l *Limiter) StartRefill(every time.Duration, stop <-chan struct{}) {
	go func() {               // line 33
		t := time.NewTicker(every)
		defer t.Stop()
		for {
			select {
			case <-t.C:
				l.reset()     // line 39
			case <-stop:
				return
			}
		}
	}()
}

Read the four stacks#

Run with Go 1.24.7 as go test -race ./..., the test that starts a refill fails in only some runs: across repeated single runs here, between one in eight and one in three reported the race, and in some reports the previous access was the read on line 20 instead of the write on line 23. One failing run printed (paths shortened, testing frames trimmed):

==================
WARNING: DATA RACE
Write at 0x00c000022278 by goroutine 9:
  example.test/ratelimit.(*Limiter).reset()
      limiter.go:28 +0xe4
  example.test/ratelimit.(*Limiter).StartRefill.func1()
      limiter.go:39 +0xdc

Previous write at 0x00c000022278 by goroutine 8:
  example.test/ratelimit.(*Limiter).Allow()
      limiter.go:23 +0x10a
  example.test/ratelimit.TestRefillAllowsAgain()
      limiter_test.go:22 +0x14e
  testing.tRunner()
      .../src/testing/testing.go:1792 +0x225

Goroutine 9 (running) created at:
  example.test/ratelimit.(*Limiter).StartRefill()
      limiter.go:33 +0xe7
  example.test/ratelimit.TestRefillAllowsAgain()
      limiter_test.go:19 +0x104

Goroutine 8 (running) created at:
  testing.(*T).Run()
      .../src/testing/testing.go:1851 +0x8f2
==================
--- FAIL: TestRefillAllowsAgain (0.00s)
    testing.go:1490: race detected during execution of test
FAIL

Read it as three answers:

  1. What collides. Both accesses hit the same address, and both name a line in limiter.go: line 28 writes l.count in reset, line 23 writes l.count in Allow.
  2. Who runs each side. Goroutine 9 was created at line 33, the go statement inside StartRefill. Goroutine 8 is the test's own goroutine, created by testing.(*T).Run.
  3. What already protects the variable. Allow touches count only while holding l.mu. reset does not. The data has an owner (the mutex) and one path skipped it.

Choose the fix from who owns the data#

The four usual repairs each fit a different ownership story. Pick the one the report's stacks support, not the one that silences the report fastest.

  • A mutex fits when the variable already has a lock and one access path skipped it, as here. Take the same lock.
  • An atomic fits a single word that is read and written independently, such as a flag or a counter that is only incremented and read. It does not fit here: Allow reads count, compares it with limit, and increments it as one step, and an atomic load followed by an atomic add would let two callers both pass the check.
  • A channel fits when work should move from one goroutine to another, so the receiver becomes the only owner. The refill loop could send a reset request to a goroutine that owns count, but that means changing every caller of Allow.
  • Single ownership fits when the value never needed sharing: a goroutine received a pointer to a struct it could have copied, or a loop variable was captured instead of passed. Copy it or pass it as an argument.

The fix here is the existing mutex:

func (l *Limiter) reset() {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.count = 0
}

Repeating the run gives the scheduler more chances to produce the colliding interleaving. The unfixed code failed all ten -count=20 runs tried here; the fixed code passes:

$ go test -race -count=20 .
ok  	example.test/ratelimit	1.124s

The disconfirming run: a clean race build that is still racy#

The racy version did not fail every test. Run against the same unfixed code, only the test that lets the ticker fire reports anything:

$ go test -race -count=1 -v -run 'TestAllowRespectsLimit|TestStartAndStop' .
=== RUN   TestAllowRespectsLimit
--- PASS: TestAllowRespectsLimit (0.00s)
=== RUN   TestStartAndStop
--- PASS: TestStartAndStop (0.00s)
PASS
ok  	example.test/ratelimit	1.016s

TestStartAndStop starts the refill goroutine, calls Allow and stops it, but with a one-minute interval, so reset never runs. The race exists in the code and the race-enabled binary was built, yet the detector reports nothing, because it observes accesses as they happen. The article says so plainly: "The race detector only finds races that happen at runtime, so it can't find races in code paths that are not executed." Its advice for incomplete coverage is to run "a binary built with -race under a realistic workload."

So a dismissal that says "go test -race is clean" needs one more fact: the list of tests that ran the two code paths in the report concurrently. When a CI run reported a race and a local rerun is clean, the race is not gone. Check that the local run executed the test named in the --- FAIL line, and that the two goroutines in the report were both running.

Options that change what you see#

The GORACE variable controls the detector. The article lists halt_on_error ("Controls whether the program exits after reporting first data race") and exitcode, which defaults to 66 when a race was detected. Under go test, a race fails the test that was running, as the race detected during execution of test line shows, so a test suite run without -race hides the report entirely: the plain go test ./... run of the racy code above printed ok.

The article also describes the race build tag, which a file can use to exclude a test under -race. An exclusion like that is a dismissal and needs the same recorded reason as any other.

Decide from the stacks and the tests that ran#

What the report saysEvidence to collectDecision
Two accesses, one inside a lock and one outsideThe lock that guards the variable elsewhereTake the same lock on the unguarded path
Two accesses to an independent counter or flagWhether any caller combines read and write into one decisionUse sync/atomic only if no caller does
Goroutine created in a loop, access to a captured variableThe created at stack and the captured namePass the value as an argument or copy it per goroutine
Report in CI, clean locallyWhether the local run executed the failing test and both pathsKeep the finding; rerun the named test with -race -count=N
Clean -race run offered as proofThe tests that exercised both code paths concurrentlyCollect coverage of the concurrent path before dismissing

A reviewer's comment about a race needs different evidence from a detector report; the guide to race condition comments covers it. When a race shows up as a test that fails only sometimes, the guide to flaky test comments covers separating timing from logic.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading