Skip to Content
Skip to content
Bound Concurrency in Go With a Fixed Worker Pool
Advanced
Tutorials

Bound Concurrency in Go With a Fixed Worker Pool

Stop spawning an unbounded goroutine per job and build a fixed-size worker pool in Go with bounded channels, context cancellation, and predictable memory usage. After this, spikes in work queue up cleanly instead of exhausting file descriptors or RAM.

Updated 5 min read GoConcurrency

Spawning a new goroutine for every incoming job feels free until a sudden burst of 50,000 webhook events hits your service at once. Even though each goroutine starts with a small stack, 50,000 concurrent network calls will exhaust file descriptors, saturate database connection pools, and spike memory until the kernel OOM-kills the process.

A fixed worker pool puts a hard ceiling on concurrency. Instead of launching one goroutine per item, you launch N long-lived workers that pull jobs from a shared channel and stop cleanly when the channel closes or a context.Context is canceled.

Skip ahead

Already comfortable with sync.WaitGroup and channels? Jump straight to the cancellation-safe pool pattern or the common mistakes section.

The two halves of a Go worker pool

Every bounded worker pool has two moving parts that must agree on shutdown:

  • Workers (consumers): A fixed number of goroutines ranging over a jobs channel, tracked by a sync.WaitGroup.
  • Producer (feeder): A loop that sends jobs into the channel and calls close(jobs) once every job is queued—or earlier if the context is canceled.
package main

import (
	"context"
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

func runPool(ctx context.Context, workers int, jobs []int) int64 {
	ch := make(chan int)
	var done atomic.Int64
	var wg sync.WaitGroup

	for range workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := range ch {
				select {
				case <-ctx.Done():
					return
				case <-time.After(10 * time.Millisecond):
					_ = j
					done.Add(1)
				}
			}
		}()
	}

	for _, j := range jobs {
		select {
		case ch <- j:
		case <-ctx.Done():
			close(ch)
			wg.Wait()
			return done.Load()
		}
	}
	close(ch)
	wg.Wait()
	return done.Load()
}

func main() {
	jobs := make([]int, 20)
	for i := range jobs {
		jobs[i] = i + 1
	}
	start := time.Now()
	n := runPool(context.Background(), 4, jobs)
	fmt.Printf("completed=%d elapsed>=40ms=%v\n", n, time.Since(start) >= 40*time.Millisecond)

	ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond)
	defer cancel()
	partial := runPool(ctx, 4, jobs)
	fmt.Printf("canceled_early completed<20=%v (%d)\n", partial < 20, partial)
}

Running this with the race detector on Go 1.27:

$ go run -race .
completed=20 elapsed>=40ms=true
canceled_early completed<20=true (8)

With 20 jobs taking 10 ms each across 4 workers, the full run takes 5 batches (~50 ms). When the 25 ms timeout fires, the producer stops feeding jobs on case <-ctx.Done():, closes the channel so idle workers exit, and waits for in-flight workers before returning 8.

Diagram showing a producer feeding a bounded jobs channel consumed by fixed Go workers
A fixed worker pool bounds active sockets and memory regardless of burst size.

Unbuffered vs. buffered job channels

Channel choice Backpressure behavior Best used when
make(chan Job) (unbuffered) Producer blocks until a worker picks up the job You want tight memory bounds and immediate cancellation
make(chan Job, workers*2) Producer can queue a small batch ahead of workers Jobs arrive in short bursts and you want to keep workers fed
make(chan Job, len(jobs)) Queues everything in RAM up front All jobs are already in memory and you just want a cap on execution

💡 Tip

If your workers only need to limit concurrency on an existing slice—and you do not need streaming results—errgroup.SetLimit(n) from golang.org/x/sync/errgroup gives you a bounded pool with built-in error propagation and context cancellation in five lines of code.

Collecting results without deadlocking

If each worker writes a result to a results channel, never wait on wg.Wait() in the same goroutine before draining results. If the results channel fills up, workers block trying to send, wg.Wait() blocks waiting for workers to finish, and the whole program deadlocks.

Close results from a tiny helper goroutine instead:

go func() {
	wg.Wait()
	close(results)
}()

for res := range results {
	// safe: results closes only after every worker exits
}

Common mistakes

  • Sending without <-ctx.Done(): Writing ch <- job without a select hangs the producer goroutine forever if all workers exit early on cancellation.
  • Closing the channel from a worker: Only the producer knows when no more jobs will arrive. Closing from a worker causes a panic on the next send or a double-close panic.
  • Calling wg.Add(1) inside the goroutine: Always call wg.Add(1) in the spawning loop before go func(), so wg.Wait() cannot race ahead of a worker that has not started yet.

⚠ Warning

Do not pick a worker count like 1000 blindly for CPU-bound work. For pure computation, match runtime.GOMAXPROCS(0); larger pools only add scheduler overhead. Save larger worker counts (16–64) for network or disk I/O where workers spend most of their time waiting.

What happens if you skip this

Without a concurrency bound, traffic spikes translate directly into thousands of simultaneous database queries, TLS handshakes, and open sockets. Your service either runs out of memory under load or triggers cascading timeouts against downstream dependencies.

Related course: Go Advanced.

About

Stop spawning an unbounded goroutine per job and build a fixed-size worker pool in Go with bounded channels, context cancellation, and predictable memory usage. After this, spikes in work queue up cleanly instead of exhausting file descriptors or RAM.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
5 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.