Programming Languages Bug Report

Our request counter undercounted by 7% under load: a Go data race found with -race

Billing usage counts from a Go service were consistently lower than the load balancer's numbers. The cause was an unsynchronised counter incremented from many goroutines. How the race detector found it, and when to use atomic versus a mutex.

Julian Navarro Julian Navarro @juliannavarro · November 23, 2026 · 7 min read · 45 Views
Banner: Go data race on a shared counter detected with the race flag

Our API gateway service, written in Go, counts requests per customer and flushes the counts to the billing database every minute. Finance runs a monthly check comparing those counts with the load balancer's access logs. In October the comparison came back with a gap: our counts were 6 to 8 percent lower for the busiest customers and almost exact for small ones.

Undercounting means undercharging, and the pattern (worse at higher traffic) pointed at concurrency before we even opened the code.

The counting code:

type UsageCounter struct {
    counts map[string]int64
}

func (u *UsageCounter) Inc(customerID string) {
    u.counts[customerID]++
}

func (u *UsageCounter) Flush() map[string]int64 {
    out := u.counts
    u.counts = make(map[string]int64)
    return out
}

Each HTTP request runs in its own goroutine, and every one of them calls Inc. A background goroutine calls Flush once a minute. There is no lock anywhere.

Reproducing with the race detector

We wrote a test that does what production does: many goroutines incrementing at once.

func TestUsageCounterConcurrent(t *testing.T) {
    u := &UsageCounter{counts: make(map[string]int64)}
    var wg sync.WaitGroup
    for i := 0; i < 50; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := 0; j < 1000; j++ {
                u.Inc("cust-1")
            }
        }()
    }
    wg.Wait()
    if got := u.counts["cust-1"]; got != 50_000 {
        t.Fatalf("count = %d, want 50000", got)
    }
}

Without the race detector the test sometimes crashed with a runtime error and sometimes reported a low count:

fatal error: concurrent map writes
--- FAIL: TestUsageCounterConcurrent (0.01s)
    usage_test.go:24: count = 46113, want 50000

With -race it failed every time and told us exactly where:

go test -race -run TestUsageCounterConcurrent ./usage/
==================
WARNING: DATA RACE
Read at 0x00c000124060 by goroutine 9:
  example.com/gateway/usage.(*UsageCounter).Inc()
      /src/usage/usage.go:12 +0x5c

Previous write at 0x00c000124060 by goroutine 8:
  example.com/gateway/usage.(*UsageCounter).Inc()
      /src/usage/usage.go:12 +0x84
...
==================
--- FAIL: TestUsageCounterConcurrent (0.02s)
    testing.go:1490: race detected during execution of test

Why count++ is not one step

u.counts[id]++ reads the current value, adds one, and writes it back. When two goroutines run it at the same time on different CPU cores, both can read 41, both write 42, and one increment is lost. The more concurrent requests a customer sends, the more often this overlap happens, which is why the gap grew with traffic.

The map makes it worse. Go maps are not safe for concurrent use. Concurrent writes can corrupt the map's internal structure, and the runtime detects some of these cases and stops the whole program with fatal error: concurrent map writes. That is not a panic you can recover from. In production we had seen three unexplained gateway restarts in the previous quarter; the logs confirmed this was the cause of all three.

Why it hid for so long

  • Most requests for a given customer did not overlap in time, so most increments survived.
  • The fatal map error is probabilistic and rare at moderate load.
  • Unit tests called Inc from a single goroutine and passed every time.
  • The service was never built or tested with -race.

What the race detector does

go test -race (and go build -race) instruments every memory access and tracks which goroutine touched each address and whether a synchronisation event (lock, channel operation, atomic) happened in between. Two accesses to the same address from different goroutines, at least one a write, with no happens-before relationship, is reported as a data race. It only finds races that actually execute during the run, so it needs tests that exercise concurrency, but when it reports one it is real.

Environment

Item Value
Go 1.23
Service API gateway, about 4,000 requests per second per instance at peak
Counter map[string]int64, no synchronisation
Symptom 6-8% undercount for top customers, 3 restarts with concurrent map writes

There are two standard tools: sync/atomic for simple numeric operations, and sync.Mutex for anything involving more than one value or a data structure like a map.

