Go Reference ยท Concepts
Goroutine leaks in Go
Understand why goroutines leak in Go, the common causes (blocked channels, missing cancellation, forgotten tickers) and how to detect and fix them.
A goroutine leak happens when a goroutine is started and then can never finish. It sits blocked forever, holding its stack and every variable it references, while the garbage collector can do nothing about it: a goroutine that is blocked is still a live root. Leaks usually do not crash anything at first. Memory and goroutine counts creep up until a server becomes slow or is killed.
Almost every leak has the same shape: the goroutine waits for an event (a channel send or receive, a lock, a context, a network read) and nobody will ever deliver that event. The cure is to give every goroutine a clear way to stop and to make sure the code that starts it also knows how it ends.
go func() { v := <-ch // blocks forever if nobody sends or closes ch use(v) }()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
The usual causes
Concepts, not an API, so here are the patterns that leak most often.
- Send with no receiver. A worker computes a result and sends it on an unbuffered channel, but the caller already returned (timeout, error, early exit). Fix: use a channel with a buffer of at least one for single-result workers, or
selecton a done signal when sending. - Receive with no sender. A goroutine ranges over a channel that no one ever closes. Fix: the owner of the sending side closes the channel when finished.
- No cancellation path. A loop that waits on a network read, a ticker or a queue has no
ctx.Done()case. Fix: thread acontext.Contextthrough and select on it. - Forgotten tickers and timers.
time.NewTickershould be stopped withdefer t.Stop(). Since Go 1.23 an unreferenced ticker is garbage collected, but a goroutine looping on<-t.Cstill never ends by itself. - Missing lock release or
WaitGroupmismatch. Awg.Wait()that never completes because oneDoneis skipped on an error path keeps the waiter alive indefinitely. - HTTP bodies and connections. Not closing
resp.Bodykeeps the connection's reader goroutines around.
Usage notes
- Before writing
go, answer two questions: who stops this goroutine, and what does it wait on? If you cannot name both, you are building a leak. runtime.NumGoroutine()is a quick counter, good in tests and metrics. For the stacks of blocked goroutines, usepprof.Lookup("goroutine")or the/debug/pprof/goroutine?debug=2endpoint ofnet/http/pprof; blocked goroutines show the exact channel operation and line.- In tests, compare the goroutine count before and after, or use a leak detector library; Go 1.25 also added
testing/synctest, which runs a test in a bubble and can detect that everything is blocked. - A leaked goroutine keeps everything it references alive. A small goroutine holding a large buffer is a large leak.
errgroupandsync.WaitGroupmake lifetimes visible: the function that starts workers waits for them before returning.- A buffered channel only hides the problem if it can fill up; use it deliberately for the one-result case, not as a general cure.
Related
go,chan,select,context.WithCancel(),close()- Lessons: Goroutines, Context, Concurrency patterns