Skip to content

Hunting goroutine leaks in a long-running Go service

Spot a goroutine leak from pprof and metrics, find the leaking stack, and fix the four classic causes — unclosed channels, missing context cancel, leaked HTTP responses, ticker leaks.

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:

  1. Send on a channel with no receiver. ch <- val blocks forever if the receiving goroutine exited early.
  2. Receive on a channel with no sender. <-ch blocks forever if the sender goroutine never closes or sends.
  3. Missing context cancel. A goroutine that does select { case <-ctx.Done(): ... } cannot exit if ctx is never canceled. The parent must call cancel() even on the happy path.
  4. HTTP response body not closed. http.Get returns a Response; if you forget defer resp.Body.Close(), the transport keeps a goroutine alive holding the connection.
  5. time.Ticker never stopped. A ticker spawns an internal goroutine that runs until t.Stop() is called. Goroutines created in a hot loop without defer 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

  1. 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 -20

    The 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.

  2. Use goleak in tests to catch leaks before prod. Add go.uber.org/goleak to 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.

  3. 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 pair context.WithCancel with defer cancel().

    ctx, cancel := context.WithCancel(parentCtx)
    defer cancel()
    badPoll(ctx, q)
  4. 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-alive re-establishes a new connection every time and the old goroutines accumulate.

  5. 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.After inside a loop is the same bug class — it spawns a fresh timer every iteration that lives until it fires.

  6. 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.Group with SetLimit:

    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.After in a select loop leaks until it fires. Use time.NewTimer + Reset or wrap After with a ticker — see golang-pprof-profiling for diagnosis.
  • sync.WaitGroup deadlock looks like a leak. A wg.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.