A single counter: atomic

If we only needed one global count, atomic.Int64 (added in Go 1.19) is the simplest correct option:

type Requests struct {
    n atomic.Int64
}

func (r *Requests) Inc()        { r.n.Add(1) }
func (r *Requests) Load() int64 { return r.n.Load() }
func (r *Requests) Reset() int64 { return r.n.Swap(0) }

Add performs the read, increment and write as one indivisible hardware operation. Swap(0) reads and resets in one step, so no increment can fall between reading the value and clearing it.

A map of counters: mutex

Our counter is per customer, so it is a map. Atomics cannot make map access safe; a mutex can:

type UsageCounter struct {
    mu     sync.Mutex
    counts map[string]int64
}

func (u *UsageCounter) Inc(customerID string) {
    u.mu.Lock()
    u.counts[customerID]++
    u.mu.Unlock()
}

func (u *UsageCounter) Flush() map[string]int64 {
    u.mu.Lock()
    out := u.counts
    u.counts = make(map[string]int64, len(out))
    u.mu.Unlock()
    return out
}

Flush swaps the map under the lock and returns the old one. The caller can then write it to the database without holding the lock, so a slow database never blocks request goroutines.

Is the mutex a bottleneck?

At 4,000 requests per second the critical section is a map increment, nanoseconds long. We benchmarked with go test -bench . -cpu 1,4,16 and saw no measurable effect on request latency. If contention had been a problem, the next steps would be sharding the map into N mutex-protected buckets by hash of the customer ID, or keeping per-goroutine counts and merging them. We did not need either, and adding them early would have been complexity without evidence.

Why not sync.Map?

sync.Map is designed for two cases: keys written once and read many times, or goroutines working on disjoint sets of keys. Our workload is many writes to the same hot keys, where a plain map with a mutex is usually faster and easier to reason about. Incrementing a value inside a sync.Map also needs a compare-and-swap loop or an atomic value per key, which is more code for no gain here.

1. The concurrency test passes under -race, 100 runs in a row:

go test -race -count=100 -run TestUsageCounterConcurrent ./usage/
ok      example.com/gateway/usage    3.912s

2. Race detector in CI for every package. We added go test -race ./... as a required CI step. It is slower (the Go docs note typical overhead of 2 to 20 times in execution time and 5 to 10 times in memory), so it runs in a separate job in parallel with the normal test job. On its first run it found one more race, in a cache warm-up flag read without synchronisation, which we fixed with atomic.Bool.

3. Production reconciliation. We ran a race-enabled build on one canary instance for a day under real traffic (race builds are too slow for the whole fleet). No reports. The next monthly comparison with the load balancer logs matched within 0.05 percent, explained by requests that failed before reaching the counter.

4. Security and billing implications. The bug undercharged, so customers were not harmed, but we reported the gap to finance with the corrected method rather than back-billing. The same pattern in a rate limiter would have been worse: lost increments would let clients exceed their limits. We audited the rate limiter, which already used Redis atomic increments, and confirmed it was not affected.

Takeaways

  • x++ on shared memory is read, modify, write. Concurrent goroutines lose updates.
  • Go maps are not safe for concurrent writes, and the runtime may kill the process when it detects them.
  • Use atomic for single numeric values and a Mutex for maps or anything with more than one field.
  • Run go test -race ./... in CI, and write tests that actually exercise concurrent paths.

References: Go data race detector, sync/atomic, sync.Mutex and sync.Map, The Go memory model.

Add a label

#go #concurrency #data-race #sync-atomic #mutex
Written by
Julian Navarro @juliannavarro

I have worked as a backend engineer for about twelve years, mostly in Python and Go, with enough JavaScript on the side to keep the frontend team honest. Most of that time was spent on internal platforms: billing jobs, import pipelines and the services everything else quietly depends on. What I keep seeing is that the expensive bugs rarely come from exotic corners. They come from fundamentals we all learned once and then stopped thinking about: a copy that was not deep, a loop that turned quadratic at real volume, an async call nobody awaited, a subclass that broke a rule its parent relied on. Each post here starts from one of those failures, shows how we traced it, the smallest fix that held and the test that keeps it from coming back. Where a principle or pattern helps, I show it on real code, and I am just as clear about where it only adds weight.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.