Golang / Golang Internals and Memory Management Interview Questions
What are GOGC and GOMEMLIMIT and how do you use them to tune GC behavior?
Go's GC is controlled by two primary knobs: GOGC (the classic throughput knob) and GOMEMLIMIT (the memory ceiling introduced in Go 1.19).
| Variable | Default | Meaning |
|---|---|---|
| GOGC | 100 | GC triggers when live heap grows by GOGC% since last GC |
| GOMEMLIMIT | math.MaxInt64 (off) | Hard memory limit; GC runs more aggressively when heap approaches this |
// GOGC examples (set as environment variable or via runtime/debug)
// GOGC=100 (default) — GC when heap is 2x last-collection live set
// GOGC=200 — GC when heap is 3x — fewer GCs, more memory
// GOGC=50 — GC when heap is 1.5x — more frequent, lower peak
// GOGC=off — disable GC (benchmarks/short programs only)
import "runtime/debug"
// Set programmatically (returns old value)
oldGOGC := debug.SetGCPercent(200) // increase to reduce GC frequency
defer debug.SetGCPercent(oldGOGC)
// GOMEMLIMIT — prevents OOM by forcing GC before memory is exhausted
// GOMEMLIMIT=500MiB
debug.SetMemoryLimit(500 * 1024 * 1024) // 500 MB hard limit
// Best practice for containerized Go services:
// Set GOMEMLIMIT to ~90% of container memory limit
// This prevents OOM kills while allowing GC to breathe
// Example: container limit 1 GiB → GOMEMLIMIT=900MiB
// Runtime metrics (Go 1.16+)
import "runtime/metrics"
samples := []metrics.Sample{
{Name: "/gc/cycles/total:gc-cycles"},
{Name: "/memory/classes/heap/objects:bytes"},
}
metrics.Read(samples)
fmt.Println(samples[0].Value.Uint64()) // total GC cyclesThe interaction between the two: if GOGC=100 would trigger GC at 2 GB but GOMEMLIMIT=1.5 GB, the runtime will trigger GC earlier to stay under the limit. This makes containerised deployments safer — previously, a spike in allocations could cause an OOM kill before GC had a chance to run.
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...
