Level: AdvancedGo Lang

Go Race Detector: Find and Fix Data Races

8 min read
Go Race Detector featured image: turn on race mode, read the report and fix the race

The Go race detector is a built-in tool that finds data races. These are some of the hardest bugs in concurrent code. In this post, you will learn what a data race is and how to switch the detector on. Then we will fix a broken counter in two different ways and compare the fixes.

This lesson builds on Go goroutines for beginners and Go sync package with WaitGroup and Mutex. We also use ideas from Go httptest for testing handlers, because the detector works well inside tests. So if goroutines are new to you, read those lessons first.

What Is the Go Race Detector?

A data race happens when two goroutines touch the same variable at the same time. At least one of them must be writing. In short, the Go race detector watches your running program and reports every such moment. Because it is part of the Go toolchain, you do not install anything.

Think of two people editing one paper form at the same moment. One crosses out a number while the other writes a new one. As a result, the final form may show something neither person meant. Similarly, two goroutines can overwrite each other’s work, and the result changes from run to run.

Races are dangerous because the program often looks fine. For example, it may pass every test on your laptop and then fail only on a busy server. As a result, you need a tool, not just careful reading. Fortunately, the Go race detector makes this check almost automatic.

Why the Go Race Detector Matters

Concurrency is one of Go’s best features, but it also makes bugs harder to see. So here is what the Go race detector gives you.

  • Proof, not guesses: it shows the exact lines that read and write the shared value.
  • Early warnings: it finds races in tests, long before users see them.
  • Hidden bugs made visible: it catches races even when the final output looks correct.
  • Safer refactoring: you can change concurrent code and re-check it in seconds.
  • Team trust: a clean race test run builds confidence before a release.

Because of this, the Go team recommends running tests with -race as a normal habit. In fact, a few extra seconds in your test run can save days of debugging later.

How the Go Race Detector Works

You turn on the Go race detector with the -race flag on go run, go test or go build. After that, the compiler adds extra checks around every memory access. While the program runs, the detector records which goroutine touched which address and when. Finally, if two accesses clash without a proper synchronisation step between them, it prints a report.

Go Race Detector diagram showing two goroutines writing one counter and the race report
Two goroutines write the same counter with no lock between them. The race detector records both writes and prints a report with the two stack traces.

However, the detector only reports races that actually happen during the run. In other words, it cannot see code that never executes. So good tests matter just as much as the flag.

What a Race Report Contains

A report has a few clear parts, so the table below explains each one.

Report partWhat it tells you
WARNING: DATA RACEA race was found
Read at or Write atThe memory address and the goroutine
Previous write atThe earlier access that clashed
Goroutine ... created atThe line that started each goroutine
Found N data race(s)The total, printed at exit

Also, a program with a detected race exits with status 66. As a result, CI tools can stop the build.

The Cost of the Detector

The detector is not free. For example, programs usually run several times slower and use more memory. Therefore, use it in tests and staging. On the other hand, avoid shipping a -race build to production unless you have a good reason.

Go Race Detector: Mutex vs Atomic

There are two common ways to fix a simple counter race. Both are correct, but they fit different jobs, as the table below shows. Either way, the Go race detector will confirm that the fix works.

Featuresync.Mutexsync/atomic
ProtectsAny block of codeOne number or pointer
SpeedFastFastest for simple counters
Easy to misuseA little, if you forget to release itLess, but the API is small
Several variables at onceYesNo
Best forMaps, structs, multi-step updatesCounters and flags
Go Race Detector diagram comparing a mutex with an atomic counter
A mutex lets only one goroutine run a protected block at a time, while an atomic operation updates one value in a single safe step.

So when should you use which? Use an atomic for a single counter or flag. On the other hand, use a mutex when you update several fields or a map together.

Go Race Detector Hands-On: Fix a Broken Counter

Now let’s see a real race and fix it. We start 100 goroutines. Each one adds 1 to the same counter 1000 times, so the right answer is 100000.

Step 1: The Broken Version

First, here is the broken code. Later, we add a mutex fix and an atomic fix in the same file.

func main() {
	// 1. Broken: plain counter shared by 100 goroutines.
	broken := 0
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 1000; j++ {
				broken++
			}
		}()
	}
	wg.Wait()
	fmt.Println("broken:", broken)

