Skip to content
Latchkey

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.

go
fatal error: concurrent map writes

goroutine 12 [running]:
	example.com/app.(*Cache).Set(...)
	/app/cache.go:22 +0x64

Common 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

  1. Protect every map access with a sync.Mutex, or switch to sync.Map for concurrent use.
Go
var mu sync.Mutex
mu.Lock()
m[key] = val
mu.Unlock()

Catch it with the race detector

  1. Run tests with -race so unsynchronized map access is flagged early.
Terminal
go test -race ./...

How to prevent it

  • Never write a shared map without synchronization.
  • Use sync.Map or a mutex for concurrent maps.
  • Run -race in CI to catch map races.

Frequently asked questions

What causes ""concurrent map writes""?
A shared map is written concurrently without a mutex or sync.Map, which the runtime detects and aborts on.
How do I fix "concurrent map writes"?
Guard the map

Related guides

References

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