debuggoCritical
Go goroutine leak from unbuffered channel or missing context cancellation
Viewed 0 times
goroutine leakcontext cancelchannel blockpprofNumGoroutineerrgroup
Error Messages
Problem
Go application memory grows over time. Goroutines accumulate and are never garbage collected. pprof shows increasing goroutine count. Common in HTTP handlers and background workers.
Solution
Goroutines leak when they block forever on channel operations or missing cancellation. Fixes: (1) Always use context.Context and select on ctx.Done(). (2) Use buffered channels when the sender might not have a receiver. (3) Add timeouts: ctx, cancel := context.WithTimeout(ctx, 30*time.Second); defer cancel(). (4) Monitor with runtime.NumGoroutine() or pprof. (5) Use errgroup for managing goroutine lifecycles.
Why
Go's garbage collector cannot collect goroutines. A goroutine blocked on a channel read/write will exist until the program exits. Unlike threads, goroutines are cheap to create but must be explicitly managed.
Revisions (0)
No revisions yet.