Garbage collector
Understand allocation rate, live heap, and latency tradeoffs before tuning GC behavior.
Canonical guidance
- reduce unnecessary allocations before tuning GC knobs
- understand the relationship between allocation rate, live heap, and CPU overhead
- use the official GC guide as the baseline mental model
- tune only after measurement demonstrates a need
Use when
- memory pressure
- GC CPU spikes
- latency-sensitive services
Avoid
- treating GC tuning as a first-line fix
- cargo-culting
GOGCvalues - assuming every allocation issue is a collector issue
Preferred pattern
func BenchmarkDecode(b *testing.B) {
payload := []byte(`{"name":"gopher"}`)
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var req Request
if err := json.Unmarshal(payload, &req); err != nil {
b.Fatal(err)
}
}
}
Anti-pattern
- lowering
GOGCor raising it dramatically without workload data
Explanation: This anti-pattern is common because GC knobs look like easy wins, but without workload data they usually mask the real allocation problem.
Why
- most GC wins come from allocation behavior and workload understanding, not magic settings
Sources
- A Guide to the Go Garbage Collector - Michael Knyszek
- The Green Tea Garbage Collector - Michael Knyszek and Austin Clements
- Getting to Go: The Journey of Go's Garbage Collector - Rick Hudson