Find and fix a goroutine leak in Go
Compare goroutine stacks after work has drained, identify the missing exit path, and cancel and join workers before returning.
Capture the goroutine profile while the count is growing, group repeated stacks, and find the operation that never finishes. Then give that goroutine an exit path and wait for it to exit. Go’s garbage collector cannot reclaim a goroutine simply because your request handler stopped caring about its result.
Reproduce the missing shutdown
Save as leak.go (Go 1.27.3):
package main
import (
"flag"
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"runtime"
"sync"
)
func worker(stop <-chan struct{}, ready, done *sync.WaitGroup) {
defer done.Done()
ready.Done()
<-stop
}
func main() {
fixed := flag.Bool("fixed", false, "stop and join workers")
flag.Parse()
baseline := runtime.NumGoroutine()
stop := make(chan struct{})
var ready, done sync.WaitGroup
ready.Add(20); done.Add(20)
for i := 0; i < 20; i++ { go worker(stop, &ready, &done) }
ready.Wait()
fmt.Println("baseline:", baseline, "with workers:", runtime.NumGoroutine())
if *fixed { close(stop); done.Wait(); fmt.Println("after join:", runtime.NumGoroutine()); return }
log.Fatal(http.ListenAndServe("127.0.0.1:6060", nil))
}
go build -o leak leak.go
./leak
The program starts twenty workers, then leaves them waiting on a channel nobody closes. The wait groups make startup and shutdown observable without relying on a sleep. In another terminal:
curl -fsS 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' > goroutines.txt
curl -fsS http://127.0.0.1:6060/debug/pprof/goroutine > goroutines.pb.gz
go tool pprof -top ./leak goroutines.pb.gz
The blank import registers handlers on the default HTTP mux. debug=2 requests readable stacks; the default profile is suitable for pprof. The HTTP pprof documentation lists the handlers. Keep this listener on loopback or behind access control: profiles expose application internals.
The twenty workers produce repeated channel-receive stacks. Example output, with the source path shortened:
goroutine 8 [chan receive]:
main.worker(0x1ef26d7fa0e0, 0x0?, 0x0?)
…/leak.go:14 +0x5b
Argument addresses and instruction offsets vary; inspect the blocked application frame and its creator rather than matching addresses. The binary profile attributed twenty goroutines cumulatively to main.worker through runtime.chanrecv. The profile also includes its own HTTP handling goroutines, so its total is larger than the count printed before the server starts.
Close the channel and join
Stop the running demo with Ctrl-C, then run:
./leak -fixed
Output:
baseline: 1 with workers: 21
after join: 1
Closing stop releases every receiver. done.Wait() establishes that all workers finished before main reports its final count. In a real request pipeline, use a context and select on ctx.Done() alongside a blocking channel send or receive. Cancellation must reach every potentially unbounded wait; cancelling only the parent does not unblock a child sending to an abandoned result channel.
runtime.NumGoroutine() is useful as a trend, not an exact production invariant. Repeat the same workload, let legitimate background work drain, and compare stack groups. A large stable worker pool can be intentional; a rising population at the same abandoned request stack is stronger evidence.
Keep the fix covered
The maintained test helper’s import path is go.uber.org/goleak; the Go module proxy reports v1.3.0 as its latest release on November 15, 2026. In a module that already depends on it, a package-level check is:
package main
import (
"testing"
"go.uber.org/goleak"
)
func TestMain(m *testing.M) { goleak.VerifyTestMain(m) }
The upstream usage guide also documents defer goleak.VerifyNone(t) for individual tests. Use the package-level form when tests run in parallel; unrelated test goroutines can confuse an individual check. Join your own workers before verification, and keep ignore rules narrow.
Go deeper
The Go concurrency pitfalls explain why blocked sends, missing cancellation and forgotten joins keep goroutines alive.