3. Memory, GC, and Tuning
Understand GC trade-offs (GOGC
, GOMEMLIMIT
), reduce allocation pressure, and size heaps in containers.
Question: Can you briefly explain how the Go garbage collector works and how
GOGC
tunes it?
Answer: Go uses a concurrent, tri-color mark-and-sweep garbage collector. It runs concurrently with the application for most of its cycle, with very short stop-the-world (STW) pauses. The GOGC
environment variable controls the trade-off between GC frequency and total heap size. GOMEMLIMIT
caps the GC-targeted heap size for memory-bounded workloads.
Explanation: GOGC=100
(the default) means the GC triggers when the heap doubles relative to the last live set. Lower values reduce peak memory at the cost of CPU; higher values do the opposite. GOMEMLIMIT
(e.g., GOMEMLIMIT=512MiB
) directs the GC to keep the live heap under a soft cap—very useful in containers to avoid OOM. Monitor with GODEBUG=gctrace=1
.
Question: When profiling a service, you notice high allocation pressure. What are some common techniques to reduce it?
Answer: To reduce allocations, I would first check for obvious issues like creating large objects in tight loops. Then, I would consider using a sync.Pool
to reuse objects that are expensive to create, pre-allocating slices and maps with a known size to avoid reallocations, and carefully reviewing API designs to avoid unnecessary copying of data.
Explanation: High allocation pressure puts more work on the garbage collector, consuming CPU and potentially increasing pause times. Using pprof
's -inuse_space
and -alloc_objects
flags can help pinpoint exactly where allocations are happening. For very high-performance scenarios, arena-based memory allocation (as seen in the experimental arena
package) can be used to manage the lifecycle of a group of objects together, completely avoiding individual GC overhead for them.
Question: When do you tune
GOGC
vsGOMEMLIMIT
?
Answer: Use GOMEMLIMIT
to cap heap in containers; use GOGC
to trade memory for CPU when heap growth is acceptable.
Explanation: GOMEMLIMIT
enforces a soft cap; GOGC
changes growth target. Prefer allocation reduction first.