Go Goroutine Leak Detection — Complete Guide
In this tutorial, you'll learn about Go Goroutine Leak Detection. We cover key concepts, practical examples, and best practices.
Goroutine leak prevention -- Prevent goroutine leaks by always having a way to stop them, using context cancellation or closing channels.
The Problem
Goroutines that block on channels without a way to unblock leak memory. Always ensure every goroutine has a shutdown path via context, channel close, or timeout.
Wrong
ch := make(chan int)
go func() {
val := <-ch // blocks forever, nobody sends
}()
time.Sleep(time.Second)
Output:
// Goroutine stays in memory forever. Leaked!
Right
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ch := make(chan int)
go func() {
select {
case val := <-ch:
fmt.Println("Got:", val)
case <-ctx.Done():
fmt.Println("Worker stopping")
}
}()
cancel() // Worker stops
Output:
Worker stopping
Prevention
- Always have a way to stop goroutines
- Use context.WithCancel for lifecycle control
- Use select with ctx.Done() for blocking ops
- Use buffered channels to prevent sender blocks
- Monitor with runtime.NumGoroutine() in health checks
Common Mistakes with goroutine leak
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro