Memory Fragmentation in Long-Lived Go Services: GOGC and GOMEMLIMIT in Practice
One of our Go edge aggregators ran smoothly for weeks until traffic doubled during a promotional event, at which point Kubernetes began OOMKilling pods even though heap profiles showed only 60% live object utilization.
Understanding MADV_FREE vs. Container RSS Accounting
Linux cgroup v2 tracks anonymous memory aggressively. Under sudden allocation spikes, Go's default GOGC=100 lets the heap double before triggering a GC cycle, easily breaching tight container memory limits before the runtime can scavenge idle spans back to the OS.
The Fix That Stabilized RSS
- Set
GOMEMLIMITto 80% of the container cgroup memory limit (e.g.,GOMEMLIMIT=1600MiBfor a 2 GiB pod) while leavingGOGC=100. - Replaced ad-hoc byte slice allocations on the hot request path with tiered
sync.Poolbuffers capped at 64 KiB so oversized outliers are never retained in the pool. - Exposed
runtime/metricsheap goal and live bytes to Prometheus so GC pacing pressure is visible well before OOM thresholds.
// Avoid pooling abnormally large buffers
func putBuf(b *bytes.Buffer) {
if b.Cap() > 64*1024 {
return
}
b.Reset()
bufPool.Put(b)
}