Why Your Go Worker Pool Deadlocks: An Unbuffered Channel Post-Mortem
Here is a worker pool that worked fine in testing, passed code review, and then locked up in production the moment someone fed it more than a handful of jobs:
func process(jobs []Job) []Result {
jobCh := make(chan Job)
resultCh := make(chan Result)
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobCh {
resultCh <- doWork(job)
}
}()
}
for _, j := range jobs {
jobCh <- j
}
close(jobCh)
wg.Wait()
close(resultCh)
var results []Result
for r := range resultCh {
results = append(results, r)
}
return results
}
Run it with three jobs and it hangs forever. The runtime eventually notices and prints:
fatal error: all goroutines are asleep - deadlock!
There's no panic in doWork, no race, and nothing you'd catch with go vet. It goes silent, then crashes. It's worth working through why, because the bug is structural rather than a typo, and the same shape turns up in a lot of hand-rolled pool code.
An unbuffered channel is a rendezvous, not a queue
An unbuffered channel has no storage. A send on it doesn't complete until some goroutine is doing a matching receive at that exact moment. So resultCh <- doWork(job) reads less like "hand this result off and carry on" and more like "block here until someone reads it".
On its own, that's fine. The trouble is who is supposed to be doing the reading.
Tracing the wedge step by step
Walk through process with, say, three jobs and four workers:
- The main goroutine starts sending jobs into
jobCh. Workers pick them up as fast as they're sent, sincejobChis also unbuffered and a worker is usually waiting on it. - A worker finishes
doWorkand triesresultCh <- .... Nobody is receiving fromresultChyet, because the main goroutine is still in the loop sending jobs, not in the loop reading results. The worker blocks. - If enough workers finish before the main goroutine has sent all jobs, every worker ends up parked on
resultCh <- .... None of them can go back torange jobChto accept the next job. - The main goroutine is stuck trying to send the next job into
jobCh, because there's no worker free to receive it.
Now everyone is asleep waiting on someone else:
- the main goroutine wants a worker to receive a job
- the workers want the main goroutine to receive a result
- the main goroutine won't get to the result-reading loop until it has finished sending every job
That's the deadlock, and it's a genuine circular wait rather than a timing fluke. Whether it triggers depends only on whether a worker manages to produce a result before the job-sending loop finishes. Which is how it can pass a quick smoke test with two jobs and fail immediately with twenty.
The fix: dispatch and collection must never block each other
Once you've seen the trap, the rule is simple: dispatching and collecting have to run concurrently whenever the channel connecting them is unbuffered. The standard shape drains results in a separate goroutine and uses sync.WaitGroup purely to know when it's safe to close the results channel:
func process(jobs []Job) []Result {
jobCh := make(chan Job)
resultCh := make(chan Result)
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobCh {
resultCh <- doWork(job)
}
}()
}
go func() {
for _, j := range jobs {
jobCh <- j
}
close(jobCh)
}()
go func() {
wg.Wait()
close(resultCh)
}()
var results []Result
for r := range resultCh {
results = append(results, r)
}
return results
}
Now the main goroutine does one thing: range over resultCh. So there's always someone ready to receive the moment a worker sends.
Dispatch happens on its own goroutine, so it can block on jobCh <- without stopping anyone reading results. The wg.Wait() that closes resultCh gets its own goroutine too. Calling it inline in the main goroutine (right after the dispatch loop, as in the original) would put you back where you started, with result-collection waiting for dispatch to finish.
That's the whole fix: three goroutines doing one thing each, and none of them can block the others out of the loop.
A buffered channel just moves the deadlock to later
A common first instinct is to make resultCh buffered:
resultCh := make(chan Result, 100)
This really does make the deadlock disappear for a workload of 100 jobs or fewer, and that's what makes it a dangerous fix. The circular dependency between dispatch and collection is still there; the buffer just has enough slack to absorb it, up to a point.
Feed the same code 101 jobs, or run it on a slower path where doWork finishes faster relative to dispatch, and it wedges again in the same way, only later. You've swapped a reliable, fast-failing bug for an intermittent, load-dependent one, which is worse.
It'll pass CI, pass staging, and then show up in production traffic six months from now when volume finally crosses the buffer size. Once the structural fix is in, adding a buffer for throughput is a legitimate tuning decision. Using one to paper over a blocking cycle isn't.
Actually, the deadlock detector only catches the total case
Hang on, this bit is interesting: the Go runtime's "all goroutines are asleep" detector only fires when literally every goroutine in the process is blocked. If your worker pool is embedded in a larger service with an HTTP server or other goroutines still running, the same circular wait won't crash the process at all.
The pool goroutines just sit there forever, leaked, each holding on to a few kilobytes and never returning. You'll see it as a slow memory climb and a request that never completes, with nothing in the logs pointing at channels.
go tool pprof on the goroutine profile, or just GODEBUG=schedtrace, is usually how people find this in the wild. By the time it's visible in production, there's no standalone reproduction to run the deadlock detector against.