errgroup with SetLimit: at most N goroutines at once

Read the explanation
What if

Four jobs, at most two at a time. When both slots are taken, main's own g.Go waits for one to free up. g.Wait waits for every job.

01234567main: g.Go(job 1), g.Go(job 2)g.Go ×2main: g.Go(job 3): waits for a slotwaitsmain: g.Go(job 3), g.Go(job 4)g.Go ×2g.Wait()main: print all donedonenetwork callnetwork callnetwork callnetwork call

Tap any block to see what that thread is doing.

  • Running
  • Waiting / parked
  • Waiting on I/O
Step 1/5

SetLimit(2): at most two jobs at once. main starts jobs 1 and 2.

1func fetch(ctx context.Context, id int) error {2    select {3    case <-time.After(20 * time.Millisecond): // a network call4        fmt.Println("job", id, "done")5        return nil6    case <-ctx.Done(): // another job failed: stop early7        return ctx.Err()8    }9}10 11func main() {12    g, ctx := errgroup.WithContext(context.Background())13    g.SetLimit(2) // at most 2 jobs at once14    for id := 1; id <= 4; id++ {15        g.Go(func() error { return fetch(ctx, id) }) // waits while 2 are running16    }17    if err := g.Wait(); err != nil {18        fmt.Println("error:", err)19    }20    fmt.Println("all done")21}

Explanation

What just happened

SetLimit(2) gave the group two slots. Jobs 1 and 2 took them, so the third g.Go didn’t return: main itself waited until a job finished. Then jobs 3 and 4 ran, and g.Wait waited for all four.

Try the what-if switch

Why

A plain go statement starts as many goroutines as you ask for. A thousand jobs that each open a connection can overload the server they call. SetLimit makes the loop wait instead.

When to use it

For many independent jobs that can fail, where you want the first error and the rest stopped: fetching a list of URLs, processing files. For results, collect them as in getting results back from goroutines.

Watch out

g.Go blocks its caller, as it blocked main here. If that goroutine has other work to do, TryGo never waits: it returns false when every slot is taken.

Common questions

How do I limit how many goroutines run at once?

Use errgroup.Group with SetLimit(n). At most n jobs run at once; past that, g.Go blocks the goroutine that calls it, in [chan send], until a job finishes and frees a slot.

What does g.Wait return when a job fails?

The first error. With errgroup.WithContext, that error also cancels the group's context, and g.Wait still returns the first error, not the cancellations it caused.

Does a failing job stop the other goroutines?

Only if they watch ctx.Done(). WithContext cancels the context; a plain errgroup.Group cancels nothing, and its other jobs run to the end.

What's the difference between g.Go and g.TryGo?

g.Go waits for a free slot. g.TryGo doesn't: with every slot taken, it returns false and starts nothing.

Verified: this timeline matches a real program, checked in CI on Go 1.26 and 1.27. How we verify. Unclear or wrong? Tell us