Introduction
Goleak is a Go testing library developed at Uber that detects goroutine leaks. Leaked goroutines consume memory, hold open connections, and can cause flaky tests or production issues. Goleak snapshots running goroutines before and after each test, reporting any that were not properly cleaned up.
What Goleak Does
- Detects goroutines that outlive the test that spawned them
- Integrates with Go's testing.T or TestMain for automatic leak checking
- Provides options to ignore known background goroutines (e.g., runtime or library goroutines)
- Reports leaked goroutine stacks for easy root-cause identification
- Works with both unit tests and integration tests
Architecture Overview
Goleak uses runtime.Stack to capture a snapshot of all active goroutines at the start and end of a test. It compares the two snapshots, filtering out known-safe goroutines using configurable matchers. Any goroutine present in the post-test snapshot that was not in the pre-test snapshot (and is not filtered) is reported as a leak. The comparison includes a configurable poll interval to allow goroutines time to shut down gracefully.
Self-Hosting & Configuration
- Add to your project with
go get go.uber.org/goleak - Call
goleak.VerifyTestMain(m)in TestMain for package-wide leak detection - Use
goleak.VerifyNone(t)at the end of individual tests for finer control - Filter known goroutines with
goleak.IgnoreTopFunction("runtime.ensureSigM") - Set custom timeouts with
goleak.MaxRetries(20)for goroutines with delayed shutdown
Key Features
- Zero-config goroutine leak detection with a single function call
- Per-test or package-wide verification modes
- Flexible filtering to ignore known background goroutines
- Detailed stack traces for leaked goroutines to aid debugging
- Used extensively across Uber's Go microservice fleet
Comparison with Similar Tools
- go test -race — detects data races, not goroutine leaks; Goleak catches leaks
- runtime.NumGoroutine() — raw count without identification; Goleak provides stack-level detail
- pprof goroutine profile — manual inspection tool; Goleak automates detection in tests
- errgroup — helps manage goroutine lifecycles; Goleak verifies they actually ended
- golangci-lint — static analysis; Goleak is a runtime check during test execution
FAQ
Q: Will Goleak slow down my tests? A: The overhead is minimal. Goleak captures goroutine stacks only at test boundaries, not during execution.
Q: How do I ignore goroutines from third-party libraries?
A: Use goleak.IgnoreTopFunction("package.functionName") to filter goroutines by their top stack frame.
Q: Can I use Goleak with testify suites?
A: Yes, call goleak.VerifyNone(t) in your suite teardown or use VerifyTestMain at the package level.
Q: Does Goleak work with goroutine pools?
A: Yes, as long as pool goroutines are shut down before the test ends. Use IgnoreTopFunction if pools are intentionally long-lived.