Worker pool
A worker pool is a fixed number of goroutines that pull jobs from a channel (or from errgroup with a limit). It caps concurrency so you do not start one goroutine per item when the item count is unbounded.
Detailed Explanation
for _, job := range jobs { go work(job) } is simple and dangerous when jobs is a million URLs. Each goroutine has a stack and will try to do I/O at once. A pool starts N workers. A channel of jobs feeds them. When the jobs channel closes, workers return. A WaitGroup or errgroup waits for the workers, not for each job's goroutine.
The skeleton. jobs := make(chan Job), start N loops for j := range jobs { handle(j) }, send all jobs, close(jobs), wait. Buffer the jobs channel if producers should not block on a slow start, but the real cap is N, not the buffer.
errgroup.SetLimit is a pool without a jobs channel: each Go is a job, and only N run at once. Use it when jobs are closures you already have. Use a channel when jobs are data (URLs, IDs) produced separately from the workers.
Backpressure. If the producer is faster than N workers, a buffered jobs channel fills and then the producer blocks. That is what you want next to a database with a max connection count.
What it costs. Too small N underuses CPU and I/O. Too large N overwhelms a dependency. Start with the dependency's limit (DB pool size, API rate) and measure. A pool is not a substitute for context cancel: workers should take ctx and return when it is done.
Code Examples
package main
import "sync"
func run(n int, jobs <-chan int, fn func(int)) {
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobs {
fn(j)
}
}()
}
wg.Wait()
}
func main() {
jobs := make(chan int)
go func() {
for i := 0; i < 10; i++ {
jobs <- i
}
close(jobs)
}()
run(4, jobs, func(int) {})
}Common Gotchas
Unbounded `go` per job is not a pool
it is a stampede.
A huge jobs buffer hides overload until memory grows
keep the buffer modest.
Forgetting to close `jobs` leaves workers in `range` forever
Forgetting to close `jobs` leaves workers in `range` forever
Panic in a worker still crashes the process unless recovered
Panic in a worker still crashes the process unless recovered