A Go service is consuming more memory every hour, RSS climbs without bound, and pprof shows a goroutine count that only goes up. You have a goroutine leak — and goroutines hold stack frames, channels, contexts, and any pointer they captured, so the leak shows up as RAM and eventually as an OOMKill. This article is the runbook Stack Harbor uses to find which goroutine is leaking, identify the cause, and fix it.
How to verify
Confirm the count is climbing and dump every goroutine’s stack:
curl -s 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=1' | head -20
curl -s 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' > goroutines.txt
grep -c '^goroutine ' goroutines.txt
grep -A2 '^goroutine ' goroutines.txt | grep -E 'chan receive|select|sync\.' | sort | uniq -c | sort -nr | head
A healthy service has a stable goroutine count (within a small band of concurrent request count). A leak shows monotonic growth — pull two snapshots ten minutes apart and diff the count.
What’s happening
A goroutine in Go is cheap (8KB initial stack), but it is not free. It holds:
- The growable goroutine stack
- Every pointer it has on the stack (channels, contexts, closures)
- Its scheduler bookkeeping
A goroutine that never returns is a leak. Common causes:
- Send on a channel with no receiver.
ch <- valblocks forever if the receiving goroutine exited early. - Receive on a channel with no sender.
<-chblocks forever if the sender goroutine never closes or sends. - Missing context cancel. A goroutine that does
select { case <-ctx.Done(): ... }cannot exit ifctxis never canceled. The parent must callcancel()even on the happy path. - HTTP response body not closed.
http.Getreturns aResponse; if you forgetdefer resp.Body.Close(), the transport keeps a goroutine alive holding the connection. time.Tickernever stopped. A ticker spawns an internal goroutine that runs untilt.Stop()is called. Goroutines created in a hot loop withoutdefer t.Stop()accumulate.
The pprof goroutine dump is the smoking gun — every leaked goroutine has a stack trace pointing at the line where it is parked. Group by stack; the largest group is your leak.
The procedure
-
Capture a goroutine dump and group by stack signature.
curl -s 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=1' > g.txt awk '/^[0-9]+ @/ {print $1, $0}' g.txt | sort -rn | head -20The number is the count of goroutines parked at that exact stack. A leak shows up as a very large count (thousands, then tens of thousands) at one signature.
-
Use goleak in tests to catch leaks before prod. Add
go.uber.org/goleakto your test suite:import "go.uber.org/goleak" func TestMain(m *testing.M) { goleak.VerifyTestMain(m) }Any test that exits with goroutines still running will fail. This catches the common channel/context patterns before they ship.
-
Fix pattern A — missing context cancel. The leak source:
func badPoll(ctx context.Context, q Queue) { go func() { for { select { case <-ctx.Done(): return case msg := <-q.Next(): handle(msg) } } }() }Caller forgets to cancel
ctx. Fix: always paircontext.WithCancelwithdefer cancel().ctx, cancel := context.WithCancel(parentCtx) defer cancel() badPoll(ctx, q) -
Fix pattern B — leaked HTTP response. Every response body needs
Close:resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() io.Copy(io.Discard, resp.Body)io.Copy(io.Discard, ...)is required to allow connection reuse — without it,keep-alivere-establishes a new connection every time and the old goroutines accumulate. -
Fix pattern C — ticker without Stop.
func renewLeases(ctx context.Context) { t := time.NewTicker(30 * time.Second) defer t.Stop() for { select { case <-ctx.Done(): return case <-t.C: renew() } } }defer t.Stop()is mandatory.time.Afterinside a loop is the same bug class — it spawns a fresh timer every iteration that lives until it fires. -
Fix pattern D — unbounded fan-out. Workers spawned per request and never bounded:
for _, item := range items { go process(item) }Replace with a worker pool of fixed size, or use
errgroup.GroupwithSetLimit:g, ctx := errgroup.WithContext(ctx) g.SetLimit(runtime.GOMAXPROCS(0) * 2) for _, item := range items { item := item g.Go(func() error { return process(ctx, item) }) } return g.Wait()
Common pitfalls
time.Afterin aselectloop leaks until it fires. Usetime.NewTimer+Resetor wrapAfterwith a ticker — see golang-pprof-profiling for diagnosis.sync.WaitGroupdeadlock looks like a leak. Awg.Wait()that never returns blocks the parent forever; the children may or may not be leaked depending on cause. Read the stack.runtime.NumGoroutine()is a decent metric. Export it as a Prometheus gauge — sudden growth is a fast alert. Pair with the goroutine pprof endpoint for diagnostics.- A test that passes with goleak does not prove production-safety. Real services have signal handling, shutdown hooks, and external connections that tests do not exercise.
- The “expected” pool of goroutines matters. A net/http server has ~3-4 goroutines per active connection. Subtract the baseline from total before deciding there is a leak.
Stack Harbor runs goleak in CI on every Go service and exports go_goroutines as an alerting metric — a goroutine count that grows monotonically over an hour triggers our on-call rotation in the support desk. See how that fits into our managed operations practice.