Finding Leaked Goroutines in Go with pprof
A common goroutine leak with unbuffered channels and timeouts in Go, how pprof showed it on one service, and how to avoid it.
· 2 min read · Erik Kubica
One of the nicest things about Go is how easy concurrency feels. You prepend go to a function call, as in go worker(), and the runtime starts a lightweight goroutine. No thread pools to configure, no async/await state machines to untangle.
That ease can hide problems. On one project, a production API slowly crept from 40 MB of RAM to 3.8 GB over three weeks, until the Linux out-of-memory killer terminated the service at 4:00 AM.
I spent a weekend in 2022 tracking it down. It wasn't a memory leak in the C sense. It was about 42,000 goroutines stuck in memory.
A Bug That's Easy to Write
Here is a goroutine leak pattern I've run into more than once in code reviews, and in my own code:
func queryWithTimeout(ctx context.Context) (string, error) {
ch := make(chan string) // Unbuffered channel!
go func() {
// Slow external API or database call
result := slowExternalFetch()
ch <- result // BLOCKS FOREVER if receiver timed out!
}()
select {
case res := <-ch:
return res, nil
case <-time.After(500 * time.Millisecond):
return "", errors.New("request timed out")
}
}
The trap is easy to miss.
If slowExternalFetch() takes 600 milliseconds, the select statement hits the timeout case and returns an error. The caller moves on.
One hundred milliseconds later, slowExternalFetch() finishes and executes ch <- result.
Because ch is unbuffered, sending blocks until another goroutine reads from it. But there is no receiver anymore, since the parent function has already returned.
That goroutine stays blocked on ch <- result indefinitely. The garbage collector can't free it because the goroutine is still alive, so its 2 KB stack, its local variables, and whatever it closed over stay in memory.
Finding Them with pprof
First, expose runtime metrics on an internal router using net/http/pprof:
import _ "net/http/pprof"
func main() {
// Internal debug listener on private interface
go http.ListenAndServe("127.0.0.1:6060", nil)
// Run normal API...
}
When you suspect memory growth, check the live goroutine count:
$ curl -s http://127.0.0.1:6060/debug/pprof/goroutine?debug=1 | head -n 4
goroutine profile: total 42180
42100 @ 0x43a290 0x449b20 0x5a18c0 0x46e101
at 0x5a18bf main.queryWithTimeout.func1+0x5f /app/service.go:12
Forty-two thousand goroutines, and 42,100 of them were stuck on line 12 of service.go.
You can look at the call stacks with the pprof command line:
$ go tool pprof http://127.0.0.1:6060/debug/pprof/goroutine
(pprof) top
Showing nodes accounting for 42100, 99.8% of 42180 total
flat flat% sum% cum cum%
42100 99.8% 99.8% 42100 99.8% runtime.gopark
0 0.0% 99.8% 42100 99.8% main.queryWithTimeout.func1
Habits That Helped
Two habits have helped me avoid this:
- Know how each goroutine stops: A background worker should accept a
context.Contextand exit when<-ctx.Done()fires. - Buffer the channel when a timeout is involved: Changing
make(chan string)tomake(chan string, 1)lets the worker put its result in the buffer and exit, even if the parent has already left.
Goroutines are cheap to start, but ones that never exit add up.
I now treat go func() a bit like opening a database transaction: it helps to know where it ends. It isn't the only fix, and errgroup or explicit cancellation may suit your code better, but these two cover the case above.