Errgroup
golang.org/x/sync/errgroup runs a set of goroutines and returns the first error. Group.Go starts a function; Wait joins. WithContext cancels the others when one fails.
Detailed Explanation
A WaitGroup does not collect errors. A channel of errors plus a wait is several moving parts. errgroup.Group is that pattern in one type. g.Go(func() error { ... }) starts a goroutine. g.Wait() returns the first non-nil error, or nil if all succeed. Later errors are discarded unless you collect them yourself.
WithContext. g, ctx := errgroup.WithContext(parent) derives a child context cancelled when a Go function returns an error, or when Wait returns. Pass ctx into each task so a failure stops the rest. Wait still waits for every goroutine to return — cancel is the signal to exit promptly, not a kill.
SetLimit. g.SetLimit(n) caps the number of running Go functions. Extra calls to Go block until a slot is free. This is a worker pool without a channel of jobs, when the jobs are the Go closures themselves.
Zero Group is usable. You do not need WithContext if you only want "wait and first error" without cancel. Use WithContext for pipelines and request-scoped fan-out.
What it costs. Same as a wait group plus a mutex around the first error, and optionally a context. Import golang.org/x/sync/errgroup — it is not in the standard library. Pin the module in go.mod.
Code Examples
package main
import (
"fmt"
"golang.org/x/sync/errgroup"
)
func main() {
var g errgroup.Group
for i := 0; i < 3; i++ {
i := i
g.Go(func() error {
if i == 1 {
return fmt.Errorf("boom")
}
return nil
})
}
fmt.Println(g.Wait())
}func all(ctx context.Context, urls []string, fetch func(context.Context, string) error) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8)
for _, u := range urls {
u := u
g.Go(func() error { return fetch(ctx, u) })
}
return g.Wait()
}Common Gotchas
`Wait` does not cancel unless you used `WithContext` and the tasks watch `ctx`
a failed task's siblings keep running otherwise.
Only the first error is returned
log others inside the task if you need them.
`SetLimit(-1)` means unlimited
the default.