Production Go Concurrency: Worker Pools & Cancellation
This deep-dive covers go concurrency worker pool pattern with actionable analysis, practical implications, and expert insights.
Why Unbounded go func() Breaks Production Linux Services
Goroutines are cheap (~2 KB initial stack), which tempts developers into writing for _, item := range items { go process(item) }. On a 10-item test list, that works fine. When a production batch contains 50,000 URLs or database records, unbounded goroutines immediately exhaust Linux file descriptors (too many open files), saturate PostgreSQL connection limits, and trigger OOM kills. A bounded worker pool with context cancellation gives you predictable throughput, backpressure, and clean shutdowns.
Complete Leak-Free Bounded Worker Pool in Go 1.23
Save this runnable example as main.go. It processes jobs across a fixed pool of workers, respects SIGINT/SIGTERM via signal.NotifyContext, cancels cleanly on the first fatal error, and guarantees zero leaked goroutines:
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"runtime"
"sync"
"syscall"
"time"
)
type Job struct {
ID int
Payload string
}
type Result struct {
JobID int
Out string
Err error
}
func runPool(ctx context.Context, workers int, jobs []Job) ([]Result, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
jobCh := make(chan Job)
resCh := make(chan Result, workers)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case job, ok := <-jobCh:
if !ok {
return
}
out, err := processJob(ctx, job)
select {
case resCh <- Result{JobID: job.ID, Out: out, Err: err}:
case <-ctx.Done():
return
}
}
}
}(w)
}
// Producer goroutine feeds jobs and closes jobCh cleanly
go func() {
defer close(jobCh)
for _, job := range jobs {
select {
case jobCh <- job:
case <-ctx.Done():
return
}
}
}()
// Close resCh once all workers finish
go func() {
wg.Wait()
close(resCh)
}()
results := make([]Result, 0, len(jobs))
for res := range resCh {
if res.Err != nil {
cancel() // Stop remaining work immediately
return results, res.Err
}
results = append(results, res)
}
if err := ctx.Err(); err != nil && !errors.Is(err, context.Canceled) {
return results, err
}
return results, nil
}
func processJob(ctx context.Context, job Job) (string, error) {
select {
case <-time.After(15 * time.Millisecond):
return fmt.Sprintf("processed-%d:%s", job.ID, job.Payload), nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
jobs := make([]Job, 40)
for i := range jobs {
jobs[i] = Job{ID: i + 1, Payload: "event"}
}
start := time.Now()
results, err := runPool(ctx, 8, jobs)
fmt.Printf("Completed %d jobs in %v (err=%v, goroutines=%d)\n",
len(results), time.Since(start).Round(time.Millisecond), err, runtime.NumGoroutine())
}
Alternative: Concise Bounded Concurrency with errgroup.SetLimit
When you do not need multi-stage channel streaming, golang.org/x/sync/errgroup implements bounded fan-out with automatic error propagation in 15 lines:
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(8) // Cap active goroutines to 8
for _, job := range jobs {
job := job
g.Go(func() error {
_, err := processJob(gctx, job)
return err
})
}
if err := g.Wait(); err != nil {
return err
}
Testing for Data Races and Goroutine Leaks
Always run Go's built-in race detector in local development and CI pipelines:
go run -race main.go
go test -race -count=5 ./...
Summary
Bounded worker pools and errgroup.SetLimit paired with context.Context turn Go concurrency into a predictable, leak-free workhorse for Linux backend services. Respecting ctx.Done() on every channel operation guarantees instant cancellation and zero orphaned goroutines during deployments.
Was this technical analysis helpful?
Your feedback informs our benchmark updates and ongoing article audits.
FAQ
Frequently Asked Questions
Structured for search engines and AI answer systems (AEO/GEO).
Use errgroup.WithContext + g.SetLimit(n) for simple fan-out jobs where you want automatic fail-fast cancellation on the first error. Use explicit channel pipelines when streaming continuous jobs or transforming data across multiple stages.
For CPU-bound tasks (hashing, compression, parsing), match runtime.GOMAXPROCS(0). For I/O-bound tasks (HTTP calls, database queries), size workers to match your downstream connection pool or rate limit (typically 10 to 64).
The most common cause is a worker blocked forever trying to send a result to an unbuffered channel after the consumer returned early on an error. Selecting on ctx.Done() or using a buffered error channel eliminates the leak.
Use go.uber.org/goleak inside TestMain or individual tests, and always run go test -race to verify thread safety.
More answers in our FAQ hub.
Newsletter
Practical Linux & Applied AI Newsletter
Get new tested tutorials and benchmark comparisons delivered directly to your inbox. Zero spam.
Join Weekly guides readers getting our weekly digest.
- Practical Linux administration & terminal workflows
- Tested open-source AI setups & benchmarks
- Zero spam - unsubscribe anytime