Skip to content

Lesson 1 of 9 · 22m

Goroutine Lifetimes and Ownership

Treat goroutines as owned resources with clear startup, shutdown, and error paths rather than fire-and-forget background threads.

The first production goroutine leak I chased did not look like a leak. Requests were fast, tests passed, and memory climbed only a few megabytes an hour. Three days later the service had 80,000 goroutines parked in chan receive, all descendants of one innocent helper. Goroutines are cheap to start and expensive to forget.

A goroutine is a resource

The least controlled line in many Go services is also the shortest:

go process(job) // who waits, cancels, and sees the error?

If you cannot answer those questions, the goroutine is unowned. Ownership means one component starts it, one component knows how it exits, and one contract explains what happens when the parent shuts down first.

Start work where you can wait for it

Keep the synchronizing object close to the spawn point:

func serve(ctx context.Context, jobs <-chan Job) error {
    var wg sync.WaitGroup
    for job := range jobs {
        wg.Add(1)
        go func(j Job) {
            defer wg.Done()
            handle(j)
        }(job)
    }
    wg.Wait()
    return nil
}

This example is not complete — cancellation and producer shutdown are missing — but it shows the shape: the owner that creates concurrency also joins it. A WaitGroup hidden in package-level state usually means ownership was never designed.

Daemons are deliberate exceptions

Metrics refreshers, connection reapers, and cache warmers can be legitimate daemon goroutines. Make that exception explicit: pass a context, name the loop, and make shutdown wait for it. go cache.refreshLoop(ctx) is defensible. An anonymous go func(){ ... }() with no exit condition is not.

Shutdown is part of the API

Every long-running goroutine needs at least one documented exit: parent context canceled, input channel closed and drained, an explicit Close method, or process exit as the only intended lifetime. If none exists, the leak is already designed in.

Field notes

  • go creates scheduling possibility, not unlimited parallelism; work still shares memory, CPU, and downstream capacity.
  • Go 1.22 fixed per-iteration loop variables, but explicit capture parameters still make handoffs obvious in review.
  • Recover panics at background boundaries, log them, and propagate failure; otherwise one panic takes the whole process down.
  • Tests that finish while spawned goroutines continue running are not isolated tests.

Was this lesson helpful?

Sign in to rate