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.

GoResilience

Code

gosnippet
28 lines
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/singleflight must be installed first — the snippet imports it directly.
  • Error values are returned, not thrown — every call site must inspect err before 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

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.