Skip to content
Latchkey

Go "fatal error: concurrent map read and map write" - Fix in CI

Go maps are not safe for concurrent use. The runtime detects a simultaneous read and write on a map and aborts the whole process with a fatal error - this is a real data race, not a flake.

What this error means

A test crashes with fatal error: concurrent map read and map write and a goroutine dump. It means two goroutines touched the same map at once without a lock, often in a cache, registry, or shared counter.

go
fatal error: concurrent map read and map write

goroutine 18 [running]:
	example.com/app.(*Cache).Get(...)
goroutine 25 [running]:
	example.com/app.(*Cache).Set(...)

Common causes

Unguarded shared map

A map is read and written from different goroutines with no mutex protecting it.

Map captured by a goroutine in a test

A test spawns goroutines that share a map directly instead of through synchronization.

How to fix it

Protect the map with a mutex

  1. Wrap every read and write of the shared map in a sync.RWMutex.
Go
mu.RLock()
v, ok := m[key]
mu.RUnlock()

Use sync.Map for concurrent access

  1. For read-heavy concurrent maps, switch to sync.Map and its Load/Store methods.
Go
var m sync.Map
m.Store(key, val)
v, ok := m.Load(key)

How to prevent it

  • Never share a plain map across goroutines without a lock.
  • Run tests with -race to catch map races before they crash.
  • Prefer sync.Map or a mutex-guarded wrapper for shared maps.

Frequently asked questions

What causes ""concurrent map read and map write""?
A map is read and written from different goroutines with no mutex protecting it.
How do I fix "concurrent map read and map write"?
Protect the map with a mutex

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card