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
More Related questions...