singleflight

The golang.org/x/sync/singleflight package provides a Group whose Do method allows only one in-flight function execution per key within that group. Concurrent callers using the same key wait for the execution and share its result, while singleflight does not coordinate work across separate processes.

Minimal example

go
var group singleflight.Group
value, err, shared := group.Do(key, func() (any, error) {
	return load(ctx)
})

Learn this concept

Lesson 6.1 · Cache-aside with jitter and singleflight

Used in exercises

Exercise 6.2 · Menu cache and stock updater Exercise 6.17 · XFetch cache refresh decider
Prerequisite conceptsGoroutinesGo context