Skip to content
Huseyin Babal
Go back

Go's garbage collector: GOGC, GOMEMLIMIT and Green Tea, measured

I ran the same Go binary three times for 30 seconds, changing nothing but GOGC. The number of completed jobs went from 6,497 to 15,838. Peak memory went from 1.5 GB to 4.8 GB.

GOGC=50   jobs  6497  GC runs  189  GC CPU  51.5%  peak  1473 MB
GOGC=100  jobs  9311  GC runs  143  GC CPU  39.2%  peak  1983 MB
GOGC=400  jobs 15838  GC runs   60  GC CPU  16.6%  peak  4790 MBoutput

This post covers what the collector does, how to read its trace, the two knobs it gives you (GOGC and GOMEMLIMIT), and how the Green Tea collector, the default since Go 1.26, compares with the old one on the same program.

Setup

All numbers come from one Linux VM: 4 vCPUs, Go 1.27.3. Two small programs, standard library only.

tree.go is the stress test. It builds a tree of about 16 million nodes (depth 24, roughly 800 MB of small, pointer-heavy objects) and keeps it alive for the whole run. Then, for the given number of seconds, it builds and drops a depth-16 tree on every core, over and over. One round on all cores counts as one job. At the end it prints jobs, GC cycles, the collector’s share of CPU time and the memory obtained from the OS:

package main

import (
	"fmt"
	"os"
	"runtime"
	"runtime/metrics"
	"strconv"
	"time"
)

type node struct {
	l, r *node
	v    int
}

func build(d int) *node {
	if d == 0 {
		return &node{v: 1}
	}
	return &node{build(d - 1), build(d - 1), d}
}

func main() {
	secs, _ := strconv.Atoi(os.Args[1])
	keep := build(24) // about 800 MB of small objects, full of pointers
	start := time.Now()
	jobs := 0
	for time.Since(start) < time.Duration(secs)*time.Second {
		done := make(chan struct{})
		for w := 0; w < runtime.GOMAXPROCS(0); w++ {
			go func() { _ = build(16); done <- struct{}{} }()
		}
		for w := 0; w < runtime.GOMAXPROCS(0); w++ {
			<-done
		}
		jobs++
	}
	s := []metrics.Sample{{Name: "/cpu/classes/gc/total:cpu-seconds"}, {Name: "/cpu/classes/total:cpu-seconds"}}
	metrics.Read(s)
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("jobs %5d  GC runs %4d  GC CPU %5.1f%%  peak %5d MB  keep=%d\n", jobs, m.NumGC, s[0].Value.Float64()/s[1].Value.Float64()*100, m.Sys/1024/1024, keep.v)
}

“GC CPU” is the collector’s CPU time from runtime/metrics divided by the total CPU time. “peak” is MemStats.Sys, the memory the runtime got from the operating system.

pause.go is smaller and only exists to produce a readable trace line: it allocates 40 million tiny nodes and keeps every fourth one in a linked list.

package main

import "fmt"

type node struct{ next *node }

func main() {
	var keep *node
	for i := 0; i < 40_000_000; i++ {
		n := &node{}
		if i%4 == 0 {
			n.next, keep = keep, n
		}
	}
	fmt.Println(keep != nil)
}

What the collector does

Go uses a concurrent mark-and-sweep collector. The mark phase walks the object graph: it begins at goroutine stacks and global variables and sets a mark bit on every object reachable through pointers. Whatever is left unmarked can’t be reached by the program, and the sweep phase makes that memory available again.

Marking runs at the same time as your goroutines. The runtime aims to use 25% of the available CPU for it (one of the four Ps here), and it can also make a goroutine that allocates heavily help with marking (“mark assist”). The program is stopped twice per cycle, once before marking and once after it, and both stops are normally microseconds long.

Reading a gctrace line

GODEBUG=gctrace=1 makes the runtime print one line per cycle to standard error. pause.go produces a dozen cycles; this pipeline keeps cycle 9 and trims two fields so it fits on one line:

GODEBUG=gctrace=1 ./pause 2>&1 | sed -n 9p | sed 's/ clock.*cpu//; s/, 0 MB stacks.*//'
gc 9 @0.436s 23%: 0.011+96+0.002 ms, 26->33->21 MB, 31 MB goaloutput
FieldMeaning
gc 9the ninth cycle since the program started
@0.436stime since start
23%share of CPU time spent in GC since start
0.011+96+0.002 mswall clock: stop-the-world before marking, concurrent mark, stop-the-world after marking
26->33->21 MBheap when marking started, heap when it ended, heap still live after it
31 MB goalheap size this cycle aimed to finish at, set from the previous cycle’s live heap

The two pauses were 11 and 2 microseconds. The 96 ms in the middle is concurrent: the program kept running and allocating, which is why the heap grew from 26 to 33 MB during marking. The removed clock ... cpu part splits that same work into CPU time per category (assist, background, idle), which is useful when you suspect mark assists are slowing your goroutines down.

