The runtime and scheduler
The runtime multiplexes goroutines onto threads and frees memory while your code runs. Here is how the scheduler moves work, and how GOGC and GOMAXPROCS change what you measure.
- 1A goroutine runs on a thread only while that thread holds a P. GOMAXPROCS is the number of Ps.
- 2An idle P steals half of another P's queue. The scheduler keeps every P busy without a central lock on the fast path.
- 3GC work scales with live data, and frequency scales with allocation. GOGC trades memory for CPU.
- 4Set GOMEMLIMIT to protect a container. Since Go 1.25, GOMAXPROCS follows the cgroup CPU limit.
// GOMAXPROCS is 1. One goroutine spins in a loop with no function call, and
// main sleeps for 10 ms. Who finishes first? The program runs itself twice:
// once with defaults, and once with asynchronous preemption turned off.
package main
import (
"fmt"
"os"
"os/exec"
"runtime"
"sync/atomic"
"time"
)
var sink int
func spin() {
total := 0
for i := range 2_000_000_000 {
total += i2
}
sink = total
}
func race() string {
runtime.GOMAXPROCS(1)1
start := time.Now()
var running atomic.Bool
go func() {
running.Store(true)
spin()
}()
for !running.Load()3 {
runtime.Gosched()
}
time.Sleep(10 * time.Millisecond)4
if time.Since(start) > 200*time.Millisecond {
return "main woke late: it waited for the loop"
}
return "main woke on time: the runtime stopped the loop"
}
func main() {
if os.Getenv("CHILD") != "" {
fmt.Println(race())
return
}
for _, debug := range []string{"", "asyncpreemptoff=1"} {
cmd := exec.Command(os.Args[0])
cmd.Env = append(os.Environ(), "CHILD=1", "GODEBUG="+debug)
out, err := cmd.Output()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("GODEBUG=%q: %s", debug, out)
}
}- 1One P, so one goroutine runs Go code at a time.
- 2No call in this loop, so no stack check, so no cooperative stop point.
- 3Main gives way until the loop has started. Time counts from before this wait.
- 4Main needs a P to wake. Only the spinner has it.
| setting | recorded output | status |
|---|---|---|
| default | main woke on time: the runtime stopped the loop | Preempted |
| asyncpreemptoff=1 | main woke late: it waited for the loop | As before Go 1.14 |
- The sysmon thread sees that a goroutine has held its P for 10 ms.
- It sends SIGURG to the thread. The signal handler stops the goroutine at a safe instruction.
- The same stop is what lets a garbage collection begin during a tight loop.
- Programs that make raw system calls can now see EINTR. Retry those calls.
Since Go 1.14, a tight loop cannot hold a P forever. The runtime preempts it with a signal after about 10 ms.
| what it is | how many | |
|---|---|---|
| G | Stack, state and the function to run. | Millions |
| M | An OS thread. | Limit 10,000; change it with debug.SetMaxThreads |
| P | A run queue and the allocator caches. | GOMAXPROCS |
- A P runs runnext, then its local queue, then the global queue. Then it steals.
- A blocked goroutine parks. It holds no M and no P.
G is the goroutine, M is the thread, P is the right to run Go code. Threads can outnumber Ps, because a thread in a system call does not need a P.
See it: the scheduler, step by step
a model that follows runtime/proc.go; the local queue holds 4 here and 256 in the runtimestep 1 of 16, runtime: schedinit
The program starts
G1 runs on P0. Thread M0 holds P0. P1 is idle and has no thread.
A test replays each step and proves that no goroutine is lost or doubled. The execution tracer confirms that real goroutines move between Ps (panel N).
New work goes to runnext. Overflow goes global. Idle Ps steal half. sysmon takes back a P from a thread stuck in the kernel.
| 100 goroutines in | recorded | status |
|---|---|---|
| time.Sleep | under 50 threads: true | Parks |
| conn.Read | under 50 threads: true | Parks in the netpoller |
| syscall.Read | at least 100 threads: true | Each holds a thread |
| a cgo call | A thread for the call | Same as a system call |
- On a system call, the thread keeps its P at first. sysmon retakes the P after at least 20 µs if other work waits.
- Sockets use the netpoller, so one thread can serve many waits.
- On return, a goroutine takes an idle P, or goes to the global queue.
A goroutine that waits in the runtime costs a stack. A goroutine in a blocking system call also costs a thread.
| situation | result |
|---|---|
| Goroutine runs for 10 ms | sysmon marks it. It stops at its next function entry. |
| Goroutine has no calls | A signal stops it. Since Go 1.14. |
| Preempted goroutine | Goes to the global queue. |
| Goroutine parks or calls Gosched | Gives up the P at once. |
| runnext goroutines | Share one time slice, so two goroutines cannot starve the rest. |
| Stop the world | Preempts every P. Latency here is the time to reach each one. |
Do not add runtime.Gosched to a loop to be fair. The runtime handles that.
Preemption has two paths: a check at function entry, and a signal for code with no calls.
// A local variable stays on the stack, and the stack grows while p points at
// it. Does the pointer survive?
package main
import (
"fmt"
"unsafe"
)
func deep(n int) int {1
var pad [256]byte
pad[n%256] = 1
if n == 0 {
return int(pad[0])
}
return deep(n-1) + int(pad[n%256])
}
func main() {
done := make(chan struct{})
go func() {
defer close(done)
x := 42
p := &x
before := uintptr(unsafe.Pointer(p))
deep(10_000)
after := uintptr(unsafe.Pointer(p))
fmt.Println("address changed:", before != after2)
fmt.Println("p still points at x:", p == &x3, *p)
}()
<-done
}- 1Each function checks the stack bound at entry. A failed check calls the runtime, which grows the stack.
- 2The stack is now at a new address.
- 3The runtime rewrote p during the copy. This needs precise stack maps, in place since Go 1.3.
Recorded output: address changed: true; p still points at x: true 42
A stack starts at about 2 KB and doubles by copying. The runtime fixes pointers into the stack, so my code cannot see the move.
| question | answer |
|---|---|
| Start size | 2,048 B here. Since Go 1.19 it follows the average use of the program. |
| Growth | Doubles, then copies. Contiguous since Go 1.3. |
| Shrink | During GC, to half, if the goroutine uses under a quarter. |
| Limit | 1 GB on 64-bit systems. debug.SetMaxStack changes it. |
| At the limit | "fatal error: stack overflow". Recover cannot catch it. |
| Why not a large fixed stack | A million goroutines would reserve too much address space and memory. |
Deep recursion costs a copy at each doubling, and the amortized cost is small. Stack overflow is fatal, and recover cannot stop it.
- Mark starts from the roots: goroutine stacks and globals. It follows every pointer in the heap.
- The write barrier records pointer writes during mark, so a moved pointer cannot hide a live object.
- Go uses a hybrid barrier: a Yuasa deletion barrier with a Dijkstra insertion barrier. Stacks need no rescan.
- The target for background mark is 25% of GOMAXPROCS. Idle Ps can also help.
- Go does not move objects and has no generations. Sweep frees unmarked memory as allocation needs it.
The collector marks concurrently with a write barrier on. It stops the world twice, briefly, and those pauses do not grow with the heap.
| before | Green Tea | |
|---|---|---|
| Work list holds | Objects | Whole pages |
| Queue order | A stack | First in, first out |
| Locality | Jumps around memory | Scans nearby objects together |
| Scale with cores | A shared queue contends | Smaller queues contend less |
| GC CPU here, GOGC 100 | 3.4 s | 2.1 s |
- On this workload, Green Tea used 39% less GC CPU. Results vary by program. Small objects with many pointers gain most.
- Newer amd64 CPUs gain about 10% more from vector instructions.
- GOEXPERIMENT=nogreenteagc still builds the old collector in Go 1.27.3. The 1.26 notes expected that to end in 1.27.
Green Tea scans pages and not single objects. The release notes expect 10 to 40% less GC cost, and it needs no change to your code.
| GOGC | live | goal | goal / live |
|---|---|---|---|
| 25 | 148 MiB | 185 MiB | 1.25 |
| 50 | 160 MiB | 240 MiB | 1.50 |
| 100 | 172 MiB | 344 MiB | 2.00 |
| 200 | 179 MiB | 538 MiB | 3.00 |
| 400 | 172 MiB | 861 MiB | 5.00 |
Target heap = live heap + (live heap + GC roots) × GOGC / 100. Roots count since Go 1.18. They are small in this program. The minimum total heap target is 4 MiB × GOGC / 100.
The next cycle starts when the heap reaches live plus live times GOGC over 100. Doubling GOGC halves the GC work and doubles the headroom.
| GOGC | cycles | peak heap | GC CPU | wall time | pause p50 | pause p99 |
|---|---|---|---|---|---|---|
| 25 | 112 | 186 MiB | 7.9 s | 1.3 s | 66 µs | 164 µs |
| 50 | 53 | 243 MiB | 3.8 s | 0.8 s | 49 µs | 164 µs |
| 100 | 28 | 333 MiB | 2.1 s | 0.6 s | 66 µs | 164 µs |
| 200 | 15 | 461 MiB | 1.1 s | 0.5 s | 66 µs | 131 µs |
| 400 | 7 | 752 MiB | 0.5 s | 0.5 s | 57 µs | 115 µs |
128 MiB live, in a tree of 128-byte nodes, with 4 GiB of churn from 4 goroutines. The test asserts that cycles and GC CPU fall and peak heap rises at each step. Pause numbers vary by run and are not asserted. Each pause is a bucket bound of the histogram.
GOGC trades memory for CPU. Pauses stay near or under 1 ms at every value, so I tune it for cost and not for latency.
| case | use it |
|---|---|
| A container with a fixed limit: leave 5 to 10% headroom | Approved |
| GOGC=off with a limit, in a dedicated container | Most heap, least GC |
| Shared memory with other programs | Keep a GOGC too |
| A CLI tool, or memory that grows with input | Not approved |
| A program already near its limit | Slow, not safe |
Measured: GOGC=off and GOMEMLIMIT=256MiB peaked at 236 MiB of heap, with 58 cycles. The limit covers all runtime memory, not only the heap. The GC CPU limit is roughly 50%.
In a container, I set GOMEMLIMIT to about 90% of the limit. It is a soft limit, and the GC stops at about 50% CPU rather than thrash.
gc 32 @0.719s 7%:4 0.062+7.9+0.057 ms clock1,
1.0+1.0/27/41+0.91 ms cpu2, 294->333->174 MB, 345 MB goal3,
0 MB stacks, 0 MB globals, 16 P- 1Wall time: sweep termination, concurrent mark, mark termination. The first and third are the pauses.
- 2CPU time. The middle term splits into assist, background and idle mark.
- 3The heap size at which this cycle aimed to finish.
- 4Share of time in GC since the program started.
The runtime package documents this format. The format can change between releases.
The three clock numbers are pause, concurrent mark, pause. The MB triple is heap at start, at end, and live.
| GOMAXPROCS | wall time | Ps used | moves between Ps | of resumes |
|---|---|---|---|---|
| 1 | 0.86 s | 1 | 0 | 1,503 |
| 2 | 0.44 s | 2 | 314 | 1,504 |
| 4 | 0.23 s | 4 | 850 | 1,991 |
| 8 | 0.14 s | 8 | 2,220 | 3,320 |
| 16 | 0.09 s | 16 | 7,293 | 8,225 |
32 goroutines wake at one gate, 400 times, and each does a short burst of CPU work. The test asserts that p99 latency and wall time fall from 1 to 4 to 16 Ps. The last three columns come from an execution trace. Moves count a goroutine that resumed on a different P.
Scheduling latency is the time a runnable goroutine waits for a P. If it grows, I have too few Ps for the runnable work.
| setting | result |
|---|---|
| Default, on Linux, with a CPU limit | The lower of logical CPUs and the cgroup limit. |
| Limit or CPU count changes | The runtime updates GOMAXPROCS, on all systems. |
| CPU request with no limit | Ignored. |
| GOMAXPROCS variable or a manual call | Both behaviours turn off. |
| containermaxprocs=0, updatemaxprocs=0 | Turn each one off by GODEBUG. |
| runtime.SetDefaultGOMAXPROCS | Returns to the default. |
Before Go 1.25, a container with a low CPU limit on a large host got too many Ps, and the kernel throttled it. The new default needs a go directive of 1.25 or later.
Since Go 1.25, GOMAXPROCS follows the cgroup CPU limit on Linux and updates at run time. CPU requests do not count, only limits.
s := []metrics.Sample{
{Name: "/gc/cycles/total:gc-cycles"},
{Name: "/cpu/classes/gc/total:cpu-seconds"},
{Name: "/cpu/classes/user:cpu-seconds"},
{Name: "/sched/pauses/total/gc:seconds"1},
{Name: "/gc/heap/goal:bytes"},
{Name: "/gc/heap/live:bytes"},
{Name: "/gc/stack/starting-size:bytes"},
}
metrics.Read(s)2
pauses := s[3].Value.Float64Histogram()- 1A histogram of stop-the-world time for GC.
- 2Reuse the slice. Read fills each sample, with no stop of the world.
// quantile reads a fraction from a runtime/metrics histogram. It returns the
// upper bound of the bucket that holds it.
func quantile(h *metrics.Float64Histogram, q float64) float64 {
var total uint64
for _, c := range h.Counts {
total += c
}
want := uint64(q * float64(total))
var seen uint64
for i, c := range h.Counts {
seen += c
if c > 0 && seen >= want {
return h.Buckets[i+1]1
}
}
return 0
}- 1Buckets has one more entry than Counts. A bucket gives a bound, not an exact value.
runtime/metrics is the stable way to read the runtime. Each sample has a name with a unit, and latency comes as a histogram.
if path := os.Getenv("TRACE"); path != "" {
f, err := os.Create(path)
if err != nil {
fatal(fmt.Errorf("create trace: %w", err))
}
defer f.Close()
if err := trace.Start(f)1; err != nil {
fatal(fmt.Errorf("start trace: %w", err))
}
defer trace.Stop()
}- 1Since Go 1.21 this costs much less CPU, up to 10 times less than before on amd64 and arm64.
| question | tool |
|---|---|
| Where does CPU go? | pprof CPU profile |
| Why did this request stall? | go tool trace |
| A rare slow event in production | trace.FlightRecorder |
| Too few Ps? | /sched/latencies:seconds |
| GC pauses? | /sched/pauses/total/gc:seconds |
pprof says where the CPU goes. The tracer says when goroutines waited. For a rare event, I use a flight recorder.
| since | what changed | what it means here |
|---|---|---|
| 1.3 | Contiguous stacks replace segmented stacks. Stack values are precise. | Stacks grow by copying. |
| 1.5 | A concurrent collector. GOMAXPROCS defaults to the number of cores. | Pauses fall to under 10 ms. |
| 1.8 | No stop-the-world stack rescan. | Pauses usually under 100 µs. |
| 1.14 | Asynchronous preemption. | A tight loop cannot hold a P. |
| 1.18 | GOGC counts GC roots. | The heap goal includes stacks and globals. |
| 1.19 | GOMEMLIMIT. Start stack size follows average use. GC CPU limit of 50%. | A real memory budget for containers. |
| 1.21 | GC tuning cuts tail latency by up to 40%. Traces cost far less. | Keep a tracer on in more places. |
| 1.24 | Swiss Table maps. A new runtime mutex. runtime.AddCleanup. Package weak. | 2 to 3% less CPU on average. |
| 1.25 | Container-aware GOMAXPROCS. SetDefaultGOMAXPROCS. trace.FlightRecorder. Green Tea as an experiment. | Container CPU limits work with no extra library. |
| 1.26 | Green Tea is the default. Scheduler metrics under /sched/goroutines. Heap base address is randomized. cgo calls cost about 30% less. | Count goroutines by state with runtime/metrics. |
| 1.27 | Size-specialized allocation for objects under 80 bytes. Stack dumps print pprof labels. | Small allocations cost up to 30% less, about 1% in real programs. |
| when | the moment | what to do or say |
|---|---|---|
| build | You want a goroutine per request. | That is the model. A parked goroutine costs a stack, and net/http does this for you. |
| build | Work is CPU-bound. | Size the pool near GOMAXPROCS. More goroutines only add latency. See G12. |
| talk | "How many goroutines can you run?" | Memory sets the limit, at about 3 KB each. Threads stay near GOMAXPROCS, except during blocking system calls. |
| talk | "p99 rose after a deploy." | Read /sched/latencies:seconds and the GC pause histogram. Then take a trace of one slow request. |
| talk | "The pod is OOM-killed." | Set GOMEMLIMIT with 5 to 10% headroom. Then find what grows with a heap profile. |
| talk | "Why not pool everything?" | GC cost follows live pointers. Pool hot buffers only, and measure. |
| talk | "How does Go compare with a thread per request?" | Go parks a goroutine in user space, and sockets share the netpoller. So a wait holds no thread. |
I keep the live heap small and let GOGC stay at 100 until a profile says otherwise.
0 of 8 known
Predict the output. GOMAXPROCS is 1.
package main import ( "fmt" "runtime" "strings" "sync" ) func main() { runtime.GOMAXPROCS(1) var mu sync.Mutex var out strings.Builder var wg sync.WaitGroup for i := range 5 { wg.Go(func() { mu.Lock() defer mu.Unlock() fmt.Fprint(&out, i, " ") }) } wg.Wait() fmt.Println(out.String()) }Predict the output.
// 10,000 goroutines wait on one channel. How many threads does that take? package main import ( "fmt" "runtime" "runtime/metrics" "time" ) func main() { gate := make(chan struct{}) for range 10_000 { go func() { <-gate }() } time.Sleep(50 * time.Millisecond) s := []metrics.Sample{{Name: "/sched/threads/total:threads"}} metrics.Read(s) fmt.Println("goroutines:", runtime.NumGoroutine()) fmt.Println("under 50 threads:", s[0].Value.Uint64() < 50) close(gate) }Predict the output. GOMAXPROCS is 1, and the spin takes about 1 s.
// GOMAXPROCS is 1. One goroutine spins in a loop with no function call, and // main sleeps for 10 ms. Who finishes first? The program runs itself twice: // once with defaults, and once with asynchronous preemption turned off. package main import ( "fmt" "os" "os/exec" "runtime" "sync/atomic" "time" ) var sink int func spin() { total := 0 for i := range 2_000_000_000 { total += i } sink = total } func race() string { runtime.GOMAXPROCS(1) start := time.Now() var running atomic.Bool go func() { running.Store(true) spin() }() for !running.Load() { runtime.Gosched() } time.Sleep(10 * time.Millisecond) if time.Since(start) > 200*time.Millisecond { return "main woke late: it waited for the loop" } return "main woke on time: the runtime stopped the loop" } func main() { if os.Getenv("CHILD") != "" { fmt.Println(race()) return } for _, debug := range []string{"", "asyncpreemptoff=1"} { cmd := exec.Command(os.Args[0]) cmd.Env = append(os.Environ(), "CHILD=1", "GODEBUG="+debug) out, err := cmd.Output() if err != nil { fmt.Println(err) os.Exit(1) } fmt.Printf("GODEBUG=%q: %s", debug, out) } }Predict the output. deep calls itself 10,000 times.
// A local variable stays on the stack, and the stack grows while p points at // it. Does the pointer survive? package main import ( "fmt" "unsafe" ) func deep(n int) int { var pad [256]byte pad[n%256] = 1 if n == 0 { return int(pad[0]) } return deep(n-1) + int(pad[n%256]) } func main() { done := make(chan struct{}) go func() { defer close(done) x := 42 p := &x before := uintptr(unsafe.Pointer(p)) deep(10_000) after := uintptr(unsafe.Pointer(p)) fmt.Println("address changed:", before != after) fmt.Println("p still points at x:", p == &x, *p) }() <-done }Predict the output. The limit is 1 MiB.
// Recursion with no base case, with the stack limit set to 1 MiB. The child // run prints addresses, so the parent keeps only the lines that do not. package main import ( "bufio" "bytes" "fmt" "os" "os/exec" "runtime/debug" "strings" ) func recurse(n int) int { return recurse(n+1) + 1 } func main() { if os.Getenv("CHILD") != "" { debug.SetMaxStack(1 << 20) fmt.Println(recurse(0)) return } cmd := exec.Command(os.Args[0]) cmd.Env = append(os.Environ(), "CHILD=1") var out bytes.Buffer cmd.Stderr = &out err := cmd.Run() scan := bufio.NewScanner(&out) for scan.Scan() { line := scan.Text() fatal := strings.HasPrefix(line, "fatal error") if fatal || strings.Contains(line, "exceeds") { fmt.Println(line) } } fmt.Println("exit:", err) }Predict the output.
// 100 goroutines block in three ways. How many OS threads does each take? package main import ( "fmt" "net" "os" "runtime/metrics" "sync" "syscall" "time" ) func threads() int { s := []metrics.Sample{{Name: "/sched/threads/total:threads"}} metrics.Read(s) return int(s[0].Value.Uint64()) } // during starts 100 goroutines and returns the thread count while they block. func during(block func()) int { var wg sync.WaitGroup for range 100 { wg.Go(block) } time.Sleep(50 * time.Millisecond) n := threads() wg.Wait() return n } func fatal(err error) { fmt.Println(err) os.Exit(1) } func main() { slept := during(func() { time.Sleep(100 * time.Millisecond) }) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { fatal(err) } defer ln.Close() polled := during(func() { c, err := net.Dial("tcp", ln.Addr().String()) if err != nil { fatal(err) } defer c.Close() c.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) c.Read(make([]byte, 1)) }) syscalled := during(func() { fds := make([]int, 2) if err := syscall.Pipe(fds); err != nil { fatal(err) } defer syscall.Close(fds[0]) defer syscall.Close(fds[1]) time.AfterFunc(100*time.Millisecond, func() { syscall.Write(fds[1], []byte{1}) }) syscall.Read(fds[0], make([]byte, 1)) }) fmt.Println("100 in time.Sleep, under 50 threads:", slept < 50) fmt.Println("100 in a socket read, under 50 threads:", polled < 50) fmt.Println("100 in a raw blocking read, at least 100 threads:", syscalled >= 100) }Predict the output.
package main import ( "fmt" "runtime" "runtime/debug" ) var sink []byte func cycles(alloc func()) uint32 { var before, after runtime.MemStats runtime.ReadMemStats(&before) alloc() runtime.ReadMemStats(&after) return after.NumGC - before.NumGC } func churn() { for range 2000 { sink = make([]byte, 1<<20) } } func main() { debug.SetGCPercent(-1) fmt.Println("GOGC off, 2 GiB allocated, cycles:", cycles(churn)) debug.SetMemoryLimit(128 << 20) fmt.Println("then a 128 MiB limit, cycles > 0:", cycles(churn) > 0) }Predict the output.
package main import ( "fmt" "runtime" ) func main() { start := runtime.GOMAXPROCS(0) runtime.GOMAXPROCS(2) fmt.Println("after GOMAXPROCS(2):", runtime.GOMAXPROCS(0)) runtime.SetDefaultGOMAXPROCS() fmt.Println("default restored:", runtime.GOMAXPROCS(0) == start) }
- time slice
- 10 ms, then sysmon preempts.
- local queue
- 256 goroutines. Steal takes half.
- global check
- Every 61st tick.
- start stack
- 2,048 B; limit 1 GB.
- GC pause
- p99 of 164 µs at GOGC 100, measured.
- GC goal
- 2.0 times the live heap at GOGC 100.
- GOGC 25 to 400
- 186 MiB to 752 MiB of heap; 7.9 s to 0.5 s of GC CPU.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16 unless set, on a busy machine. The first three rows come from the runtime source. Use the others as orders of magnitude.