Golang / GoLang Concurrency Mastery Interview Questions
How do you write tests that detect goroutine leaks automatically?
Goroutine leaks are among the hardest production bugs to diagnose — they accumulate invisibly. Catching them at test time is far more effective than debugging production memory growth.
import ( "testing" "runtime" "time" "go.uber.org/goleak" ) // Method 1: goleak â recommended, most accurate func TestNoLeak(t *testing.T) { defer goleak.VerifyNone(t) // fails if goroutines remain after test svc := NewService() svc.Start() // ... exercise the service ... svc.Stop() // if Stop() leaks a goroutine, goleak catches it } // goleak with TestMain â check all tests in the package func TestMain(m *testing.M) { goleak.VerifyTestMain(m, goleak.IgnoreTopFunction("database/sql.(*DB).connectionOpener"), ) } // Method 2: manual count check (simpler, less precise) func TestGoroutineCount(t *testing.T) { before := runtime.NumGoroutine() svc := NewService() svc.Start() svc.Stop() time.Sleep(100 * time.Millisecond) // let goroutines exit runtime.Gosched() after := runtime.NumGoroutine() if after > before { buf := make([]byte, 1<<20) n := runtime.Stack(buf, true) t.Errorf("goroutine leak: %d before, %d after\n%s", before, after, buf[:n]) } }
More Related questions...