Bound Concurrency With a Worker Pool
Limit active goroutines using a fixed worker pool reading from a jobs channel and respecting context cancellation. After this, spikes in work will not exhaust file descriptors or memory.
Course content
Sign in to save your progress.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
Imagine your monitoring service needs to health-check 5,000 customer webhook URLs every minute. The naive Go loop spawns one goroutine per URL:
// Naive: fine for 10 URLs, explodes at 5,000
for _, u := range urls {
go check(u)
}
For 10 URLs in local dev, that finishes in 50 ms. For 5,000 URLs in production, you just started 5,000 simultaneous TCP/TLS handshakes—hitting OS file-descriptor limits (too many open files), saturating ephemeral ports, and spiking memory across thousands of TLS buffers. A fixed worker pool caps active workers at a predictable number (say, 16) no matter how huge the incoming burst is.
Skip ahead
If you already build cancellation-safe worker pools without result-channel deadlocks and know when errgroup.SetLimit is simpler, continue to "Coordinate Shared State With sync.Mutex and atomic."
Experiment 1: A real concurrent HTTP health checker
Look at the three distinct goroutine roles in checkURLs: a feeder goroutine sends URLs into jobs (stopping early if ctx.Done() fires) and closes jobs; N fixed workers pull from jobs and push CheckResult values to results; and a tiny closer goroutine waits on wg.Wait() before closing results:
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"time"
)
type CheckResult struct {
URL string
Status int
Err error
}
func checkURLs(ctx context.Context, client *http.Client, workers int, urls []string) []CheckResult {
jobs := make(chan string)
results := make(chan CheckResult)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for u := range jobs {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
results <- CheckResult{URL: u, Err: err}
continue
}
resp, err := client.Do(req)
if err != nil {
results <- CheckResult{URL: u, Err: err}
continue
}
resp.Body.Close()
results <- CheckResult{URL: u, Status: resp.StatusCode}
}
}()
}
go func() {
defer close(jobs)
for _, u := range urls {
select {
case jobs <- u:
case <-ctx.Done():
return
}
}
}()
go func() {
wg.Wait()
close(results)
}()
var out []CheckResult
for r := range results {
out = append(out, r)
}
return out
}
func main() {
okSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(15 * time.Millisecond)
w.WriteHeader(http.StatusOK)
}))
defer okSrv.Close()
badSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
}))
defer badSrv.Close()
urls := []string{okSrv.URL, badSrv.URL, okSrv.URL, okSrv.URL, badSrv.URL, okSrv.URL}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
res := checkURLs(ctx, &http.Client{Timeout: 100 * time.Millisecond}, 3, urls)
up, down := 0, 0
for _, r := range res {
if r.Status == 200 {
up++
} else {
down++
}
}
fmt.Printf("checked=%d up=%d down=%d\n", len(res), up, down)
}
$ go run -race .
checked=6 up=4 down=2
Experiment 2: Tracing the classic result-channel deadlock
Beginners frequently write wg.Wait(); close(results) directly inside checkURLs right before for r := range results. Trace step by step what freezes when you do that:
- Worker 1 finishes checking URL 1 and tries to execute
results <- CheckResult{...}. - Because
resultsis unbuffered, Worker 1 blocks untilcheckURLsentersfor r := range results. - Meanwhile,
checkURLsis stuck onwg.Wait()waiting for Worker 1 to exit! - Every goroutine waits on another, and Go aborts with
fatal error: all goroutines are asleep - deadlock!.
Moving wg.Wait(); close(results) into a tiny helper goroutine lets for r := range results start draining immediately, and closes results only once the final worker has exited.
Experiment 3: When errgroup.SetLimit replaces a manual pool
If all jobs are already in a slice and you want bounded concurrency plus automatic first-error cancellation, golang.org/x/sync/errgroup gives you a bounded pool in five lines without managing channels at all:
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(16) // at most 16 active goroutines at once
for _, u := range urls {
g.Go(func() error {
return checkOne(gctx, client, u)
})
}
if err := g.Wait(); err != nil {
return err
}
Experiment 4: Picking worker count by workload
- CPU-bound work (compression, hashing, JSON parsing): Set workers to
runtime.GOMAXPROCS(0). Launching 200 workers on a 4-core box only adds scheduler overhead. - I/O-bound work (HTTP APIs, DB queries, S3 uploads): Size workers to what the downstream system can safely absorb (typically
8–64)—never more than your DB pool or vendor rate limit allows.
Common mistakes
- Sending into
jobswithoutcase <-ctx.Done():: Hangs the feeder goroutine forever if all workers exit early on cancellation. - Closing
jobsfrom inside a worker: Only the producer knows when no more jobs remain; closing from a worker panics on the next send or double-close. - Picking
workers = 1000blindly: Defeats the point of bounding concurrency and triggers downstream rate limits or port exhaustion.
💡 Tip
Buffer jobs lightly (make(chan string, workers*2)) if your producer fetches jobs in batches—that keeps workers fed smoothly while keeping memory tightly bounded.
What happens if you skip this step
Unbounded goroutines turn every traffic spike into an instant self-DDoS against your own databases, file descriptors, and third-party APIs.
In checkURLs, why does placing wg.Wait(); close(results) synchronously before for r := range results trigger a deadlock on the very first completed URL?
About
Limit active goroutines using a fixed worker pool reading from a jobs channel and respecting context cancellation. After this, spikes in work will not exhaust file descriptors or memory.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.