Understanding Singleflight in Go

· coding · Source ↗

TLDR

  • Go’s golang.org/x/sync/singleflight package deduplicates concurrent requests for the same resource, executing the function once and sharing the result.

Key Takeaways

  • singleflight.Group.Do(key, fn) ensures only one in-flight call per key; all waiting goroutines receive the same result and error.
  • Useful when caching is not viable or results change frequently – complements but does not replace a cache layer.
  • Combining singleflight with sync.Map covers both deduplication (in-flight) and caching (post-fetch), as shown in the weather service example.
  • Key design: string key management determines deduplication scope; poor key choice causes missed deduplication or incorrect result sharing.
  • Error propagation is shared too – a single upstream failure returns that error to all waiting callers simultaneously.

Hacker News Comment Review

  • No substantive HN discussion yet.

Original | Discuss on HN