Golang / GoLang System Architecture and Testing Interview Questions
What memory leak patterns in Go are not goroutine leaks and how do you detect them?
Go has several memory leak patterns beyond leaked goroutines: long-lived caches without eviction, global maps that grow without bounds, slice backing arrays held by small sub-slices, and finalizers that delay GC.
// LEAK 1: growing global map without eviction
var requestMetrics = map[string]int64{} // grows forever with new paths
// Fix: use a bounded structure (LRU cache, TTL cache)
var metricsCache = cache.NewLRU[string, int64](1000) // bounded
// LEAK 2: slice sub-slice retaining large backing array
func getHeader(data []byte) []byte {
return data[:8] // BAD: keeps ALL of 'data' alive
}
func getHeaderSafe(data []byte) []byte {
header := make([]byte, 8)
copy(header, data[:8]) // GOOD: independent allocation
return header
}
// LEAK 3: time.Ticker without Stop()
// Already discussed but worth repeating — channel and goroutine alive forever
// LEAK 4: cgo-allocated memory (outside GC's purview)
// Must manually call C.free() for C.CString(), C.malloc(), etc.
// DETECTION:
// A. runtime.ReadMemStats — watch HeapAlloc over time
func monitorHeap(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done(): return
case <-ticker.C:
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
slog.Info("heap",
"alloc_mb", stats.HeapAlloc / (1 << 20),
"sys_mb", stats.HeapSys / (1 << 20),
"num_gc", stats.NumGC,
"goroutines", runtime.NumGoroutine(),
)
}
}
}
// B. pprof heap profile comparison
// curl http://localhost:6060/debug/pprof/heap > heap1.out
// # wait a while
// curl http://localhost:6060/debug/pprof/heap > heap2.out
// go tool pprof -base heap1.out heap2.out
// > top10 # shows objects that grew between snapshots
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
