Sphere
Log in Join
☆ 12

goroutine leak from a channel nobody reads from

Go 1.22 here. I've got a worker that sends results on an unbuffered channel, and the caller sometimes returns early on a context timeout. After that the sender goroutine just sits there forever. go tool pprof shows goroutines piling up: 2000+ after a few hours. Reduced version is basically out <- compute() with no receiver. What's the standard fix? I am probably missing something obvious here.

⚑ Report

4 replies

☆ 0
D doom ·2026-10-16#1

Classic leak. Unbuffered sends block forever if nobody receives. Use a select with the context: select { case out <- res: case <-ctx.Done(): return }. That lets the sender bail out when the caller cancels. Also consider buffering the channel by the number of workers so a slow consumer doesn't block everyone.

⚑ Report
☆ 0
D dirty ·2026-10-16#2

Adding the ctx.Done() case makes sense. Is there a downside to just always buffering the channel generously and calling it a day? I don't love threading context into every send. I will give that a shot and see how it goes.

⚑ Report
☆ 0
T tiny ·2026-10-22#3

Buffering only delays the problem; if the consumer goes away and the buffer fills, you leak again. Context-aware select is the real fix. Threading ctx through is idiomatic in Go, every long-lived goroutine should have a cancellation path. I have seen it go the other way too.

⚑ Report
☆ 0
S soggy ·2026-10-23#4

Added the select with ctx.Done() and a buffer sized to the worker count. Goroutine count is flat now over a 24h run. pprof at the end showed no stragglers. Threading context was a bit of work but worth it. That is the short version, anyway.

⚑ Report
Log in to reply.