Singleflight
Deduplicate concurrent calls. 10 goroutines request the same key, only one fetches.
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
"golang.org/x/sync/singleflight"
)
var (
group singleflight.Group
fetchCount atomic.Int64
)
// Simulate a slow database query
func fetchFromDB(key string) (string, error) {
fetchCount.Add(1)
time.Sleep(100 * time.Millisecond)
return fmt.Sprintf("value-for-%s", key), nil
}
func getData(key string) (string, error) {
val, err, shared := group.Do(key, func() (any, error) {
return fetchFromDB(key)
})
if err != nil {
return "", err
}
fmt.Printf("key=%s shared=%v result=%s\n", key, shared, val)
return val.(string), nil
}
func main() {
var wg sync.WaitGroup
// 10 goroutines request the same key at the same time
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
getData("user:42")
}()
}
wg.Wait()
fmt.Printf("\n10 concurrent requests, %d actual DB calls\n", fetchCount.Load())
}Output shows shared=true for 9 of the 10 calls and only 1 actual DB fetch.