~/Detecting and Preventing Golang Memory Leaks
Jul 14, 2022
Memory leaks in Golang occur when memory is allocated but not released, causing higher memory usage over time. Despite Go’s garbage collector, leaks can happen if references to objects are unintentionally kept.
Common causes:
- Goroutines not stopped (example)
- Slices, maps, or channels growing without bounds (slice doc)
- Global variables holding data
Detecting leaks:
- Use
runtime/pprof
for profiling - pprof tool to generate heap profiles
- Libraries like uber-go/goleak detect goroutine leaks in tests
Example of a leaked goroutine:
Prevention tips:
- Always close channels and exit goroutines
- Limit use of global variables
- Profile regularly using pprof
To learn more, see Go Memory Leaks and how to avoid them.