Never Shared Once

A team adds request coalescing in front of an 800 ms origin query. Under load the origin still takes one call per concurrent reader, and line 4 logs shared=false every single time.

func GetProfile(ctx context.Context, id string) (*Profile, error) {
    if p, ok := cache.Get(id); ok {
        return p, nil
    }
    var g singleflight.Group                          // 1
    v, err, shared := g.Do(id, func() (any, error) {  // 2
        p, err := origin.LoadProfile(ctx, id)         // 3  ~800 ms
        if err != nil {
            return nil, err
        }
        cache.Set(id, p, 30*time.Second)
        return p, nil
    })
    log.Printf("profile %s shared=%v", id, shared)    // 4
    if err != nil {
        return nil, err
    }
    return v.(*Profile), nil
}

Which line is the bug?

A

Line 2: fn is missing a defer g.Forget(id), so the group keeps the completed entry and later callers wait on a call that has already returned

B

Line 1: g is a local variable, so every caller builds its own Group with an empty key map and has nothing to join. Hoisting it to package scope or a struct field collapses the 800 ms call to one per key

C

Line 3: passing the first caller's ctx into the shared function means a cancelled first caller aborts the origin query for everyone, forcing the rest to retry

D

The cache.Get guard above line 1 is racy, so concurrent readers all miss and each takes its own g.Do slot