Skip to Content
Skip to content
Find and Fix Go Data Races With -race
Advanced
Tutorials

Find and Fix Go Data Races With -race

Trigger a real data race under go test -race, read the race detector output, and fix shared counters, maps, and slice writes using atomic, sync.Mutex, and disjoint indices. After this, concurrent bugs fail in tests instead of production.

Updated 4 min read GoTesting and Debugging

A data race happens when two goroutines access the same memory variable concurrently and at least one of them is writing—with no lock, atomic operation, or channel synchronization between them. Worse, data races often pass 500 local runs on a quiet laptop and only corrupt counters, lose map entries, or crash with fatal error: concurrent map writes under real production load.

Go ships a built-in runtime race detector right inside go test -race and go run -race. Verified on Go 1.27.

Case 1: Triggering a real data race on a shared counter

Suppose 10 goroutines each increment a shared hits counter 1,000 times. Without synchronization, hits++ is a three-step read-modify-write, so goroutines silently overwrite each other's increments:

// Broken: unsynchronized concurrent writes to hits
func TestCounterRace(t *testing.T) {
	hits := 0
	var wg sync.WaitGroup
	for range 10 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for range 1000 {
				hits++ // DATA RACE!
			}
		}()
	}
	wg.Wait()
	if hits != 10000 {
		t.Fatalf("got %d, want 10000", hits)
	}
}
$ go test -race .
==================
WARNING: DATA RACE
Read at 0x00c000120048 by goroutine 8:
  example.com/race.TestCounterRace.func1()
      /src/race_test.go:15 +0x44

Previous write at 0x00c000120048 by goroutine 7:
  example.com/race.TestCounterRace.func1()
      /src/race_test.go:15 +0x56
==================
FAIL

Case 2: How to read a race detector report in 10 seconds

Every Go race report gives you the exact two colliding accesses:

  1. Top stack (Read at 0x... by goroutine 8): The current goroutine and exact file:line that collided.
  2. Second stack (Previous write at 0x... by goroutine 7): The other goroutine and exact file:line that touched the exact same memory address with no synchronization in between.

Because the race detector only sees code paths that actually execute during the test, write concurrent tests with at least 2–10 goroutines hitting the shared code at the same time.

Case 3: Three clean fixes depending on what is shared

  • Single counter or flag → sync/atomic: Replace hits := 0 with var hits atomic.Int64 and call hits.Add(1) / hits.Load()—lock-free and ~17× faster than a mutex on hot reads.
  • Shared map or multi-field struct → sync.Mutex: Protect every read and every write with the same mutex (a map read racing against a map write crashes the entire Go runtime without even needing -race!):
type SafeCache struct {
	mu   sync.Mutex
	data map[string]string
}

func (c *SafeCache) Set(k, v string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.data[k] = v
}

func (c *SafeCache) Get(k string) (string, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	v, ok := c.data[k]
	return v, ok
}
  • Parallel results into a slice → disjoint indices: Pre-allocate out := make([]Result, len(items)) and let worker i write exclusively to out[i]—zero locks and 100% race-free once wg.Wait() returns.

Case 4: When to run -race (and its runtime cost)

The race detector adds roughly 2–5× CPU overhead and 5–10× memory overhead—making it ideal for go test -race ./... in every PR/CI run and in staging soak tests, while production binaries are built normally without -race.

💡 Tip

Remember that -race requires cgo (a C compiler like gcc) on Linux/macOS—so if your build environment sets CGO_ENABLED=0 globally, override it when running tests: CGO_ENABLED=1 go test -race ./....

Common mistakes

  • Locking only writes and leaving reads unlocked: A read concurrent with a write is still a data race! Both readers and writers must synchronize with the same mutex or atomic.
  • Assuming a passing go test -race proves zero races on untested paths: The race detector is dynamic—it only inspects code that runs concurrently during tests.
  • Ignoring "benign" races on booleans or metrics counters: In Go's memory model, there is no such thing as a benign data race—unsynchronized writes can cause torn reads, stale CPU caches, or infinite loops.

⚠ Warning

Never ship a concurrent map without a sync.Mutex (or sync.Map for specialized append-mostly caches). Go's runtime intentionally terminates the entire process on concurrent map writes—even recover() cannot save it.

What happens if you skip this

Data races stay invisible on quiet dev machines, then silently corrupt counters, drop cache entries, or crash production pods with unrecoverable concurrent map-write panics under peak traffic.

Related course: Go Advanced.

About

Trigger a real data race under go test -race, read the race detector output, and fix shared counters, maps, and slice writes using atomic, sync.Mutex, and disjoint indices. After this, concurrent bugs fail in tests instead of production.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
4 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.