Fix Concurrent Map Read/Write Panics & Data Races in Go
Why Go maps crash with fatal concurrent map writes, and how sync.RWMutex, sync.Map, and go test -race keep them safe.
By the end of this tutorial you will know:
- Why Go's built-in
mapis not safe for concurrent writes - How to protect a map with
sync.RWMutex(and when to usesync.Map) - How to catch hidden data races before production using
go test -race
Prerequisites: Go 1.20+ installed and basic familiarity with maps and structs.
1. The big idea
Go's built-in map is optimized for single-goroutine speed, not thread safety. If two goroutines write to the same map—or one writes while another reads—the runtime detects the corruption and immediately crashes your whole process with a fatal error (not even a recover()-able panic).
2. Reproducing the crash
package main
import "sync"
func main() {
counts := map[string]int{}
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
counts["hits"]++ // concurrent read + write!
}(i)
}
wg.Wait()
}Running this quickly fails with:
fatal error: concurrent map read and map write3. The fix: wrap the map with sync.RWMutex
Putting a sync.RWMutex right next to the map inside a struct lets many goroutines read at the same time (RLock), while ensuring writes (Lock) have exclusive access.
package main
import (
"fmt"
"sync"
)
type SafeCounter struct {
mu sync.RWMutex
counts map[string]int
}
func NewSafeCounter() *SafeCounter {
return &SafeCounter{counts: make(map[string]int)}
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counts[key]++
}
func (c *SafeCounter) Get(key string) int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.counts[key]
}
func main() {
counter := NewSafeCounter()
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter.Inc("hits")
}()
}
wg.Wait()
fmt.Println("hits:", counter.Get("hits"))
}hits: 50Run go run -race safe_map.go. You should see hits: 50 with zero race warnings. In your real projects, always run go test -race ./... in CI.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
| Returning a pointer/slice inside the map without copying | Data race after RUnlock() | Return a copy of the value while holding the lock |
Calling Lock() twice in the same goroutine | Deadlock | Keep locked sections small and never call another locking method |
Skipping -race in tests | Crashes only under production traffic | Run go test -race ./... |
5. What you learned
You now know why Go maps crash under concurrent access, how to encapsulate a map with sync.RWMutex, and how go test -race catches data races automatically.
Video walkthrough
YouTubeClick play to load video (YouTube)