Go: fatal error: concurrent map writes in goroutines
The runtime catches two writes to one map and stops the process. Guard access with a mutex, use sync.Map for caches, or give one owner.

Introduction & Quick Summary
fatal error: concurrent map writes
goroutine 47 [running]:
runtime.throw({0x596e0e?, 0x0?})
runtime/panic.go:1096
internal/runtime/maps.(*Map).putSlotSmallFastStr(...)
internal/runtime/maps/map.go:1234This is not a panic you can recover from. The Go runtime detects that two goroutines are writing the same map at once and terminates the process, because the map's internal state is already corrupt and continuing would produce arbitrary memory behavior.
The safe patterns are few and well known:
sync.Mutexorsync.RWMutexaround every access, including reads that race with writes.sync.Mapfor append-only caches with many readers and rare writes.- One map per goroutine, merged at the end.
- A channel that owns the map, serializing all mutations through one goroutine.
concurrent map read and map write and concurrent map iteration and map write are the same defect with a different detector branch.
| Access pattern | sync.Mutex | sync.Map | Channel owner |
|---|---|---|---|
| Many reads, rare writes | Good with RWMutex | Best | Acceptable |
| Write-heavy | Best | Poor | Acceptable |
| Read-modify-write | Best | No atomic equivalent | Best |
| Iteration while writing | Lock for both | Range is a snapshot-ish | Best |
| Per-request scratch | No sharing needed | No | No |
Core Mechanics, Signatures & Reproducible Setup
A Go map is a header pointing at runtime buckets. Writes mutate buckets and may trigger growth, which moves entries; a concurrent reader or writer sees inconsistent state. The runtime sets a hashWriting flag during a write and calls throw if another write observes it — a deliberate hard failure, since a data race on a map is undefined behavior in the memory model.
Reproduce it reliably:
package main
import "sync"
func main() {
m := map[int]int{}
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
m[n] = n * n // unsynchronized write
}(i)
}
wg.Wait()
}go run main.go
# fatal error: concurrent map writesThe crash is probabilistic: a run with one goroutine or a fast scheduler may finish without detection. That is why the race detector, not the crash, is the correct verification tool:
go run -race main.go
# WARNING: DATA RACE
# Write at 0x00c0000... by goroutine 8:
# main.main.func1()The minimal fix with a mutex:
type Counter struct {
mu sync.RWMutex
m map[string]int
}
func NewCounter() *Counter {
return &Counter{m: make(map[string]int)}
}
func (c *Counter) Add(key string, n int) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[key] += n
}
func (c *Counter) Get(key string) (int, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.m[key]
return v, ok
}RWMutex is worth it only when reads dominate and critical sections are short; otherwise Mutex is faster because it has less bookkeeping.
Key Comparison Table
| Tool | Protects | Cost per op | Fails when |
|---|---|---|---|
sync.Mutex | All map access | ~20ns uncontended | Lock omitted on one path |
sync.RWMutex | All map access | Higher write cost | Reader takes Lock and calls RLock |
sync.Map | Individual keys | Allocation on write | Read-modify-write assumed atomic |
| Channel owner | All access | Channel hop | Reply channel closed early |
| Per-goroutine map | Nothing shared | None until merge | Merge order matters |
atomic.Pointer[map] | Whole map swap | CAS retry | In-place mutation of the pointed map |
| Message | Detector | Usual code |
|---|---|---|
concurrent map writes | Write flag | Handler writes shared map |
concurrent map read and map write | Write flag + read | Cache read during refresh |
concurrent map iteration and map write | Iterator check | range over map being updated |
DATA RACE from -race | Shadow memory | Any unsynchronized access |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: A package-level map written by HTTP handlers
var hits = map[string]int{}
func handler(w http.ResponseWriter, r *http.Request) {
hits[r.URL.Path]++ // concurrent requests crash the server
w.WriteHeader(http.StatusNoContent)
}Under load this crashes the whole process, not one request. Replace the map with a guarded type and make the zero value usable so callers cannot forget initialization:
type Hits struct {
mu sync.Mutex
m map[string]int
}
func (h *Hits) Inc(key string) {
h.mu.Lock()
if h.m == nil {
h.m = make(map[string]int)
}
h.m[key]++
h.mu.Unlock()
}A nil map read is legal and a nil map write panics, so lazy initialization under the same lock removes an entire class of bugs.
Case 2: Double-checked cache without the second lock
var cache = map[string][]byte{}
var mu sync.Mutex
func get(key string) []byte {
if v, ok := cache[key]; ok { // read without lock
return v
}
mu.Lock()
defer mu.Unlock()
if v, ok := cache[key]; ok {
return v
}
v := load(key)
cache[key] = v
return v
}The first read races with writes from other goroutines. Either lock every read, or use sync.Map with LoadOrStore to avoid duplicate loads entirely:
var cache sync.Map
func get(key string) []byte {
if v, ok := cache.Load(key); ok {
return v.([]byte)
}
v, _ := cache.LoadOrStore(key, load(key))
return v.([]byte)
}load may still run more than once under contention; LoadOrStore guarantees one stored value, not one computation. Use sync.Once per key or singleflight when the load must be unique.
Case 3: Copying a struct that contains a map
type Registry struct {
items map[string]Item
}
func (r Registry) Set(k string, v Item) { // value receiver
r.items[k] = v // still the same map
}Maps are reference types: copying the struct copies the header, so both copies write the same buckets. A value receiver makes the bug look like it cannot happen. Use a pointer receiver and an explicit mutex, and keep the struct non-copyable with noCopy if the linter supports it.
Case 4: Iterating while another goroutine writes
go func() {
for range time.Tick(time.Second) {
sessions["new"] = Session{}
}
}()
for id, s := range sessions {
expire(id, s)
}The runtime reports concurrent map iteration and map write. Snapshot the keys under a read lock, then work on the copy:
mu.RLock()
ids := make([]string, 0, len(sessions))
for id := range sessions {
ids = append(ids, id)
}
mu.RUnlock()
for _, id := range ids {
expire(id)
}Iteration order was never guaranteed, so the snapshot loses nothing semantically.
Case 5: Subtests sharing a map under t.Parallel
func TestParse(t *testing.T) {
results := map[string]bool{}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
results[tc.name] = parseOK(tc.input) // racy
})
}
}Parallel subtests run in separate goroutines and the parent returns before they finish. Use a channel or a mutex, and note that Go 1.22 changed loop variable capture, so tc is safe to capture now, but the map is not.
var mu sync.Mutex
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ok := parseOK(tc.input)
mu.Lock()
results[tc.name] = ok
mu.Unlock()
})Case 6: sync.Map does not make read-modify-write atomic
var counts sync.Map
func inc(key string) {
v, _ := counts.Load(key)
n, _ := v.(int)
counts.Store(key, n+1) // lost updates, but no crash
}sync.Map protects its internals, not your invariants. Two goroutines can both load 5 and store 6. The crash disappears and a subtler correctness bug appears, which is worse. Use a mutex plus a plain map, or atomic.Int64 values inside LoadOrStore.
Common Compilation/Runtime Mistakes & Version Gotchas
- Assuming no crash means no race. The runtime detects a subset of interleavings. Run
go test -race ./...in CI; the race detector finds reads and writes the fatal check never sees. -racein production builds. It costs 5–20x CPU and memory. Use it in tests and staging, not in the deployed binary, and keep a separate CI job for it.- Go 1.24 map implementation. The runtime switched to Swiss-table maps; the fatal error text and stack frames changed, and iteration performance differs, but the safety rules are identical. Stack traces that name
internal/runtime/mapsare not a new bug class. - Go 1.22 loop variables. Per-iteration loop variables removed a common capture bug but did nothing for shared maps; code that "worked" before because of a lucky scheduling order is still racy.
maps.Cloneis shallow. Cloning before mutation avoids sharing the top-level map, not nested maps or slices inside values. Deep structures need a real copy.atomic.Pointer[map]is not a lock. It makes swapping a map safe; mutating the map that a reader is ranging over still triggers the fatal error.
When a stack trace arrives as a log line, format the goroutine dump into JSON with the JSON formatter and isolate the frames that touch the map with the regex tester. For the race detector's report, the diff tool shows whether the two conflicting accesses are on the same field after a refactor.
Primary references: The Go Programming Language Specification defines map types and their non-atomic behavior, and sync documents Mutex, RWMutex and Map including the rule that Map is optimized for write-once, read-many cases.
Official references
primary documentationThe Go documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo: x509 certificate signed by unknown authority
Go cannot build a chain to a trusted root: no CA bundle in the image, a private CA, or a missing intermediate. Install roots or set RootCAs.
Go: go.mod file not found in current directory
Go 1.16 and later build in module mode. Run commands inside the module root, create a go.mod with go mod init, or set GO111MODULE and GOWORK deliberately.
Go: import cycle not allowed
Go forbids cycles in the package import graph. Break them by extracting shared types, declaring interfaces where consumed, or inverting init registration.
Go: http: superfluous response.WriteHeader call
net/http logs this when a handler writes the status twice. It almost always marks a later status write that was silently ignored, or no return.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.