Lesson 3 of 9 · 21m
Errgroup and Supervised Concurrency
Use errgroup and small supervisor patterns to join concurrent work, propagate first failure, and avoid orphaned goroutines.
Most teams do not need a custom actor framework. They need a boring way to start three related operations, fail fast when one breaks, and wait for the rest to stop. That is exactly the gap golang.org/x/sync/errgroup fills. Used well, it turns a pile of go statements into a supervised unit with a lifecycle.
The mental model
An errgroup is a small process tree. Every child shares a derived context. The first non-nil error cancels the rest, and Wait returns that error after all children exit; cancellation remains cooperative, so children must check it:
func rebuild(ctx context.Context, tenants []string) error {
g, ctx := errgroup.WithContext(ctx)
for _, tenant := range tenants {
g.Go(func() error { return rebuildTenant(ctx, tenant) })
}
return g.Wait()
}First failure is a policy choice
Returning the first error is often right for dependent RPC fanout. In a batch job, losing the other failures can blind operators. For independent bulk work, collect per-item errors and return nil from each child so siblings continue:
mu.Lock()
errs = append(errs, fmt.Errorf("tenant %s: %w", tenant, err))
mu.Unlock()
return nilUse errors.Join(errs...) after g.Wait(). Decide explicitly: fail fast for dependent work, collect for independent work.
Bound concurrency at the same boundary
SetLimit prevents accidental self-inflicted denial of service:
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8)
for _, object := range objects {
g.Go(func() error { return upload(ctx, object) })
}Avoid half supervision
If a child launches another untracked goroutine, g.Wait() no longer means the unit finished:
g.Go(func() error {
go audit(event) // escaped ownership
return process(event)
})Pass a child group downward deliberately or use an owned queue. Do not let work escape the lifecycle boundary.
Field notes
g.Wait()can block forever if one child ignores cancellation. Errgroup is coordination, not preemption.- Calling blocking
g.Gofrom inside a limited group's child can deadlock; spawn from the owner. - Return contextual errors.
tenant 42: context canceledis actionable; a bare error is not. - Errgroup joins work. If children need restart and health-check semantics, write a supervisor instead of contorting errgroup.
Was this lesson helpful?