TL;DR
For a batch of independent jobs that can fail, use errgroup.WithContext plus SetLimit(n). It bounds concurrency, returns the first error and cancels the rest in about 10 lines. Use a channel pool when the input is a long-running stream or each worker owns state, such as a database connection. Use semaphore.Weighted when jobs have different costs.
In the tests below, all three held concurrency at the limit. None of them stopped work after an error by itself: with jobs that ignored the context, a failure at 40 ms still let all 24 jobs run to 170 ms. The most common mistake is “spawn one goroutine per job, then wait for a slot”. At 10,000 jobs it held 10,002 goroutines and 20.2 MiB of stack, against 10 goroutines and 0.5 MiB for errgroup.SetLimit.
| Fact | Value | Source | Verified |
|---|---|---|---|
| Go version for every run below | go1.27.4 (Go Playground, 8 CPUs) | runtime.Version() and runtime.NumCPU() on the Playground | Nov 25, 2026 |
golang.org/x/sync version | v0.25.0, tagged Oct 15, 2026 | module proxy | Nov 25, 2026 |
sync.WaitGroup.Go | Added in Go 1.25 | Go 1.25 release notes | Nov 25, 2026 |
goroutineleak profile | Experimental in Go 1.26, generally available in Go 1.27 | Go 1.27 release notes | Nov 25, 2026 |
| errgroup panic propagation | In x/sync v0.14.0 and v0.15.0, removed in v0.16.0 (Jun 20, 2025) | errgroup source by tag | Nov 25, 2026 |
Three ways to bound concurrency in Go
Every Go service eventually has a long list of jobs to run concurrently, with only a few of them in flight at any moment. You might have 50,000 S3 keys to fetch, with a rate limit that allows 8 requests in flight. Or a crawler that must not open 2,000 sockets. The standard library gives you goroutines and channels. The golang.org/x/sync module adds two helpers built on top of them, and the three approaches solve the same problem:
- A channel pool: start N long-lived worker goroutines that read jobs from a channel.
errgroup.GroupwithSetLimit(n): one goroutine per job, andGoblocks while n are active.semaphore.Weighted: acquire a weight before you start a job, release it when the job ends.
There’s also a fourth pattern that shows up in code review all the time: spawn every goroutine at once and make each one wait for a slot on a buffered channel. It limits the work correctly, but its goroutine count grows with the input size.
I ran each pattern on the official Go Playground, which used go1.27.4 with x/sync pinned to v0.25.0 in a go.mod. One detail shapes how you should read the numbers: the Playground uses a simulated clock. time.Sleep advances it exactly, and CPU work leaves it where it was. A CPU loop of 50 million iterations printed 0s. The elapsed times below are therefore a schedule: the order in which work could start and finish. The schedule is deterministic, so it shows exactly when each pattern lets a job start, which is the point of this comparison. For wall-clock speed, benchmark on your own hardware. Memory and allocation counts are real measurements from the runtime.
The patterns at a glance
| Behavior | Channel pool | errgroup.SetLimit | semaphore.Weighted | Spawn-then-wait |
|---|---|---|---|---|
| Peak jobs in flight (limit 4) | 4 | 4 | 4 | 4 |
| Peak goroutines, 24 jobs | 7 | 5 | 5 | 24 |
| First error returned | Manual | Wait() | Manual (or add errgroup) | Manual |
| Cancels siblings on error | Manual | Yes, with WithContext | No | No |
| Stops the submit loop on error | Manual | No, you check ctx.Err() | Yes, once the context is cancelled, Acquire(ctx) fails | No |
| Different cost per job | No | No | Yes | No |
| Allocations per job | 0.02 | 2.00 | 4.98 | Not measured |
| Worker panic | Crashes the process | Crashes the process | Crashes the process | Crashes the process |
The rest of the article is the evidence for each row.
The same workload, four patterns
The test workload has 24 jobs. Job id sleeps for (id%4+1)*10 milliseconds, so the durations cycle through 10, 20, 30 and 40 ms. The concurrency limit is 4. A small tracker counts how many jobs run at the same time and records the highest runtime.NumGoroutine() value it sees. Here are the four contenders, copied from the program that produced the output:
// 1. Classic pool: a fixed set of workers reads from a jobs channel.
func channelPool(t *tracker) int {
jobs := make(chan int)
results := make(chan int)
var wg sync.WaitGroup
for range limit {
wg.Go(func() {
for id := range jobs {
results <- t.work(id)
}
})
}
go func() {
for id := range numJobs {
jobs <- id
}
close(jobs)
}()
go func() { wg.Wait(); close(results) }()
sum := 0
for r := range results {
sum += r
}
return sum
}
// 2. errgroup with SetLimit: Go blocks once `limit` goroutines are active.
func errgroupLimit(t *tracker) int {
var g errgroup.Group
g.SetLimit(limit)
out := make([]int, numJobs)
for id := range numJobs {
g.Go(func() error {
out[id] = t.work(id)
return nil
})
}
g.Wait()
return sum(out)
}
// 3. semaphore.Weighted: acquire before spawning, release when done.
func weightedSem(t *tracker) int {
ctx := context.Background()
sem := semaphore.NewWeighted(limit)
var wg sync.WaitGroup
out := make([]int, numJobs)
for id := range numJobs {
if err := sem.Acquire(ctx, 1); err != nil {
break
}
wg.Go(func() {
defer sem.Release(1)
out[id] = t.work(id)
})
}
wg.Wait()
return sum(out)
}
// 4. Anti-pattern: spawn everything, then wait for a slot inside the goroutine.
func spawnThenWait(t *tracker) int {
sem := make(chan struct{}, limit)
var wg sync.WaitGroup
out := make([]int, numJobs)
for id := range numJobs {
wg.Go(func() {
sem <- struct{}{}
defer func() { <-sem }()
out[id] = t.work(id)
})
}
wg.Wait()
return sum(out)
}
The output on the Playground:
go1.27.4
pattern sum elapsed peak peakGor
channel pool 4324 170ms 4 7
errgroup.SetLimit 4324 170ms 4 5
semaphore.Weighted 4324 170ms 4 5
spawn-then-wait 4324 160ms 4 24
All four produce the same result and keep 4 jobs in flight. The goroutine count is where they split. The channel pool holds 7 goroutines: main, 4 workers, the producer and the goroutine that closes results. errgroup and the semaphore hold 5, because the submit loop blocks before it creates a fifth job goroutine. The spawn-then-wait version creates all 24 up front, so its goroutine count grows with the input size while the semaphore limits only the work.
The spawn-then-wait run also finished 10 ms sooner, and the start order explains the gap. Its 24 goroutines race for the semaphore, so jobs start in a different order, and this order happened to pack the 40 ms jobs better. On a different input the order could just as easily be worse.
Three recent language and library features keep these snippets short. for range limit ranges over an integer (Go 1.22). Loop variables are per-iteration since Go 1.22, so the closures capture the correct id without the old id := id copy. wg.Go is the sync.WaitGroup.Go method from Go 1.25. It replaces the wg.Add(1) / defer wg.Done() pair, and the Go 1.25 go vet adds a waitgroup analyzer that reports a misplaced wg.Add. If your module still targets an older Go, write the Add/Done pair yourself.
What happens when one job fails
In the next program, job 5 returns an error. It starts at 20 ms and fails at 40 ms. I ran the 24 jobs in four variants, A to D. For each variant, the program counts three things:
spawned: how many goroutines the loop createdran: how many jobs started their workfinished: how many jobs completed without an error
// A: errgroup + SetLimit, loop never looks at ctx, jobs ignore ctx.
g, ctx := errgroup.WithContext(context.Background())
g.SetLimit(limit)
for id := range numJobs {
s.spawned.Add(1)
g.Go(func() error { return job(ctx, id, false, &s) })
}
// B: same loop, but each job selects on ctx.Done() while it sleeps.
// C: the loop checks ctx before each Go.
for id := range numJobs {
if ctx.Err() != nil {
break
}
s.spawned.Add(1)
g.Go(func() error { return job(ctx, id, true, &s) })
}
// D: semaphore.Acquire(ctx) gates the loop, errgroup collects the error.
sem := semaphore.NewWeighted(limit)
for id := range numJobs {
if err := sem.Acquire(ctx, 1); err != nil {
break
}
s.spawned.Add(1)
g.Go(func() error {
defer sem.Release(1)
return job(ctx, id, true, &s)
})
}
A errgroup, ctx ignored elapsed=170ms spawned=24 ran=24 finished=23 err="job 5: bad record" cause="job 5: bad record"
B errgroup, jobs ctx elapsed=40ms spawned=24 ran=24 finished=5 err="job 5: bad record" cause="job 5: bad record"
C errgroup, loop ctx elapsed=40ms spawned=9 ran=9 finished=4 err="job 5: bad record" cause="job 5: bad record"
D semaphore + errgroup elapsed=40ms spawned=9 ran=9 finished=5 err="job 5: bad record" cause="job 5: bad record"
In run A, the group cancelled its context at 40 ms and Wait returned the right error. The program still took 170 ms, the same time as the run with no failure, and all 23 other jobs did their full work. errgroup cancels a context, and a function that never reads that context keeps going. Go never checks the context either. The source of Group.Go is a semaphore send, wg.Add(1) and a goroutine. Nothing in it reads ctx.
Run B fixes the jobs: each one selects on ctx.Done(), so the work stops at 40 ms. But the loop still called Go for all 24 jobs, and 15 of them started after the error only to return context.Canceled at once. With cheap jobs that’s harmless. If each job opens a connection or allocates a buffer before its first context check, it’s 15 wasted setups.
Runs C and D stop the loop itself. In C, a one-line ctx.Err() check before g.Go does it. In D, semaphore.Acquire(ctx, 1) returns the context error as soon as the group cancels, so the loop exits without an extra check. Both spawned 9 goroutines instead of 24. The finished count differs by one (4 against 5) because job 3 ends at the same 40 ms instant as the failure. Its select sees the timer and the cancellation ready together, and Go picks one of the ready cases at random.
The cause= column shows a smaller detail. WithContext builds its context with context.WithCancelCause, so context.Cause(ctx) returns the job’s real error. ctx.Err() still says only context.Canceled. If you log context.Cause(ctx), the code that receives a cancelled context can report why the group stopped.
The channel pool leak that goroutineleak catches
A hand-written channel pool has no error handling at all, and the obvious way to add it introduces a leak. Here’s a version that returns the first error. When a worker hits an error, it reports the error and returns:
func firstError(numJobs, workers int) error {
jobs := make(chan int)
errc := make(chan error, workers)
var wg sync.WaitGroup
for range workers {
wg.Go(func() {
for id := range jobs {
if err := process(id); err != nil {
errc <- err
return
}
}
})
}
go func() {
for id := range numJobs {
jobs <- id // blocks forever once all workers have quit
}
close(jobs)
}()
go func() { wg.Wait(); close(errc) }()
return <-errc
}
func main() {
fmt.Println(runtime.Version())
err := firstError(100, 1)
fmt.Println("firstError returned:", err)
time.Sleep(50 * time.Millisecond)
fmt.Println("goroutines still alive:", runtime.NumGoroutine())
pprof.Lookup("goroutineleak").WriteTo(os.Stdout, 1)
}
The function returns the correct error. But after the last worker quits, the producer goroutine is stuck on jobs <- id, and no goroutine will ever receive from jobs again. Go 1.27 made the goroutineleak profile generally available, so the program can ask the runtime about this directly:
go1.27.4
firstError returned: job 5: bad record
goroutines still alive: 2
goroutineleak profile: total 1
1 @ 0x47d30a 0x41421c 0x413e17 0x4defb8 0x483261
# 0x4defb7 main.firstError.func2+0x37 /tmp/sandbox826119002/src/prog.go:40
Line 40 of the program is the jobs <- id send. The Go 1.27 release notes describe how the detector works: it uses the garbage collector, and it reports a goroutine that is blocked on a channel or lock that no runnable goroutine can reach. The notes also say what it misses. The runtime treats a channel that a global variable can reach as reachable. A pool whose jobs channel lives in a package-level variable therefore leaks without a report. If you import net/http/pprof, the server also exposes the profile at /debug/pprof/goroutineleak. I covered the Go 1.26 experiment flag in the Go 1.26 features walkthrough; on 1.27 you don’t need the flag.
The fix for the pool is the same idea as run C: give the producer a way out.
- Pass a
ctxto the producer. - Make the send a
selectonjobs <- idand<-ctx.Done(). - When the first error arrives, cancel the context.
The Go blog’s pipelines and cancellation article has used that exact pattern since 2014. At that point you’ve written most of errgroup by hand, which is a good argument for the library.
Memory: what a parked goroutine costs
The 24-job test hides the cost of the spawn-then-wait pattern. To measure it, I ran 10,000 jobs of 10 ms each with a limit of 8. A sampler goroutine read runtime.MemStats 5 ms into each run:
go1.27.4
n=10000 tasks, limit=8, sample taken 5ms in:
errgroup.SetLimit goroutines=10 stackInuse= 0.5 MiB
spawn-then-wait goroutines=10002 stackInuse= 20.2 MiB
allocations per task (avg of 20 runs x 1000 tasks):
channel pool 0.02
errgroup.SetLimit 2.00
semaphore.Weighted 4.98
chan semaphore 2.00
That’s about 2 KiB of stack for each parked goroutine, which matches the 2,048-byte stackMin that a new goroutine starts with in the runtime source. At 10,000 jobs, 20 MiB is survivable. The cost grows with the input, though. My first version of this program also ran 100,000 jobs, and the Playground stopped it with timeout running program before it printed the spawn-then-wait line. The errgroup version stayed at 10 goroutines because Go blocks the submit loop, so the input waits in your slice or iterator, which costs nothing extra.
The allocation counts come from testing.AllocsPerRun over a no-op job:
| Pattern | Allocs per job | Where they come from |
|---|---|---|
| Channel pool | 0.02 | Only the pool setup; jobs travel as values on the channel |
errgroup.SetLimit | 2.00 | Two closures per job: the function you pass and the wrapper that Go starts |
| Buffered-channel semaphore, acquired in the loop | 2.00 | Two closures per job, like errgroup, without error handling |
semaphore.Weighted | 4.98 | Two closures, plus about 3 more each time Acquire has to wait: a list element, the waiter stored in it, and a ready channel |
The channel pool is the only design that reuses goroutines, so it’s the cheapest per job. It’s the right choice for code that handles millions of small items per second. For jobs that each do a network call, 2 to 5 allocations per job are too small to measure next to the call itself. For those jobs I’d pick on error semantics.
semaphore.Weighted for jobs of different sizes
The extra allocations of the semaphore pay off when jobs don’t cost the same. Suppose each job holds some memory while it runs and the budget is 100 MB in total. A count-based limit can’t express that, but a weighted one can:
sem := semaphore.NewWeighted(budgetMB) // 100
g, ctx := errgroup.WithContext(context.Background())
tasks := []task{{"a", 30}, {"b", 30}, {"c", 30}, {"big", 90}, {"d", 10}, {"e", 10}, {"f", 10}}
for _, t := range tasks {
if err := sem.Acquire(ctx, t.mb); err != nil {
break
}
mu.Lock()
inUse += t.mb
peak = max(peak, inUse)
fmt.Printf("%-4v acquired %-3s (%2d MB) -> %3d MB in use\n", time.Since(t0), t.name, t.mb, inUse)
mu.Unlock()
g.Go(func() error {
time.Sleep(20 * time.Millisecond) // the task's work
mu.Lock()
inUse -= t.mb
mu.Unlock()
sem.Release(t.mb)
return nil
})
}
g.Wait()
0s acquired a (30 MB) -> 30 MB in use
0s acquired b (30 MB) -> 60 MB in use
0s acquired c (30 MB) -> 90 MB in use
20ms acquired big (90 MB) -> 90 MB in use
20ms acquired d (10 MB) -> 100 MB in use
40ms acquired e (10 MB) -> 20 MB in use
40ms acquired f (10 MB) -> 30 MB in use
done at 60ms, peak 100 MB of 100
Acquire(150) on a 100 MB semaphore: context deadline exceeded
TryAcquire(60): true TryAcquire(60) again: false
The budget never went over 100 MB. Job d shows the cost. At 0 s, 10 MB were free and d needs exactly 10, but it waited until 20 ms because big was ahead of it in line. In this program the loop causes the wait: it acquires in order, so it sits in Acquire for big and never asks for d. If each job called Acquire from its own goroutine, the semaphore would give the same order, because it serves its waiters first-in, first-out on purpose. A comment in semaphore.go explains why: if small requests could go ahead of large ones, the large ones would starve. Its example is a writer that needs all N tokens while readers keep taking one each. In this run the total time didn’t suffer. With one long, heavy job in the queue, everything behind it waits.
The last two lines show two edges of the API. A weight larger than the semaphore’s size never succeeds: Acquire blocks until the context ends and only then returns the context’s error. Without a deadline it blocks forever. Before you call Acquire, check the weight against the size. TryAcquire is the non-blocking form for load shedding. errgroup has the same idea in TryGo, which starts the function only if the group is below its limit.
What errgroup does with a panic
A panic in a job takes down the whole process, whichever pattern you use. In this test, one of two errgroup jobs writes to a nil map, and main has a deferred recover():
func main() {
defer func() { fmt.Println("recovered in main:", recover() != nil) }()
var g errgroup.Group
g.Go(func() error {
var m map[string]int
m["boom"]++ // nil map write
return nil
})
g.Go(func() error { time.Sleep(time.Second); return nil })
fmt.Println("Wait returned:", g.Wait())
}
With x/sync v0.25.0:
panic: assignment to entry in nil map
goroutine 21 [running]:
main.main.func2()
/tmp/sandbox3174964907/src/main.go:15 +0x28
golang.org/x/sync/errgroup.(*Group).Go.func1()
/tmp/gopath211130848/pkg/mod/golang.org/x/sync@v0.25.0/errgroup/errgroup.go:93 +0x50
created by golang.org/x/sync/errgroup.(*Group).Go in goroutine 1
/tmp/gopath211130848/pkg/mod/golang.org/x/sync@v0.25.0/errgroup/errgroup.go:78 +0xa5
Wait never returned, and the recover() in main didn’t help, because a panic can only be recovered in the goroutine that panics. Then I changed one line in go.mod to x/sync v0.15.0 and ran the program again. It printed recovered in main: true. Versions v0.14.0 and v0.15.0 (April and May 2025) caught panics in Go and re-raised them from Wait. The Go team removed that in v0.16.0 on June 20, 2025, and closed issue #53757. A comment in today’s Group.Go gives three reasons:
- Re-raising delays the panic, which makes bugs harder to find.
- It turns the panic stack into a plain value that crash monitors can’t see.
- It can deadlock if the panic stops the program from ever reaching
Wait.
Some code from early 2025 relies on Wait re-panicking. For that code, an x/sync upgrade changes the crash behavior. To turn a panic in one job into an error, wrap the job body in your own function. In that function, use a defer that calls recover() and returns the value as an error. The decision then stays visible in your code.
Which one should you use?
| Situation | Pick | Why |
|---|---|---|
| Batch of independent jobs that can fail (fetch N URLs, resize N images) | errgroup.WithContext + SetLimit | First error, cancellation and the limit in one type; add a ctx.Err() check in the loop |
| Endless stream from a queue, socket or Kafka topic | Channel pool | Long-lived workers, per-worker state, 0.02 allocs per job |
| Jobs with different costs (memory, tokens, API quota) | semaphore.Weighted + errgroup | Weighted admission, and Acquire(ctx) stops the loop on cancel |
| Shed load when busy, don’t queue | TryGo or TryAcquire | Returns false immediately when the limit is full |
| Fire-and-forget fan-out with no errors to collect | sync.WaitGroup.Go + a buffered channel semaphore acquired in the loop | Smallest code; acquire the slot in the loop, before wg.Go |
My default for request-scoped work in a service is errgroup.WithContext with SetLimit. It’s the only option where the obvious code also handles the first error and cancellation. I’d add the ctx.Err() check to the submit loop every time, because run A shows what happens without it. The channel pool is still the right tool for daemons and pipelines. If you build one, run its error path under a test that reads the goroutineleak profile.
Python has the same split. If you write both languages, the asyncio TaskGroup vs gather comparison runs the equivalent cancel-on-error experiment, and the asyncio Queue worker pool tutorial builds the Python version of the channel pool with backpressure. For the rest of the modern Go toolbox, the modern Go guide collects the language and tooling changes from 1.22 onward.
FAQ
What is the difference between errgroup and WaitGroup in Go?
sync.WaitGroup only waits for goroutines to finish. errgroup.Group also collects the first non-nil error that a function returns, and with errgroup.WithContext it cancels a shared context when that error happens. errgroup also has SetLimit to bound concurrency, which WaitGroup doesn’t have. Internally, errgroup.Group is a WaitGroup, a sync.Once for the error and an optional buffered channel for the limit.
What does errgroup SetLimit do?
SetLimit(n) makes Go block while n goroutines from the group are active. It arrived together with TryGo through issue #27837, closed in May 2022. A negative value removes the limit. A limit of zero blocks every call. Before the group starts work, set the limit. Changing it while goroutines are active panics with “errgroup: modify limit while N goroutines in the group are still active”.
How do I limit the number of goroutines in Go?
Make the submit loop wait for a free slot before it creates the goroutine. errgroup.SetLimit, semaphore.Weighted.Acquire in the submit loop, or a fixed channel pool all do this. A buffered channel that each goroutine fills after it starts limits only the concurrent work, and the goroutine count still equals the job count. In the test above, that version held 10,002 goroutines for 10,000 jobs.
Does errgroup return all errors?
No. Wait returns only the first non-nil error. To keep every error, store each job’s error in its own slot of a slice, indexed by job ID, so no lock is needed. After Wait returns, call errors.Join on the slice.
Does errgroup recover panics?
Not in current versions. x/sync v0.14.0 and v0.15.0 re-raised a job’s panic from Wait. v0.16.0 removed this in June 2025, and v0.25.0 lets the panic crash the process, as the run above shows.
Sources
errgrouppackage documentation and source:Go,TryGo,SetLimit,WithContext, and the comment on panic propagationsemaphorepackage documentation and source:Acquire,TryAcquire, FIFO waiters- Go issue #27837: the proposal that added
TryGoandSetLimit, closed May 2022 - Go issue #53757: panic and Goexit propagation through
Wait, closed June 20, 2025 - Go 1.25 release notes:
sync.WaitGroup.Goand thewaitgroupvet analyzer - Go 1.27 release notes: the
goroutineleakprofile and its detection limits runtime/stack.go:stackMin = 2048, the starting goroutine stack- Go Concurrency Patterns: Pipelines and cancellation: the Go blog’s explanation of producer leaks and the
selectondonefix golang.org/x/syncon the module proxy: v0.25.0 release date
Bottom line
All three patterns bound concurrency correctly. The differences are in what happens around the limit: whether the submit loop stops after an error, whether goroutines pile up waiting, and whether the error path leaks. errgroup.SetLimit gets two of those right by default, and one ctx.Err() check fixes the third. The channel pool is faster per job and leaks on the first naive error path. semaphore.Weighted is the tool for jobs with unequal costs, as long as you remember the FIFO queue and the oversized weight that blocks forever. I’d choose on error behavior first: in these tests, the largest gap in elapsed time was 10 ms between the patterns, and 130 ms between run A and the runs that checked the context.