If the percentage after the timestamp stays in single digits on a real service, the collector isn’t your problem and the rest of this post is optional.

GOGC: when the next cycle starts

GOGC sets the heap growth allowed between cycles, as a percentage of the live heap left by the last one. The default is 100: with 21 MB live, the next cycle aims to finish around 42 MB; since Go 1.18 the goal also counts goroutine stacks and globals.

Lower values collect more often and keep the heap small. Higher values collect less often and use more memory. The three runs of tree.go, 30 seconds each:

GOGC=50 ./tree-new 30
GOGC=100 ./tree-new 30
GOGC=400 ./tree-new 30
GOGCJobsGC cyclesGC share of CPUPeak memory
506,49718951.5%1,473 MB
1009,31114339.2%1,983 MB
40015,8386016.6%4,790 MB

Going from 50 to 400 cut the cycle count to about a third and the collector’s CPU share from half to a sixth, and the freed CPU went into jobs: 2.4 times as many. Memory paid for it, more than three times as much. On this program the trade is close to linear because it does almost nothing except allocate; a service that spends its time on I/O or computation gets less back from the same change.

You can also change it at runtime with debug.SetGCPercent, and GOGC=off disables the growth trigger completely.

GOMEMLIMIT: a ceiling instead of a ratio

GOMEMLIMIT (Go 1.19+) sets a soft limit on the total memory the runtime manages. Near the limit, the collector runs as often as it needs to stay under it, whatever GOGC says. With GOGC=off, the limit is the only trigger left:

GOGC=off GOMEMLIMIT=1500MiB ./tree-new 30
jobs  6302  GC runs  179  GC CPU  52.0%  peak  1493 MBoutput

The process stayed at 1,493 MB, just under the limit. Throughput ended up close to the GOGC=50 run, because 1.5 GB is not much room above an 800 MB live tree, so the collector had to work almost as hard.

Two details matter in production:

Green Tea against the old collector

The old marker works object by object. It pops a pointer from its work queue, scans that object, pushes the pointers it finds, and repeats. Objects that are next to each other in the program’s logic are scattered across the heap, so this jumps around memory, and the Go team found the marker usually spent at least 35% of its time stalled on memory access.

Green Tea, the default since Go 1.26, works on pages instead. For small objects, it tracks which objects on a page still need scanning and queues the page, not the object. A page waits in the queue while more of its objects get marked, and when it is taken off, all of its pending objects are scanned in one pass, in address order. That gives the CPU caches and prefetchers a much easier job.

Go 1.27 still lets you build with the old collector, which makes a direct comparison easy:

GOEXPERIMENT=nogreenteagc go build -o tree-old tree.go
go build -o tree-new tree.go
go version -m tree-old | grep GOEXPERIMENT
	build	GOEXPERIMENT=nogreenteagcoutput

Five runs of 40 seconds each, alternating old and new:

RunOld: jobsOld: GC CPUOld: peakGreen Tea: jobsGreen Tea: GC CPUGreen Tea: peak
18,88358.6%2,725 MB11,68238.8%1,989 MB
29,54756.5%2,414 MB12,45839.5%1,980 MB
311,70445.5%2,387 MB12,41739.5%2,004 MB
411,89745.7%2,377 MB12,47539.4%1,997 MB
511,99545.7%2,372 MB12,42239.1%1,992 MB
Median11,70445.7%2,387 MB12,42239.4%1,992 MB

By median, Green Tea cut the collector’s CPU share from 45.7% to 39.4% and completed 6.1% more jobs, with about 400 MB less peak memory. It also ran more cycles (188–189 against 104–142), each one cheaper.

The spread is the other result. Green Tea stayed between 38.8% and 39.5% in all five runs. The old collector had two slow runs at 58.6% and 56.5% before settling around 45.6%. Medians hide that; if you benchmark this yourself, look at every run.

The Go 1.26 release notes expect a 10–40% reduction in GC overhead for programs that rely heavily on the collector. This test sits at the low end of that range, about 14% less GC CPU by median. It is a single data structure shape (binary trees of 24-byte nodes) on one VM, so treat it as one point, not a forecast.

What I’d do with this

  1. Start with GODEBUG=gctrace=1 on the real service. A low GC percentage means there is nothing to tune.
  2. If it is high and the machine has memory to spare, raise GOGC or set GOMEMLIMIT near the container limit. Either trades memory for CPU.
  3. Before tuning, upgrade to Go 1.26 or later. Green Tea is on by default and costs nothing to try. GOEXPERIMENT=nogreenteagc is there if you need to compare.
  4. Reducing allocations is still the bigger lever. Fewer pointers and fewer short-lived objects mean less to mark, whichever collector you use.

Related: Go escape analysis in 5 minutes shows how to keep values off the heap in the first place, and Go scheduler covers the Ps that the collector borrows its 25% from.

Sources


Share this post:

Previous Post
Go scheduler: how a million goroutines fit on five threads