Singleflight cache fill to prevent thundering herd

9171
0

When a cache key expires, it’s easy for a burst of requests to stampede the database. I use singleflight.Group to ensure only one goroutine performs the expensive fill per key while others wait for the shared result. This doesn’t replace proper TTLs or circuit breakers, but it smooths the “sawtooth” load pattern you get with synchronized expirations. The code is intentionally small: check the cache, call group.Do on miss, and set the cache on success. The other detail I care about is error behavior: if the fill fails, I don’t poison the cache, and I return the underlying error so the caller can decide whether to serve stale data. It’s one of the highest ROI concurrency primitives in Go.