Go
Concurrent Map Writes Fatal Error Fix
Two goroutines writing to one plain map is not a data race you might get away with - it is a fatal error the runtime raises when it catches the overlap, and silent corruption when it does not. This guide shows both crash shapes, the detector that catches the race every time, and the four shapes that make shared map access safe.
Written November 28, 2026 · Tested with Go 1.26.4 · 12 min read
- The first failure: two writers, one map
- The reliable detector: the race detector
- The second failure: iteration racing a write
- First fix: a Mutex around every access
Written November 28, 2026
Tested with Go 1.26.4
What this guide is
The crash line is fatal error: concurrent map writes. It fires when two goroutines write to the same plain map at overlapping moments - and the important word is when: the runtime catches some overlaps and misses others, so the same racy program can crash in one run and finish cleanly in the next. A clean finish is not evidence that the code is safe. This guide reproduces the crash with a workload heavy enough to trigger it reliably, shows the second crash shape - a write racing with an iteration - then uses the race detector, which reports the race deterministically on code far too small to crash, and gives the four fixes: guard the map with a sync.Mutex, split reads from writes with a sync.RWMutex, use sync.Map where its documented use cases fit, or give the map a single owner goroutine that answers requests over a channel.
The rule underneath is stated in the Go blog's maps article: maps are not safe for concurrent use - it is not defined what happens when you read and write to them simultaneously, and accesses from concurrently executing goroutines must be mediated by some kind of synchronization mechanism. Every fix in this guide is one such mechanism, applied to every access, with no exceptions for reads that "only look".
Each program below is a single file in one module - run go mod init once in an empty directory, save each program under the file name shown, and build it by that name. The transcripts of the failing programs set GOTRACEBACK=none, which suppresses the goroutine stack trace so the fatal line stands alone; a plain run prints the same lines followed by the trace.
The first failure: two writers, one map
Eight goroutines each write 20,000 distinct keys into one shared map, with no synchronization at all:
package main
import (
"fmt"
"sync"
)
func main() {
m := make(map[int]int)
var wg sync.WaitGroup
fmt.Println("starting concurrent writers")
for g := 0; g < 8; g++ {
wg.Add(1)
go func(g int) {
defer wg.Done()
for i := 0; i < 20000; i++ {
m[g*20000+i] = i
}
}(g)
}
wg.Wait()
fmt.Println("all writers finished")
}
$ go build -trimpath -o p1.bin p1_concurrent_writes.go
$ GOTRACEBACK=none ./p1.bin; echo "exit status $?"
starting concurrent writers
fatal error: concurrent map writes
exit status 2
The finishing line never prints and the exit status is 2. The size of the workload is what makes this transcript stable: with 160,000 writes in flight across eight goroutines, overlapping writes are effectively guaranteed, and the runtime's check fires. Shrink the same shape to two goroutines writing ten keys each and the outcome becomes a coin flip - that version finished cleanly in some runs and crashed with the same fatal line in others. Both behaviors are the same bug. The runtime check is a safety net that catches a concurrent write while it is happening; it is not a proof system, and a run where it stays silent has simply not overlapped in the way the check observes. Never conclude a shared map is safe because a test run did not crash - the next section's detector is the tool that settles the question.
Note also what the writers are doing: each goroutine writes only its own disjoint set of keys. Disjoint keys do not help. A map write mutates the map's shared internal structure, not just the slot for its key, so two writes to different keys are still two concurrent writes to one map.
The reliable detector: the race detector
The race detector is built into the Go toolchain - add the -race flag to go build, go run, or go test - and it works on a different principle: it watches the accesses themselves and reports a data race when two goroutines access the same variable concurrently and at least one access is a write, whether or not the accesses corrupt anything. This much smaller program - four goroutines, 1,000 writes each - is far below the size that crashes reliably, and the detector still names the race:
package main
import (
"fmt"
"sync"
)
func main() {
m := make(map[int]int)
var wg sync.WaitGroup
for g := 0; g < 4; g++ {
wg.Add(1)
go func(g int) {
defer wg.Done()
for i := 0; i < 1000; i++ {
m[g] = i
}
}(g)
}
wg.Wait()
fmt.Println("writers finished")
}
$ go build -race -trimpath -o p2.bin p2_race.go
$ ./p2.bin 2>&1 | grep -m 1 'WARNING: DATA RACE'
WARNING: DATA RACE
The transcript shows only the first WARNING: DATA RACE line of the report, extracted with grep, because the full report is not stable text: it contains memory addresses and goroutine numbers that change from run to run, and the run's exit status varies with how the report and the runtime's own map check interleave. That line does not vary - in repeated runs the detector reported the race every time, on a program whose plain build can finish without the fatal error. That asymmetry is the working rule: use the fatal error as the symptom that sends you looking, and the race detector as the verdict on whether a fix actually removed the race. A fix is done when the -race build runs the workload clean, not when the plain build stops crashing.
The second failure: iteration racing a write
Writes are not the only trigger. A range over a map is a long-lived read of the map's internal structure, and a write that lands while an iteration is in progress raises the sibling error:
package main
import (
"fmt"
)
func main() {
m := make(map[int]int)
for i := 0; i < 10000; i++ {
m[i] = i
}
fmt.Println("starting iteration with concurrent write")
done := make(chan struct{})
go func() {
for i := 10000; i < 200000; i++ {
m[i] = i
}
close(done)
}()
for {
for range m {
}
select {
case <-done:
fmt.Println("iteration finished")
return
default:
}
}
}
$ go build -trimpath -o p3.bin p3_iter_write.go
$ GOTRACEBACK=none ./p3.bin; echo "exit status $?"
starting iteration with concurrent write
fatal error: concurrent map iteration and map write
exit status 2
The message names both sides: concurrent map iteration and map write. The practical consequence is that "I only read the map in that goroutine" is not a defense when the read is an iteration - or any read, since a read racing a write is the same class of unsynchronized access, and the race detector reports it as one. Every access path to a shared map, reads included, goes through the same synchronization. That is what the first two fixes wire up.
First fix: a Mutex around every access
The default repair is the mediation the maps article requires: every access under a lock. One sync.Mutex guards the map, every write takes it, and - in real code - every read takes it too. The first program's workload, unchanged except for the lock around each write, now completes:
package main
import (
"fmt"
"sync"
)
func main() {
m := make(map[int]int)
var mu sync.Mutex
var wg sync.WaitGroup
for g := 0; g < 8; g++ {
wg.Add(1)
go func(g int) {
defer wg.Done()
for i := 0; i < 20000; i++ {
mu.Lock()
m[g*20000+i] = i
mu.Unlock()
}
}(g)
}
wg.Wait()
fmt.Println("entries:", len(m))
fmt.Println("all writers finished")
}
$ go build -trimpath -o p4.bin p4_mutex_fix.go
$ ./p4.bin; echo "exit status $?"
entries: 160000
all writers finished
exit status 0
All 160,000 entries are present - the count itself is part of the result, because a racy version that happened not to crash could silently lose writes. Two disciplines make this fix hold in larger code. First, the lock and the map travel together: declare them side by side, or embed both in a struct, so no code path can reach the map without passing the lock. Second, the lock covers every access - a single unguarded read or a len check outside the lock reintroduces the race the lock was added to remove. For a hold that spans a function body, the usual shape is mu.Lock() followed immediately by defer mu.Unlock(); the per-write form above suits a tight loop where the lock is taken and released around each single operation.
Second fix: RWMutex when reads dominate
When most accesses are reads and writes are comparatively rare, sync.RWMutex lets any number of readers hold the read lock at once while a writer still gets the map exclusively. Writers take Lock, readers take RLock, and each releases with its matching call:
package main
import (
"fmt"
"sync"
)
func main() {
m := make(map[string]int)
var mu sync.RWMutex
var wg sync.WaitGroup
for g := 0; g < 4; g++ {
wg.Add(1)
go func(g int) {
defer wg.Done()
key := fmt.Sprintf("key-%d", g)
for i := 0; i < 1000; i++ {
mu.Lock()
m[key] = i
mu.Unlock()
mu.RLock()
_ = m[key]
mu.RUnlock()
}
}(g)
}
wg.Wait()
mu.RLock()
fmt.Println("key-0:", m["key-0"])
fmt.Println("key-3:", m["key-3"])
mu.RUnlock()
fmt.Println("read and write finished")
}
$ go build -trimpath -o p5.bin p5_rwmutex_fix.go
$ ./p5.bin; echo "exit status $?"
key-0: 999
key-3: 999
read and write finished
exit status 0
Each key ends at 999, the last value its writer stored, and the final reads run under the read lock like every other access. Choose this shape when the read/write split is real - many readers genuinely proceeding in parallel. When writes are as common as reads, the plain Mutex is simpler and the read lock buys nothing; and a read lock held across an iteration is still a hold like any other, so keep iterations under it short or copy the entries out and iterate the copy.
Third fix: sync.Map, for the cases it is built for
sync.Map is a map that is safe for concurrent use by multiple goroutines without additional locking or coordination, with Store, Load, and Delete instead of index syntax:
package main
import (
"fmt"
"sync"
)
func main() {
var m sync.Map
var wg sync.WaitGroup
for g := 0; g < 8; g++ {
wg.Add(1)
go func(g int) {
defer wg.Done()
for i := 0; i < 20000; i++ {
m.Store(g*20000+i, i)
}
}(g)
}
wg.Wait()
count := 0
m.Range(func(key, value any) bool {
count++
return true
})
fmt.Println("entries:", count)
v, ok := m.Load(42)
fmt.Println("key 42:", v, ok)
fmt.Println("all writers finished")
}
$ go build -trimpath -o p6.bin p6_syncmap_fix.go
$ ./p6.bin; echo "exit status $?"
entries: 160000
key 42: 42 true
all writers finished
exit status 0
The same 160,000 concurrent stores complete with no lock in sight, and Load returns the stored value with its presence flag. But the documentation is explicit that this type is specialized, and that most code should use a plain map with separate locking instead, for better type safety and to make it easier to maintain other invariants along with the map content. sync.Map is optimized for two use cases: an entry that is written only once but read many times, as in a cache that only grows; and multiple goroutines reading, writing, and overwriting entries for disjoint sets of keys. If your map is neither - if code must update several entries together, or keep a counter consistent with the map - the lock-guarded plain map is the right fix and this one is not, whatever its convenience. Note also that its keys and values are any, so every Load hands back an interface value the caller must type-assert, as the 42 true line above leaves unasserted only because it is printed, not used.
Fourth fix: one owner goroutine, requests by channel
The fourth shape removes sharing instead of guarding it: exactly one goroutine owns the map, and every other goroutine asks it, over a channel, to do the work. No second goroutine ever touches the map, so there is nothing to race:
package main
import "fmt"
type request struct {
key int
value int
reply chan int
}
func main() {
reqs := make(chan request)
done := make(chan struct{})
go func() {
m := make(map[int]int)
for req := range reqs {
m[req.key] = req.value
req.reply <- len(m)
}
close(done)
}()
for i := 0; i < 5; i++ {
reply := make(chan int)
reqs <- request{key: i, value: i * 10, reply: reply}
fmt.Println("stored, size now:", <-reply)
}
close(reqs)
<-done
fmt.Println("owner goroutine finished")
}
$ go build -trimpath -o p7.bin p7_owner_fix.go
$ ./p7.bin; echo "exit status $?"
stored, size now: 1
stored, size now: 2
stored, size now: 3
stored, size now: 4
stored, size now: 5
owner goroutine finished
exit status 0
The map is declared inside the owner goroutine and never leaves it; callers send a key, a value, and a reply channel, and the owner answers with the map's size after the store - 1 through 5, in order. This shape fits when the map already lives behind a service-like boundary - a cache process, a session registry, an event loop - where requests naturally arrive one at a time and the owner can also enforce invariants, expiry, or ordering for free. It is the wrong shape for a hot inner loop: every access becomes a channel round trip, where the mutex version is a single lock around the operation. Reach for it when ownership is the design, not as a lock substitute.
Decision summary
- The crash line is
fatal error: concurrent map writes: two goroutines wrote to a plain map concurrently - pick a fix below and apply it to every access, reads included. - The crash line instead reads
fatal error: concurrent map iteration and map write: arangeoverlapped a write - the iteration needs the same synchronization as any other access. - The program does not crash but shares a map between goroutines: build with
-raceand run the workload - aWARNING: DATA RACEreport is the verdict, and a clean plain run proves nothing either way. - Writes and reads are both frequent, or several entries must change together: a plain map guarded by a
sync.Mutex, lock and map declared together. - Reads dominate and writers are rare: the same guarded map with a
sync.RWMutex-RLockfor reads,Lockfor writes, each released by its matching call. - The map is a grow-only cache, or goroutines work on disjoint key sets, and no cross-entry invariants exist:
sync.Map, accepting itsany-typed keys and values. - The map sits behind a request-driven boundary where one goroutine can naturally own it: the owner-goroutine shape, with all access sent as channel requests.
Checklist
- No goroutine touches the shared map without the synchronization the chosen fix prescribes - writes, reads, iterations, and
lenchecks alike. - Disjoint keys are not treated as safety: concurrent writes to different keys of one map are still concurrent map writes.
- The fixed code is run under a
-racebuild with a realistic workload, and the run reports no data race. - No conclusion is drawn from a plain build merely not crashing - the runtime's map check is best-effort detection, not a guarantee.
- Lock and map are declared together (or embedded in one struct), so a new access path cannot bypass the lock.
sync.Map, if used, matches one of its two documented use cases, and no invariant spanning several entries depends on it.
Related guides
- Unlock of Unlocked Mutex Panic Fix - the lock discipline the first two fixes depend on: every
Unlockmust answer aLockthat is still held, and an unmatched release is a fatal error of its own. - Assignment to Entry in Nil Map Panic Fix - the other map crash, from the opposite cause: writing to a map that was never made, in a single goroutine, with no concurrency involved.
Sources
- Go blog, Go maps in action - Concurrency - the rule this error enforces: maps are not safe for concurrent use, it is not defined what happens when you read and write to them simultaneously, accesses from concurrently executing goroutines must be mediated by a synchronization mechanism, and
sync.RWMutexis the common protection it demonstrates. - Go
syncpackage - the fixes' contracts:Mapis safe for concurrent use without additional locking, is specialized, is optimized for the write-once-read-many and disjoint-key-set use cases, and most code should use a plain map with separate locking instead;MutexandRWMutexare the locking primitives the first two fixes use. - Go documentation, Data Race Detector - the detector's definition and usage: a data race is two goroutines accessing the same variable concurrently with at least one write, the detector is enabled with the
-raceflag on the go command, its report carries the lineWARNING: DATA RACE, and it only finds races in code paths that are executed.
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.