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.
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
- Wrap every read and write of the shared map in a sync.RWMutex.
mu.RLock()
v, ok := m[key]
mu.RUnlock()Use sync.Map for concurrent access
- For read-heavy concurrent maps, switch to sync.Map and its Load/Store methods.
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
-raceto catch map races before they crash. - Prefer
sync.Mapor a mutex-guarded wrapper for shared maps.