Tune GOGC and GOMEMLIMIT with evidence
Tune GOGC and GOMEMLIMIT with evidence
GOGC controls the GC CPU versus heap-growth trade-off. In Go 1.23, a simplified target before other constraints is live heap plus (live heap + roots) multiplied by GOGC/100. Roots here represent scannable stack and global memory. A higher percentage usually permits more allocation between cycles; a lower one generally increases collection frequency. GOMEMLIMIT (Go 1.19+) is a soft runtime-memory limit, not a process RSS or container cap. It accounts roughly for Sys minus HeapReleased; external allocations and mappings need separate headroom. It can still trigger collection when GOGC is off.
package main
import ( "fmt")
func goal(live, roots, pct int) int { return live + (live+roots)*pct/100 }func main() { fmt.Println(goal(20, 4, 50), goal(20, 4, 100), goal(20, 4, 200))}The inputs are small synthetic MiB counts. Actual targets include minimum heap size, pacing and memory-limit adjustments. This arithmetic is not a tuning recommendation. A tight memory limit cannot make live data disappear and can cause frequent collection; the runtime may exceed the soft limit to make progress.
Expected output:
32 44 68Change settings in an isolated process
package main
import ( "fmt" "runtime/debug" "runtime/metrics")
func main() { oldGC := debug.SetGCPercent(75) defer debug.SetGCPercent(oldGC) oldLimit := debug.SetMemoryLimit(128 << 20) defer debug.SetMemoryLimit(oldLimit) s := []metrics.Sample{{Name: "/gc/gogc:percent"}, {Name: "/gc/gomemlimit:bytes"}} metrics.Read(s) fmt.Println(s[0].Value.Uint64(), s[1].Value.Uint64() == 128<<20)}The setters change process-wide state and return previous values. The deferred calls restore them. A negative argument to SetMemoryLimit reads the existing limit without changing it; negative SetGCPercent disables ordinary percentage-driven GC, not memory-limit enforcement. Do not tune per request. Compare identical workloads under different startup settings, recording live bytes, allocation volume, GC cycles, CPU, throughput and latency, with headroom for non-Go memory.
Expected output:
75 trueTry it locally
Capture a MemStats snapshot and compute runtime-managed memory estimate Sys minus HeapReleased. Check subtraction is safe and print whether it is positive.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Garbage collection 04: Tune GOGC and GOMEMLIMIT with evidence
Check the lesson objective before moving on.
What does GOMEMLIMIT constrain?
What is an appropriate tuning method?