Golang & Concurrency (50 Qs)•Part 2: Concurrency, Channels & The GMP Scheduler (16 - 32)
How do you prevent Goroutine Leaks in production Go services?
senior LevelCode ExampleGolang
In Simple Words: A Goroutine leak occurs when a goroutine is launched but can never terminate, consuming 2KB–MBs of memory and remaining in memory forever.
Common causes and fixes:
- Sending to an unbuffered channel with no receiver: Use a buffered channel of size 1 if only the first response is needed.
- Missing cancellation: Always propagate
context.WithCancelorcontext.WithTimeout. - Forgotten ticker cleanup: Always call
ticker.Stop()to release runtime resources.
go
// BUG: Leaked goroutine if context times out before response
func leak() {
ch := make(chan int) // Unbuffered!
go func() {
ch <- doSlowWork() // BLOCKS FOREVER if receiver gave up!
}()
select {
case res := <-ch:
use(res)
case <-time.After(50 * time.Millisecond):
return // Leaks the goroutine!
}
}
// FIX: Buffer of 1 allows sender to write and exit cleanly
ch := make(chan int, 1)