Exercise 10: Anxious GC - Making the Garbage Collector Paranoid
Want to learn more? Read The Go Garbage Collector on Internals for Interns for a deep dive into how Go’s garbage collector works.
In this exercise, you’ll modify Go’s garbage collector to run aggressively — after every 5% of heap growth — and add anxious commentary every time it runs. You’ll see exactly how the GC pacing system works and how dramatically the trigger threshold affects performance.
Learning Objectives
By the end of this exercise, you will:
- Understand Go’s tri-color concurrent mark-sweep garbage collector
- Know how the GC trigger threshold (GOGC) controls collection frequency
- Locate the GC pacing logic in the runtime source
- Observe the performance impact of a hyper-aggressive GC
Introduction: How Does Go’s Garbage Collector Work?
Go uses a concurrent tri-color mark-sweep garbage collector. The “tri-color” refers to the state of each heap object during a GC cycle:
- White: Not yet visited. Objects that are still white at the end of the mark phase are garbage.
- Gray: Discovered but not fully scanned. The mark phase works through gray objects.
- Black: Fully scanned. A black object’s references have all been traced.
The GC runs concurrently with your program. To prevent the mutator (your program) from creating invisible garbage while the GC is marking, Go uses write barriers: every pointer write during GC is intercepted, ensuring the tri-color invariant holds.
The GC Pacing System
The GC doesn’t run on a fixed schedule. Instead, it uses a heap-size trigger: a new GC cycle starts when the live heap has grown by a certain fraction since the last cycle. The GOGC environment variable controls this fraction:
next_GC_trigger = live_heap_after_last_GC * (1 + GOGC/100)
With the default GOGC=100, the GC starts when the heap doubles. With GOGC=5, it starts after every 5% growth — over 20 times more frequently.
The pacer lives in mgcpacer.go and dynamically adjusts the trigger to meet throughput goals, but the gcPercent field (which GOGC maps to) sets the baseline ratio.
Key files:
- go/src/runtime/mgc.go — GC cycle start and stop
- go/src/runtime/mgcpacer.go — GC pacing and trigger calculation
Step 1: Observe Normal GC Behavior
Before changing anything, let’s see how the GC behaves normally. Create gc_demo.go:
package main
import (
"fmt"
"runtime"
"time"
)
func allocateWork() {
// Allocate 1 million small objects
result := make([][]byte, 0, 1_000_000)
for i := 0; i < 1_000_000; i++ {
result = append(result, make([]byte, 64))
}
_ = result
}
func main() {
var stats runtime.MemStats
start := time.Now()
allocateWork()
elapsed := time.Since(start)
runtime.ReadMemStats(&stats)
fmt.Printf("Time: %v\n", elapsed)
fmt.Printf("GC cycles: %d\n", stats.NumGC)
fmt.Printf("Total GC pause: %v\n", time.Duration(stats.PauseTotalNs))
}
Run with the standard Go toolchain:
go run gc_demo.go
Expected output (approximately):
Time: 45ms
GC cycles: 4
Total GC pause: 1.2ms
Note how few GC cycles occur. Now let’s make it anxious.
Step 2: Add Anxious Commentary to gcStart
Open go/src/runtime/mgc.go and find the gcStart function. It is responsible for beginning a new GC cycle. Search for it:
grep -n "func gcStart" go/src/runtime/mgc.go
You’ll find it around line 733. The function starts with a few precondition checks. Look for the section where work.cycles is incremented — this is where the new cycle actually begins. It looks something like:
work.cycles.Add(1)
Just before that line, add the anxious announcement:
// Anxious GC: announce every collection with mild panic
println("GC: oh no, running garbage collection again... (heap cycle", work.cycles.Load()+1, ")")
The full modified section should look like:
// Announce the cycle with appropriate anxiety
println("GC: oh no, running garbage collection again... (heap cycle", work.cycles.Load()+1, ")")
work.cycles.Add(1)
Understanding the Code
work— A globalworkTypestruct inmgc.gothat tracks per-cycle GC statework.cycles— An atomic counter incremented at the start of every cycleprintln()— The runtime’s built-in print, writes to stderr without needing imports
Step 3: Change the Default GOGC to 5
Now for the main event. Open go/src/runtime/mgcpacer.go and find the readGOGC function. Search for it:
grep -n "func readGOGC" go/src/runtime/mgcpacer.go
You’ll find a small function near the bottom of the file that reads the GOGC environment variable and falls back to 100 if it’s not set:
func readGOGC() int32 {
p := gogetenv("GOGC")
if p == "off" {
return -1
}
if n, err := strconv.ParseInt(p, 10, 32); err == nil {
return int32(n)
}
return 100
}
Change the fallback return value from 100 to 5:
return 5
Step 4: Rebuild the Go Toolchain
cd go/src
./make.bash
This rebuilds the entire runtime with your modifications. It takes 1-2 minutes.
Step 5: Run the Anxious GC Demo
../go/bin/go run gc_demo.go
Expected output (approximately):
GC: oh no, running garbage collection again... (heap cycle 1)
GC: oh no, running garbage collection again... (heap cycle 2)
GC: oh no, running garbage collection again... (heap cycle 3)
GC: oh no, running garbage collection again... (heap cycle 4)
GC: oh no, running garbage collection again... (heap cycle 5)
GC: oh no, running garbage collection again... (heap cycle 6)
GC: oh no, running garbage collection again... (heap cycle 7)
GC: oh no, running garbage collection again... (heap cycle 8)
GC: oh no, running garbage collection again... (heap cycle 9)
GC: oh no, running garbage collection again... (heap cycle 10)
GC: oh no, running garbage collection again... (heap cycle 11)
GC: oh no, running garbage collection again... (heap cycle 12)
GC: oh no, running garbage collection again... (heap cycle 13)
GC: oh no, running garbage collection again... (heap cycle 14)
GC: oh no, running garbage collection again... (heap cycle 15)
GC: oh no, running garbage collection again... (heap cycle 16)
...
Time: 380ms
GC cycles: 47
Total GC pause: 8.9ms
The GC now runs roughly 10x more often. The program that previously had 4 GC cycles now has dozens. Performance is significantly worse.
Step 6: See the Performance Impact More Clearly
Create a benchmark file gc_bench.go:
package main
import (
"fmt"
"runtime"
"time"
)
func allocate(n int) {
buf := make([][]byte, 0, n)
for i := 0; i < n; i++ {
buf = append(buf, make([]byte, 128))
}
_ = buf
}
func main() {
// Warm up
allocate(10_000)
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
gcsBefore := stats.NumGC
pauseBefore := stats.PauseTotalNs
start := time.Now()
allocate(1_000_000)
elapsed := time.Since(start)
runtime.ReadMemStats(&stats)
gcsAfter := stats.NumGC
pauseAfter := stats.PauseTotalNs
fmt.Printf("Allocation time: %v\n", elapsed)
fmt.Printf("GC cycles: %d\n", gcsAfter-gcsBefore)
fmt.Printf("GC pause total: %v\n", time.Duration(pauseAfter-pauseBefore))
fmt.Printf("Avg pause/cycle: %v\n", func() time.Duration {
cycles := gcsAfter - gcsBefore
if cycles == 0 {
return 0
}
return time.Duration((pauseAfter - pauseBefore) / uint64(cycles))
}())
}
../go/bin/go run gc_bench.go
Expected output with GOGC=5 (anxious):
Allocation time: 420ms
GC cycles: 52
GC pause total: 11ms
Avg pause/cycle: 211µs
Compare this to running the same program with the default Go binary (GOGC=100):
go run gc_bench.go
Expected output with GOGC=100 (normal):
Allocation time: 48ms
GC cycles: 5
GC pause total: 1.1ms
Avg pause/cycle: 220µs
The individual GC pauses are similar — each cycle does about the same amount of work. The difference is that with GOGC=5, the GC runs roughly 10 times more often, spending far more total time in the collector.
Understanding the Trade-Off
The GOGC value is a throughput/memory trade-off:
| GOGC | GC frequency | Memory overhead | CPU overhead |
|---|---|---|---|
| 5 | Very high | Very low | Very high |
| 100 | Normal | ~2x live heap | Normal |
| 400 | Low | ~5x live heap | Low |
| off | Never | Unbounded | None |
A lower GOGC means the GC collects more aggressively, keeping memory usage lower but spending more CPU time collecting. A higher GOGC allows more heap growth between collections, reducing CPU overhead at the cost of more memory.
Real applications rarely need to tune GOGC below its default. The anxious GC you just built is a pathological case — useful for understanding, but not for production.
Cleanup
To restore normal GC behavior:
cd go/src/runtime
git checkout mgc.go mgcpacer.go
cd ..
./make.bash
Summary
You’ve made Go’s garbage collector anxious:
Before: GOGC=100 → GC runs when heap doubles → 4-5 cycles per 64MB of allocations
After: GOGC=5 → GC runs after 5% growth → 50+ cycles per 64MB of allocations
Changes: runtime/mgc.go (gcStart announcement using work.cycles)
runtime/mgcpacer.go (readGOGC fallback: 100 → 5)
Result: 10x more GC cycles, ~8x slower allocation-heavy code
This exercise showed how a single constant in the runtime pacer controls the fundamental memory/CPU trade-off for every Go program.
Continue to Exercise 11 or return to the main workshop