Go Sync Singleflight
In this tutorial, you'll learn about Go Singleflight: Request Coalescing. We cover key concepts, practical examples, and best practices.
Singleflight -- Use golang.org/x/sync/singleflight to coalesce duplicate concurrent requests into a single backend call.
The Problem
Without singleflight, N concurrent requests for the same key trigger N backend calls. singleflight ensures only one call is made and all waiters share the result.
Wrong
func getUser(id int) (*User, error) {
return db.QueryUser(id) // N concurrent calls = N queries!
}
Output:
// Cache stampede: 1000 concurrent requests = 1000 DB queries
Right
var sf singleflight.Group
func getUser(id int) (*User, error) {
key := fmt.Sprintf("user:%d", id)
v, err, _ := sf.Do(key, func() (interface{}, error) {
return db.QueryUser(id)
})
return v.(*User), err
}
Output:
// 1000 concurrent requests = 1 DB query + 999 shared results
Prevention
- Use Do(key, fn) to coalesce calls by key
- Returns (value, error, shared) where shared indicates result was shared
- Forget(key) to clear the key
- Use for cache stampede prevention
- Use with external caches for defense in depth
Common Mistakes with sync singleflight
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro