Skip to content

Go Goroutine Leak Detection — Complete Guide

DodaTech Updated 2026-06-24 1 min read

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!
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

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. 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

**How to detect leaks?**

Use pprof: go tool pprof http://localhost:6060/debug/pprof/goroutine.

What causes most leaks?

Blocked channel operations without select/context.

Can I set timeout on channel ops?

Use select with time.After: case <-time.After(5*time.Second).


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