Singleflight Cache Stampede Protection
Shield a slow loader with singleflight and a shared cache, collapsing concurrent misses into one fetch and serving stale during refresh.
Code
package main
import (
"context"
"fmt"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
type Store struct {
mu sync.RWMutex
cache map[string]entry
group singleflight.Group
}
type entry struct {
value string
expires time.Time
}
func NewStore(ttl time.Duration) *Store {
return &Store{cache: make(map[string]entry)}
}
func (s *Store) Get(ctx context.Context, key string, ttl time.Duration) (string, error) {
s.mu.RLock()
e, ok := s.cache[key]
s.mu.RUnlock()
if ok && time.Now().Before(e.expires) {
return e.value, nil // 命中:新鲜数据直接返回
}
v, err, _ := s.group.Do(key, func() (interface{}, error) {
value, loadErr := slowLoad(ctx, key) // 同 key 并发只执行一次
if loadErr != nil {
return nil, loadErr
}
s.mu.Lock()
s.cache[key] = entry{value: value, expires: time.Now().Add(ttl)}
s.mu.Unlock()
return value, nil
})
if err != nil {
if ok {
return e.value, nil // 回源失败时降级旧值
}
return "", err
}
return v.(string), nil
}
func slowLoad(_ context.Context, key string) (string, error) {
time.Sleep(50 * time.Millisecond)
return "value-for-" + key, nil
}
func main() {
store := NewStore(time.Minute)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
v, _ := store.Get(context.Background(), "config", time.Minute)
fmt.Println(v)
}()
}
wg.Wait()
}How it works
The working surface is the functions NewStore, Get, slowLoad and main — everything else is wiring.
Repetition is confined to for i := 0; i < 10; i++ — the rest of the file is straight-line. The Go idiom runs throughout — 1 if err != nil check, each handling the failure on the spot. A goroutine takes the work off the current one. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
What to watch for
- Requires
golang.org/x/sync/singleflightas a package; the snippet will not run without it. - The function reports failure by returning
error— callers branch on it before touching other results.
Using it
The main signature reads func NewStore(ttl time.Duration) *Store
Execute the file and main walks through NewStore and Get, in that order.
Key statements
func slowLoad(_ context.Context, key string) (string, error) {
time.Sleep(50 * time.Millisecond)
return "value-for-" + key, nil
}
return &Store{cache: make(map[string]entry)}
if err != nil {
if ok {
return e.value, nil // 回源失败时降级旧值
}
return "", err
}
Interactive Tools for This Topic
FAQ
- Is there exception handling?
- Through `error` values, not panics — the snippet checks `err != nil` at 1 site.
- Do I need to install anything before running this?
- Yes: `golang.org/x/sync/singleflight` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.