Deduplicate Concurrent Calls With singleflight
Collapse duplicate concurrent requests for the same key into a single upstream call so a burst of callers does not stampede a slow dependency.
Code
package cache
import (
"context"
"golang.org/x/sync/singleflight"
)
type Loader func(ctx context.Context, key string) (string, error)
type Group struct {
flight singleflight.Group
load Loader
}
func NewGroup(load Loader) *Group {
return &Group{load: load}
}
func (g *Group) Get(ctx context.Context, key string) (string, error) {
value, err, _ := g.flight.Do(key, func() (interface{}, error) {
return g.load(ctx, key)
})
if err != nil {
return "", err
}
return value.(string), nil
}How the snippet works
Deduplicate Concurrent Calls With singleflight is built around the functions NewGroup and Get.
Failures are values here: 1 site check err and decide instead of letting one propagate.
What to watch for
golang.org/x/sync/singleflightmust be installed first — the snippet imports it directly.- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
Signature: func NewGroup(load Loader) *Group
Import NewGroup from the file and call it — the rest of the code is implementation detail.
Key statements
func (g *Group) Get(ctx context.Context, key string) (string, error) {
value, err, _ := g.flight.Do(key, func() (interface{}, error) {
return g.load(ctx, key)
})
if err != nil {
return "", err
}
return value.(string), nil
}
func NewGroup(load Loader) *Group {
return &Group{load: load}
}
type Loader func(ctx context.Context, key string) (string, error)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- How do errors reach the caller?
- As returned `error` values, checked at its call site — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- Are there third-party dependencies?
- `golang.org/x/sync/singleflight` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.