runtime.NumGoroutine, goleak, stack dumps, context leaks, and blocked channel diagnostics.
8 min readGo for SREBuild
Leak Detection Methods
Goroutine leaks are the most common resource leak in Go. A leaked goroutine consumes memory, CPU, and may hold resources like file descriptors or database connections.
Goleak-detection-overview.go
28 linesLn 1, Col 1Go
Monitor goroutine counts in production. Use goleak in tests. Analyze stack dumps when leaks are suspected. Each method catches different types of leaks.
goleak in Tests
Gogoleak-usage.go
35 linesLn 1, Col 1Go
goleak automatically detects goroutine leaks in tests. VerifyTestMain catches leaks across all tests. VerifyNone catches leaks in individual tests. IgnoreTopFunction filters known background goroutines.
runtime.NumGoroutine
Gogoroutine-monitoring.go
53 linesLn 1, Col 1Go
runtime.NumGoroutine returns the current count. Monitor this metric over time. A growing count indicates leaks. Snapshot before and after operations to isolate leaks. Export as Prometheus metric for alerting.
Stack Dump Analysis
Gostack-dump-analysis.go
45 linesLn 1, Col 1Go
Stack dumps show goroutine state and location. Count goroutines by state to identify patterns. chan receive/send blocks indicate channel issues. select blocks indicate waiting on multiple channels. runtime.gopark blocks have various causes.
Context Leaks
Gocontext-leak-detection.go
44 linesLn 1, Col 1Go
Context leaks happen when cancel is never called. Each context.WithCancel creates a goroutine for cancellation propagation. If cancel is not called, this goroutine leaks. Always defer cancel() after creating a cancellable context.
Blocked Channel Diagnostics
Gochannel-block-diagnostics.go
49 linesLn 1, Col 1Go
Stack dumps show which goroutines are blocked on channels. chan receive means waiting to receive. chan send means waiting to send. Common causes: unbuffered channels with no receiver, closed channels, and missing exit paths.
Prevent leaks at design time
Every goroutine must have an exit path tied to context cancellation. Every channel send must have a receiver or a context case. Every channel receive must have a sender or a context case. Design for lifecycle management from the start.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.