The line broken++ looks like one step. In reality, it reads the value, adds one and writes it back. So two goroutines can read the same old value. As a result, one update gets lost.

Step 2: Fix It with a Mutex

Next, we wrap the increment in a lock. Because only one goroutine can hold the lock at a time, no update is lost.

	var mu sync.Mutex
	locked := 0
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 1000; j++ {
				mu.Lock()
				locked++
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	fmt.Println("mutex:", locked)

Step 3: Fix It with an Atomic Counter

Finally, we use atomic.Int64. It updates the number in one safe step, so it needs no lock.

	var atom atomic.Int64
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 1000; j++ {
				atom.Add(1)
			}
		}()
	}
	wg.Wait()
	fmt.Println("atomic:", atom.Load())
}

Step 4: Run It with and without -race

Now run go run . and look at the output. The broken counter loses updates, and the exact number changes on every run. For example, our first run printed the numbers below.

broken: 85855
mutex: 100000
atomic: 100000

Sometimes the broken line even prints 100000 by luck, which is why races are so sneaky. Then build the program with go build -race and run it. This time, the detector reports the problem every time. We shortened the file paths here.

==================
WARNING: DATA RACE
Read at 0x00c000112078 by goroutine 15:
  main.main.func1()
      main.go:18 +0x99

Previous write at 0x00c000112078 by goroutine 7:
  main.main.func1()
      main.go:18 +0xab

Goroutine 15 (running) created at:
  main.main()
      main.go:15 +0x99
==================
broken: 69298
mutex: 100000
atomic: 100000
Found 2 data race(s)

Let’s read the report. First, line 18 is broken++, and both the read and the write happen there. Also, the report says which goroutines clashed and where they were created. Finally, the mutex and atomic versions never appear in the report, so they are safe.

Step 5: Use the Race Detector in Tests

In real projects, you run the Go race detector with your tests. Type go test -race ./... and every race that your tests trigger will fail the run. Then add this command to your CI pipeline. As a result, races will stop reaching production.

Common Mistakes with the Go Race Detector

  • Trusting a passing run: a clean run without -race proves nothing. So run the Go race detector regularly.
  • Ignoring the report: some people mark races as “harmless”. However, a race can corrupt data in practice, so fix every one.
  • Protecting only the writes: reads need the lock as well. Otherwise, a reader can see half-updated data.
  • Concurrent map writes: a plain map is not safe for many goroutines. In fact, Go may crash with fatal error: concurrent map writes, so guard maps with a mutex.
  • Copying a mutex: a copied mutex is a different lock, so it protects nothing. Pass pointers instead, and run go vet to catch this.

Best Practices for the Go Race Detector

  • **Run go test -race ./... in CI**, because it catches races on every commit.
  • Share memory by communicating, since channels often remove the need for locks. A well-built pipeline needs very few mutexes.
  • Keep locks short, which reduces waiting and lowers the risk of deadlocks.
  • **Use defer right after taking a lock**, because it releases the lock even when the code panics.
  • Write concurrent tests, since a race can only appear when goroutines really overlap.
  • Prefer atomics for simple counters, because they are small and fast.

Practice Task

To practise the Go race detector, write a program that starts 50 goroutines and appends numbers to one shared slice. First, run it with -race and read the report. Then fix it in two ways, once with a mutex and once with a channel.

Hint: with a channel, let each goroutine send its number, and use one goroutine to do all the appends. Then compare how the two fixes read.

Official Resources

These pages explain the detector, the memory model and the sync packages in detail.

Quick Recap

  • A data race means two goroutines touch one variable at once, and one of them writes.
  • The Go race detector finds races when you add the -race flag.
  • Its report shows both accesses and where each goroutine started.
  • Fix races with a mutex, an atomic value or a channel.
  • Run go test -race ./... in CI, and avoid -race builds in production.
  • A clean normal run does not prove that your code is race free.

What’s Next?

By now, you can find and fix races. However, the best fix is often a design with no shared memory at all. So next, we will use goroutines and channels together to build a clean pipeline, with fan-out and fan-in.

Next up: Go pipeline pattern with fan-out and fan-in