How to Use singleflight to Deduplicate Concurrent Calls

Use internal/singleflight.Group.Do to deduplicate concurrent function calls by key, ensuring only one execution runs while others wait for the shared result.

Use the internal/singleflight package's Group type to ensure only one execution of a function runs for a specific key, while other concurrent requests for that key wait and share the result. Create a Group instance, then call Do with a unique key and the function to execute; if the function is already running for that key, the call blocks until completion and returns the cached result.

import "golang.org/x/sync/singleflight"

var sf singleflight.Group

func fetchUser(id string) (string, error) {
    // Simulate expensive operation
    return "user_data", nil
}

result, err, shared := sf.Do(id, func() (any, error) {
    return fetchUser(id)
})
if err != nil {
    return err
}
fmt.Printf("Result: %v, Shared: %v\n", result, shared)