Skip to content

Go Sync Singleflight

DodaTech 1 min read

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
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

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to 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

**When should I use singleflight?**

For cache stampede prevention, expensive operations, duplicate request coalescing.

Does singleflight cache results?

No. Only for in-flight calls. Use with a cache for persistent storage.

What is the shared boolean?

True if the result was shared with other callers.


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