How to fix cache stampede in Go?
Use the singleflight pattern — only one goroutine executes the fetch while others wait and share the result.
import "golang.org/x/sync/singleflight"
var g singleflight.Group
func GetData(key string) (string, error) {
v, err, _ := g.Do(key, func() (interface{}, error) {
return fetchFromDatabase(key)
})
return v.(string), err
}