Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#Go#Concurrency#Maps#Runtime
A Go map crate hit by two cyan goroutine arrows, an amber mutex key and a runtime stop gate

Introduction & Quick Summary

text
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:1234

This 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.Mutex or sync.RWMutex around every access, including reads that race with writes.
  • sync.Map for 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 patternsync.Mutexsync.MapChannel owner
Many reads, rare writesGood with RWMutexBestAcceptable
Write-heavyBestPoorAcceptable
Read-modify-writeBestNo atomic equivalentBest
Iteration while writingLock for bothRange is a snapshot-ishBest
Per-request scratchNo sharing neededNoNo

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:

go
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() }
bash
go run main.go # fatal error: concurrent map writes

The 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:

bash
go run -race main.go # WARNING: DATA RACE # Write at 0x00c0000... by goroutine 8: # main.main.func1()

The minimal fix with a mutex:

go
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

ToolProtectsCost per opFails when
sync.MutexAll map access~20ns uncontendedLock omitted on one path
sync.RWMutexAll map accessHigher write costReader takes Lock and calls RLock
sync.MapIndividual keysAllocation on writeRead-modify-write assumed atomic
Channel ownerAll accessChannel hopReply channel closed early
Per-goroutine mapNothing sharedNone until mergeMerge order matters
atomic.Pointer[map]Whole map swapCAS retryIn-place mutation of the pointed map
MessageDetectorUsual code
concurrent map writesWrite flagHandler writes shared map
concurrent map read and map writeWrite flag + readCache read during refresh
concurrent map iteration and map writeIterator checkrange over map being updated
DATA RACE from -raceShadow memoryAny unsynchronized access

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: A package-level map written by HTTP handlers

go
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:

go
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

go
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:

go
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

go
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
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:

go
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

go
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.

go
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

go
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.
  • -race in 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/maps are 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.Clone is 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 documentation

The Go documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.