Go "fatal error: concurrent map writes" in test - Fix in CI
Go maps are not safe for concurrent writes. When two goroutines write the same map at once, the runtime aborts the whole process with a fatal error.
What this error means
A run crashes with fatal error: concurrent map writes and a goroutine trace. It often appears only in CI where higher parallelism makes the concurrent access more likely to collide.
fatal error: concurrent map writes
goroutine 12 [running]:
example.com/app.(*Cache).Set(...)
/app/cache.go:22 +0x64Common causes
Map written from multiple goroutines
A shared map is written concurrently without a mutex or sync.Map, which the runtime detects and aborts on.
Test parallelism triggers the collision
Parallel tests or goroutines in the code exercise the unsynchronized map more aggressively in CI.
How to fix it
Guard the map
- Protect every map access with a sync.Mutex, or switch to sync.Map for concurrent use.
var mu sync.Mutex
mu.Lock()
m[key] = val
mu.Unlock()Catch it with the race detector
- Run tests with -race so unsynchronized map access is flagged early.
go test -race ./...How to prevent it
- Never write a shared map without synchronization.
- Use
sync.Mapor a mutex for concurrent maps. - Run
-racein CI to catch map races.