Sphere
Log in Join
☆ 15

concurrent map writes panic from a background goroutine

Production panic: fatal error: concurrent map writes goroutine 34 [running]: main.(*Cache).Set(...) /app/cache.go:22 I have a map[string]Item used as a cache, written by several goroutines and read by the HTTP handlers. I thought reads were safe if I wasn't resizing. Clearly not. What's the right structure here, RWMutex or sync.Map? Ideally I'd understand why reads are fine but writes are not before I pick a structure, since this cache is central.

⚑ Report

4 replies

☆ 0
P paper31 ·2026-10-15#1

Concurrent reads are fine, but any concurrent write (even with no resize) is a fatal error. For a general cache with mixed reads and writes, a sync.RWMutex around a plain map is the standard answer: RLock for reads, Lock for writes. sync.Map is specialized for read-mostly or disjoint-key workloads and isn't automatically faster.

⚑ Report
☆ 0
E elastic ·2026-10-20#2

Our workload is maybe 90% reads on a small set of keys. Would sync.Map help or should I just use the RWMutex? I ran -race after the change and it's clean. What surprised me is that the map had been in production for months without an obvious panic, probably because the write pattern only kicks in under a specific request shape.

⚑ Report
☆ 0
R rust60 ·2026-10-29#3

Start with RWMutex, it's predictable and easy to reason about. sync.Map shines when keys are written once and read many times, or when different goroutines touch disjoint keys. Benchmark both with your actual access pattern if perf matters; correctness first.

⚑ Report
☆ 0
M moon ·2026-11-06#4

Went with RWMutex, panic is gone and -race is clean. Reads take RLock so there's still concurrency there. I'll keep sync.Map in mind if profiling ever shows the lock as a bottleneck, but for now this is plenty. Anyway, that is what worked for us.

⚑ Report
Log in to reply.