Shutting down a worker pool without leaking goroutines - a checklist that finally stuck

I inherited a service with a fan-out pool: one producer, N workers, and a shutdown path that only closed the input channel. Under load it left goroutines behind every deploy, and pprof showed them slowly piling up.

The fix is not exotic, but writing it down helped more than any single patch:

1. Derive a context with cancel in main and pass it everywhere.

2. select on ctx.Done() in the worker receive, not just on the channel.

3. Cancel before closing the input, not after.

4. WaitGroup.Wait with a deadline, then log the stacks of leftovers.

5. A test that runs the pool 200 times and asserts runtime.NumGoroutine comes back to baseline.

I used an AI terminal to get from the broken version to that list. Reading the actual package mattered: it followed the project’s existing errgroup usage instead of handing me a bare WaitGroup, and it wrote the test in the same table style as the rest of the file.

Where it guessed wrong: it put the cancel call inside a defer in the worker, which fires too late. I moved it to the owner of the pool.

Model choice: cheap one for the test and comments, stronger one when reasoning about ordering. darkmind.chat shows the cost before each request, so trying two models on the same diff is a few cents, not a subscription.

What does your shutdown checklist look like? Mine is above, and I would rather steal a better one than defend it.

One addition: make the producer’s exit part of the shutdown contract. Signal it to stop, wait until it has finished sending, close the input, then cancel the workers. Otherwise workers can block on result paths or drain a channel that is still being fed. Also run the repeated shutdown test under the race detector; goroutine counts catch leaks, but not every shutdown race. Keeping the leftover-stack dump behind a test flag is useful so normal shutdown logs stay quiet.