← All posts

Finding Goroutine Leaks in Go with Persistent Stack Profiles

Goroutine leaks in Go show up as persistent stacks, not brief spikes. The new leak profile in Go gives you a better way to group, verify, and fix shutdown and ownership bugs before they turn into production latency and memory issues.

Goroutine leaks are a production problem, not a style issue. They grow memory use, hold file descriptors, keep network sockets open, and distort latency under load. In Go, they also hide well. A service may pass tests, look fine in light traffic, and still accumulate stuck goroutines for days.

The recent Go blog post, “Goroutine Leak Profiles”, points at a useful fact. The runtime now exposes a dedicated pprof profile for leaked goroutine stacks. That matters because the usual goroutine dump shows what exists now, while leak profiling helps you focus on what persists. For a team running Go services in production, this shifts leak hunting from guesswork toward repeatable inspection.

Start with persistence, not peak count

A high goroutine count is only a clue. Some systems spawn thousands of short-lived goroutines by design. A batch fan-out, an HTTP server under burst traffic, or a worker pool with backpressure will all push counts up without indicating a leak.

What matters is persistence. If the count rises after traffic spikes and fails to return toward baseline, you have a stronger signal. Track this over time.

What to inspect:

  • runtime.NumGoroutine() as a time series
  • heap growth alongside goroutine growth
  • open file descriptors and socket counts
  • request latency during and after bursts
  • queue depth for background workers

A simple gauge on its own is weak. Pair it with state transitions. For example, compare goroutine count before a load test, at peak, and 10 minutes after traffic returns to normal. If 5,000 extra goroutines remain parked, you have something concrete to investigate.

This is where teams often go wrong. They alert on absolute goroutine count. That produces noise. A better rule keys off failure to recover, slope over time, or count per unit of load. For example, goroutines per request per second staying flat is healthy. Goroutines growing while traffic stays flat is not.

Use pprof to group by blocking point

Once you know leaked goroutines persist, the next step is grouping. A raw goroutine dump is often too noisy. Thousands of stacks differ by small frame details. You need to find the shared wait point.

The practical workflow is:

  1. reproduce the issue under controlled load
  2. capture profiles at intervals
  3. compare stacks which persist across captures
  4. group by top blocking frame or common call path

Common leak signatures in Go services:

  • receive from a channel with no sender left alive
  • send to a channel with no receiver draining it
  • select without a shutdown path
  • blocked io.Copy or Read on a connection with no deadline
  • http.Client calls without context cancellation or response body close
  • ticker or timer loops with no stop condition
  • worker goroutines waiting on a job channel after the owner exits

A blocked stack often tells you the class of bug in one glance. Examples:

for msg := range ch {
    process(msg)
}

This loop is fine only if some owner closes ch. If ownership is unclear, the goroutine waits forever.

resp, err := client.Do(req)
if err != nil {
    return err
}
defer resp.Body.Close()

If Close is missing in a hot path, transport goroutines and connections accumulate.

ticker := time.NewTicker(time.Second)
go func() {
    for range ticker.C {
        flush()
    }
}()

If no code calls ticker.Stop() and no shutdown signal exits the loop, the goroutine survives past its useful life.

The new leak profile helps because it narrows attention to stacks that remain around long enough to matter. That is closer to the operational definition of a leak.

Verify lifecycle ownership at API boundaries

Many goroutine leaks start as ownership bugs. One function starts a goroutine. Another function owns the context. A third owns the channel. No part has full responsibility for shutdown.

You should make ownership explicit in code review.

Check these boundaries:

  • who starts the goroutine
  • what event tells it to stop
  • who closes the channel, if any
  • whether the goroutine inherits a cancellable context
  • whether callers must drain a result channel
  • whether background work outlives the request by design

A good pattern is to tie every long-lived goroutine to a context and a WaitGroup.

func startWorker(ctx context.Context, wg *sync.WaitGroup, jobs <-chan Job) {
    wg.Add(1)
    go func() {
        defer wg.Done()
        for {
            select {
            case <-ctx.Done():
                return
            case job, ok := <-jobs:
                if !ok {
                    return
                }
                handle(job)
            }
        }
    }()
}

This does three things well. It gives the goroutine a stop signal. It handles channel closure. It lets the parent wait for exit. In production systems, these three points prevent a large share of leak classes.

Where teams slip:

  • launching goroutines inside library helpers with no lifecycle contract
  • returning channels without documenting who drains or closes them
  • spawning retries or heartbeats detached from request context
  • using context.Background() inside request-scoped work

A useful rule is simple. If a goroutine outlives the function that created it, the code should state why.

Reproduce with load, then diff before and after

Leak debugging works best when you force the system through a clear scenario. Idle inspection rarely helps. You want a test or load script that causes the count to climb, then a quiet period where healthy goroutines should exit.

A practical sequence:

  • record baseline goroutine, heap, fd, and latency metrics
  • run a fixed load pattern for 5 to 15 minutes
  • stop the load completely
  • wait for connection drains and worker completion
  • capture pprof snapshots before, during, and after
  • compare persistent stack groups

This before-and-after shape matters more than one snapshot. A single profile tells you what is blocked now. A diff tells you what failed to go away.

In HTTP services, also inspect transport settings and timeout behavior. Missing timeouts turn slow external dependencies into goroutine retention.

Look at:

  • http.Server read, write, and idle timeouts
  • outbound client timeout strategy
  • per-request contexts on RPC and database calls
  • connection pool limits
  • graceful shutdown paths during deploys

If your service exposes diagnostics endpoints, protect them and collect profiles automatically during soak tests. Many teams only capture profiles once production is already degraded. It is better to make profile collection part of pre-release load testing.

For internal services, a small profiling playbook is worth more than ad hoc debugging. Define which profiles to capture, at what intervals, and which counters to compare. If your team runs many Go services, Workflow Audit fits here as a way to standardize the manual steps around leak triage.

Read the scheduler clues around the stack traces

Goroutine leaks are not always stuck forever on a channel. Some leak by spinning, retrying, or parking around scheduler activity in a way that looks busy rather than blocked. The stack traces still carry clues.

Signals to read:

  • repeated timers and sleeps in the same call path
  • retry loops with no upper bound and no context check
  • select loops with a default branch causing busy polling
  • goroutines in network poll waits tied to abandoned connections
  • many identical stacks rooted in one request path or tenant operation

A classic bug looks like this:

for {
    select {
    case msg := <-ch:
        use(msg)
    default:
        // keep checking
    }
}

This loop does not block. It burns CPU when idle and survives until process exit unless some outer condition stops it. Under pressure, this sort of bug shows up as both scheduler churn and inflated goroutine count.

Another common miss is retry logic:

go func() {
    for {
        if err := syncOnce(); err == nil {
            return
        }
        time.Sleep(time.Second)
    }
}()

Without context cancellation or retry limits, each failed start path leaves another background loop behind.

The fix is rarely exotic. Add deadlines. Thread context through every I/O path. Define ownership for channels. Stop tickers. Close response bodies. Wait for worker exit on shutdown. The hard part is spotting where one of these contracts went missing.

What to watch next

The dedicated leak profile in Go changes how you should instrument services. Expect teams to fold leak checks into soak tests, CI load stages, and graceful shutdown testing. Also watch for libraries to document goroutine lifecycle more clearly, because leak profiling makes hidden background work easier to see.

For your own services, the next step is simple. Measure recovery after load, capture persistent stacks, and review lifecycle ownership in every place your code starts a goroutine. Leak prevention in Go is less about syntax and more about clear shutdown contracts.