Tuesday, December 1, 2026
HomeGolangShutting down a employee pool with out leaking goroutines - a guidelines...

Shutting down a employee pool with out leaking goroutines – a guidelines that lastly caught – Technical Dialogue


I inherited a service with a fan-out pool: one producer, N staff, and a shutdown path that solely closed the enter channel. Below load it left goroutines behind each deploy, and pprof confirmed them slowly piling up.

The repair is just not unique, however writing it down helped greater than any single patch:

1. Derive a context with cancel in major and go it all over the place.

2. choose on ctx.Executed() within the employee obtain, not simply on the channel.

3. Cancel earlier than closing the enter, not after.

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

5. A check that runs the pool 200 occasions and asserts runtime.NumGoroutine comes again to baseline.

I used an AI terminal to get from the damaged model to that record. Studying the precise package deal mattered: it adopted the mission’s present errgroup utilization as a substitute of handing me a naked WaitGroup, and it wrote the check in the identical desk fashion as the remainder of the file.

The place it guessed flawed: it put the cancel name inside a defer within the employee, which fires too late. I moved it to the proprietor of the pool.

Mannequin selection: low cost one for the check and feedback, stronger one when reasoning about ordering. darkmind.chat reveals the fee earlier than every request, so making an attempt two fashions on the identical diff is a couple of cents, not a subscription.

What does your shutdown guidelines appear to be? Mine is above, and I’d slightly steal a greater one than defend it.

One addition: make the producer’s exit a part of the shutdown contract. Sign it to cease, wait till it has completed sending, shut the enter, then cancel the employees. In any other case staff can block on outcome paths or drain a channel that’s nonetheless being fed. Additionally run the repeated shutdown check underneath the race detector; goroutine counts catch leaks, however not each shutdown race. Holding the leftover-stack dump behind a check flag is helpful so regular shutdown logs keep quiet.

The step about ready for the producer to complete first actually helped me. I used to shut the enter channel immediately after which surprise why a employee was nonetheless blocked. Working the shutdown check in a loop additionally caught a flaky case for me {that a} single run missed.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments