Skip to content

Lesson 6 of 9 · 27m

Worker Pools Without Leaks or Thundering Herds

Build bounded worker pools with clean shutdown, bounded queues, result propagation, and cancellation-aware job processing.

Every senior Go engineer eventually writes a worker pool. Most first versions are too clever: dynamic resizing, priority lanes, generic callbacks, graceful drain, metrics, and a subtle deadlock that appears only during deploys. A production worker pool is not a framework. It is a bounded amount of concurrency wrapped around a clear job lifecycle.

Start with lifecycle states

submit -> start -> finish  accepted, running, result recorded
shutdown                 intake closes; drain or cancel in-flight work
close                    workers exited and resources released

A small correct pool

func NewPool(ctx context.Context, workers, queue int) *Pool {
    p := &Pool{jobs: make(chan Job, queue)}
    p.wg.Add(workers)
    for i := 0; i < workers; i++ {
        go func() {
            defer p.wg.Done()
            for job := range p.jobs { job.Do(ctx) }
        }()
    }
    return p
}

Submission should expose backpressure

func (p *Pool) Submit(ctx context.Context, job Job) error {
    select {
    case p.jobs <- job: return nil
    case <-ctx.Done(): return ctx.Err()
    }
}

A bounded wait is often better than an instant drop. If you add default, you are making a load-shedding decision; test that behavior instead of discovering it during traffic spikes.

Shutdown has two phases

Close intake, then wait with a deadline:

close(p.jobs)
done := make(chan struct{})
go func() { p.wg.Wait(); close(done) }()
select {
case <-done:
case <-time.After(10 * time.Second): cancelWorkers()
}

Field notes

  • Never close the job channel twice. If multiple submitters exist, one owner controls close.
  • Jobs that fork untracked goroutines defeat the pool's concurrency bound.
  • Recover panics at the worker boundary, record job failure, and keep the worker alive if the design permits.
  • Size pools against the real constraint: database connections, CPU cores, downstream rate limits, or memory per job — not vibes. Jobs need idempotency or durable acknowledgment because a pool is not a transactional queue.

Was this lesson helpful?

Sign in to rate