A goroutine costs a few kilobytes of stack and a handful of microseconds to start. Go made them that cheap on purpose, so you can launch thousands without worrying about overhead. The downside is that they're just as easy to launch without thinking about how, or whether, they will ever stop.
The Go garbage collector reclaims memory that is no longer reachable. A blocked goroutine's stack and all the variables it closes over are still reachable from the goroutine itself, so the GC won't collect them. A goroutine parked forever stays in your process for as long as it runs: it uses memory and keeps whatever resources it captured from ever being freed.
This is a goroutine leak: a goroutine that has no path to termination.
How goroutines terminate
Whoever creates a goroutine is responsible for its lifetime. The runtime won't reclaim it, and nothing else will stop it for you. A goroutine can stop in exactly three legitimate ways:
The assigned work is complete. The goroutine finishes its task and its function returns. This is the simplest exit.
go func() { result := compute() results <- result // function returns — goroutine exits cleanly}()An error is encountered. The goroutine hits a condition it cannot recover from, reports the error through a channel or other mechanism, and returns.
go func() { data, err := fetchData() if err != nil { errCh <- err return // goroutine exits on error } results <- process(data)}()The parent signals termination. The goroutine is long-lived (it loops indefinitely, waiting for work), and the caller must explicitly tell it to stop. Without this signal, the goroutine has no way to know it is no longer needed.
Without at least one of these paths, a goroutine will never exit.
What a leak looks like
The most common leak pattern is a goroutine blocked on a channel receive with no sender:
func doWork() { ch := make(chan int) go func() { val := <-ch // blocks forever — nobody sends fmt.Println(val) }() // doWork returns; nothing outside references ch anymore, but // the goroutine still holds it and stays parked on it}doWork creates an unbuffered channel, launches a goroutine that reads from it, and returns without ever sending. The caller drops the channel, but the goroutine still holds a reference to it, so the GC sees the channel as reachable and leaves it alone. The goroutine stays parked on <-ch indefinitely.
The same issue appears on the send side:
func producer() <-chan int { ch := make(chan int) go func() { for i := 0; ; i++ { ch <- i // blocks if nobody is reading } }() return ch}func main() { ch := producer() fmt.Println(<-ch) // reads the first value, then discards ch // the producer goroutine is now blocked on ch <- 1 forever}main reads one value and discards the channel. The producer goroutine tries to send the next value, finds no receiver, and parks, and since nothing can stop it, it leaks.
Preventing leaks: the done channel
The standard way to implement the third termination path, where the parent signals termination, is the done channel. The caller creates a channel and passes it to the goroutine. When the goroutine should stop, the caller closes the channel. The goroutine watches for this in a select loop:
func producer(done <-chan struct{}) <-chan int { ch := make(chan int) go func() { defer close(ch) for i := 0; ; i++ { select { case ch <- i: case <-done: return } } }() return ch}func main() { done := make(chan struct{}) ch := producer(done) fmt.Println(<-ch) // read one value close(done) // signal the producer to stop // producer goroutine will return on its next select iteration}Closing done makes the <-done case in the select immediately ready. On the goroutine's next loop iteration, it picks that case and returns. defer close(ch) fires on the way out, signalling any downstream consumers that the channel is exhausted.
The done channel is typed as <-chan struct{} (receive-only, zero-size) in the goroutine's parameter. That's on purpose: the goroutine can't close it by accident, and the channel carries no data because it only exists to signal.
Preventing leaks: context.Context
The done channel is manual and point to point. Go's standard library has a higher-level abstraction for the same problem: context.Context.
A Context carries a cancellation signal, an optional deadline, and optional key-value pairs. Cancellation propagates through the context tree: when a parent context is cancelled, all contexts derived from it are cancelled too. That makes context the right tool when cancellation needs to cross several goroutines or function boundaries.
func worker(ctx context.Context, jobs <-chan int) { for { select { case j, ok := <-jobs: if !ok { return } fmt.Println("processing", j) case <-ctx.Done(): fmt.Println("cancelled:", ctx.Err()) return } }}func main() { ctx, cancel := context.WithTimeout( context.Background(), 2*time.Second, ) defer cancel() jobs := make(chan int, 5) go worker(ctx, jobs) for i := 0; i < 5; i++ { jobs <- i }}context.WithTimeout returns a context that cancels itself after two seconds. When it cancels, ctx.Done() is closed, just like the manual done channel, except the runtime handles the timer. ctx.Err() tells the goroutine why it was cancelled: context.DeadlineExceeded for timeouts, context.Canceled for explicit cancellation.
defer cancel() comes immediately after WithTimeout, and you can't leave it out. Even if the timeout fires on its own, calling cancel releases the internal timer and associated resources, and skipping it leaks the timer.
Detecting leaks
You usually don't see a goroutine leak until it shows up as a slow, steady rise in memory usage or goroutine count under sustained traffic.
runtime.NumGoroutine() returns the number of goroutines currently alive. In tests, you can compare the count before and after running the code under test:
func TestNoLeak(t *testing.T) { before := runtime.NumGoroutine() done := make(chan struct{}) go worker(done) close(done) time.Sleep(10 * time.Millisecond) // let the goroutine exit after := runtime.NumGoroutine() if after > before { t.Errorf("goroutine leak: %d before, %d after", before, after) }}The time.Sleep is a rough approximation, because the goroutine doesn't exit at the same instant as close(done). For precise detection, signal completion through sync.WaitGroup before taking the second measurement.
For a more ergonomic solution, the goleak package (github.com/uber-go/goleak) integrates with the testing package and reports goroutines that outlive the test:
func TestMain(m *testing.M) { goleak.VerifyTestMain(m)}With VerifyTestMain, any test that leaves a goroutine running after it returns will fail with a description of the leaked goroutine: its stack trace, where it was created, and the blocking call it is stuck on.
A checklist for every goroutine
Before launching a goroutine, confirm:
- Natural exit: does the function return when the work is done?
- Error exit: does it return (not block) when something goes wrong?
- Cancellation path: is there a
donechannel orcontext.Contextthe caller can use to stop it? - Caller responsibility: is someone actually calling
close(done)orcancel()when the goroutine is no longer needed?
If any of these is missing, the goroutine may leak. Answering them while you write the go statement takes far less time than diagnosing a memory leak in production weeks later.