My account

Go inside: the scheduler and the garbage collector

The Go runtime runs many goroutines on a few threads (the GMP model) and frees memory with a concurrent garbage collector. A specialist knows what happens in a system call, why network waits are cheap, how preemption works, why GOMAXPROCS must match the container, how to read go tool trace and gctrace, and why fast allocation makes requests slow through GC assist.

Not reviewedWritten with AI helpReading time: 20 minOnline shop exampleGo 1.25

Author: bezzad

Contents

The problem: slow requests, but the CPU looks fine

The shop’s order service runs in Kubernetes. During a sale the team sees three strange things:

  1. p99 latency jumps from 40 ms to 300 ms, but the CPU graph shows only 60% use.
  2. The number of threads in one pod grows from 15 to 900.
  3. Requests that allocate a lot (building big JSON reports) are slow, and so are small requests on the same pod.

pprof alone does not explain this, because pprof shows where CPU time goes, not why a goroutine waited. To explain it, you must know how the runtime schedules goroutines and how the garbage collector shares the CPU.

GMP in more detail

The concurrency lesson showed the three parts: G (goroutine), M (OS thread) and P (logical processor, GOMAXPROCS of them). Here are the details that matter in interviews:

  1. Each P has a local run queue with room for 256 goroutines, plus one special slot called runnext. A goroutine that was just woken up by a channel send often goes into runnext, so the receiver runs soon and stays warm in the cache.
  2. There is one global run queue for overflow. A P checks it from time to time (about every 61 scheduling rounds), so goroutines there do not wait forever.
  3. Work stealing: a P with nothing to do takes half of the queue of a random other P. This keeps all cores busy without one central lock.
  4. Spinning threads: a few Ms without work spin for a short time looking for goroutines, before they sleep. This makes wakeups fast but costs a little CPU.

System calls, cgo and the netpoller

Blocking system call vs network wait1. G1 blocks in a file writeM1 + G1 stuck in the kernelP12. sysmon gives P1 to M2M2 runs G2, G5, G6P1 on M2sysmonNetwork wait: G3 and G4 are parked in the netpoller (epoll)No thread is held. They go back to a run queue when data arrives.
A goroutine in a blocking system call holds its thread. sysmon takes the P away and gives it to another thread, so other goroutines keep running. A goroutine that waits for the network does not hold a thread at all: the netpoller wakes it up later.

There are two very different kinds of waiting:

  1. Blocking system calls (reading a file, most cgo calls): the goroutine and its M are stuck in the kernel. A background thread called sysmon sees this after a short time and hands the P to another M. If there is no free M, the runtime creates a new thread.
  2. Network waits: Go sockets are non-blocking. When a read would block, the goroutine is parked and the socket is given to the netpoller (epoll on Linux, kqueue on macOS). The M is free at once and runs other goroutines. When data arrives, the goroutine goes back into a run queue.

This explains our second problem. The report handler wrote a big file to a slow network disk with plain file writes. Each write blocked a thread, so the runtime kept creating new threads, up to 900. Network code does not do this. Fixes:

  1. Limit how many goroutines do blocking file work at the same time, for example with a buffered channel used as a semaphore.
  2. Keep cgo calls short, or run them in a small fixed pool of workers.
  3. The default limit is 10,000 threads. Above it the program crashes. Do not raise the limit to “fix” this. Find the blocking work.
var diskSlots = make(chan struct{}, 8) // max 8 writers at a time

func writeReport(path string, data []byte) error {
	diskSlots <- struct{}{}
	defer func() { <-diskSlots }()
	return os.WriteFile(path, data, 0o644)
}

Preemption

A goroutine should not hold a P forever.

  1. Cooperative points: function calls, channel operations and allocations are places where the scheduler can switch goroutines.
  2. Asynchronous preemption (since Go 1.14): if a goroutine runs for more than about 10 ms, sysmon sends the thread a signal, and the goroutine is stopped at a safe point. So a tight loop with no function calls cannot block the whole program any more, and it cannot block the GC from starting.
  3. runtime.LockOSThread ties a goroutine to its thread. It is needed for some C libraries and OS APIs that need the same thread, like some GUI libraries. Use it only when a library asks for it.

GOMAXPROCS in containers

Setup GOMAXPROCS Result
Go 1.24, 64-core node, CPU limit 2 64 64 threads run Go code. They use the 2-CPU quota in a few ms, then the kernel throttles the pod until the next 100 ms period. Latency jumps.
Go 1.25, same pod 2 The runtime reads the cgroup CPU limit. No throttling from too many threads.
Any version, CPU request but no limit Number of cores No quota, so no throttling. More Ps can be fine here.

This is our first problem: the CPU graph shows an average, but inside each 100 ms period the pod used its whole quota early and then waited. Check the container metric for throttled periods, not only CPU use.

  1. Since Go 1.25 the default GOMAXPROCS on Linux looks at the CPU limit (not the request), and the runtime updates it if the limit changes.
  2. With older Go versions, set GOMAXPROCS yourself, or use the automaxprocs library.
  3. Setting GOMAXPROCS explicitly always wins over the automatic value.

Seeing the scheduler: trace and schedtrace

pprof answers “where is the CPU spent?”. The execution tracer answers “why did this goroutine wait?”.

import "net/http/pprof"

// Admin port only, never public.
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
curl -o trace.out "localhost:6060/debug/pprof/trace?seconds=5"
go tool trace trace.out
  1. The trace shows each P on a timeline, every goroutine, when it was runnable but waited, system calls, network waits and GC phases.
  2. Scheduler latency (time between “runnable” and “running”) is the number to look at when CPU looks fine but requests are slow.
  3. The flight recorder (runtime/trace FlightRecorder, Go 1.25) keeps the last few seconds of trace in memory. You can write it to a file only when a slow request happens.
  4. For a quick look without tools, GODEBUG=schedtrace=1000 prints the run queue sizes every second.

The GC cycle

One GC cyclepausepauseConcurrent mark (about 25% of Ps)Sweep while the program runswrite barrier onrequests runGC assistrequests runFast allocation: the goroutine must help marktime →
One GC cycle: a very short stop-the-world pause to start, concurrent marking with about a quarter of the Ps plus help from busy goroutines, a second short pause, and then sweeping while the program runs.

The Go GC is a concurrent, tri-color, mark and sweep collector. It does not move objects and it is not generational.

  1. Start (short pause): all goroutines stop for a moment so the runtime can turn on the write barrier. The pause is usually well under a millisecond.
  2. Concurrent mark: the GC marks every object that can be reached from the stacks and globals. Objects are white (not seen), grey (seen, children not scanned) or black (done). The write barrier makes sure the program cannot hide a white object behind a black one while marking runs. The GC uses about 25% of GOMAXPROCS for this work.
  3. Mark termination (short pause): the runtime finishes marking and turns off the write barrier.
  4. Sweep: the memory of white objects is freed lazily, while the program runs.

When the next cycle starts is decided by the pacer, using GOGC and GOMEMLIMIT from the performance lesson.

GC assist: why fast allocation slows everyone

If goroutines allocate faster than the background GC can mark, the heap would pass its goal. So the runtime makes allocating goroutines help mark before they get new memory. This is called GC assist.

  1. Assist work happens inside your request, so it shows up as latency, not as a “GC pause”.
  2. The goroutine that allocates most pays most, but all goroutines on the pod lose CPU to the GC. This is our third problem: the report handler allocated a lot, and small requests on the same pod became slow too.
  3. Fix it by allocating less in hot code (see the performance lesson), by moving big batch jobs to their own pods, or by giving the heap more room with GOMEMLIMIT and a higher GOGC.

Read the GC with gctrace:

GODEBUG=gctrace=1 ./orders
# gc 42 @12.3s 4%: 0.03+3.1+0.02 ms clock, ... 180->190->95 MB, ...
  1. 4% is the share of CPU the GC used since the program started.
  2. 0.03+3.1+0.02 are the start pause, the concurrent mark, and the end pause.
  3. 180->190->95 MB is the heap at start, at end, and the live heap after marking.

Go 1.25 also has an experimental GC called Green Tea (GOEXPERIMENT=greenteagc). It scans memory page by page for better cache use, and can cut GC CPU for programs with many small objects. Measure before you depend on it.

Common mistakes

Mistake Result Better way
Looking only at average CPU in a container Throttling stays hidden, p99 is high. Check throttled periods and GOMAXPROCS.
Many blocking file or cgo calls at once Hundreds of threads, then a crash at 10,000. Limit blocking work with a semaphore or a pool.
Raising the thread limit with debug.SetMaxThreads The real problem stays. Find what blocks the threads.
Using pprof to explain waiting No answer, since waiting uses no CPU. Use go tool trace and look at scheduler latency.
Calling runtime.GC() in a handler Full GC on every request, very slow. Let the pacer decide. Tune GOGC and GOMEMLIMIT.
Thinking GC cost is only the pauses Assist time inside requests is missed. Read gctrace and the trace, and allocate less.

Summary in 7 lines

  1. Each P has a local queue of 256 goroutines plus runnext, and idle Ps steal half of another queue.
  2. A blocking system call holds a thread, so sysmon gives its P to another thread.
  3. Network waits park the goroutine in the netpoller and free the thread.
  4. Since Go 1.14, long running goroutines are preempted with a signal.
  5. GOMAXPROCS must match the CPU limit, or the pod is throttled. Go 1.25 does this by default.
  6. go tool trace shows why goroutines waited. pprof shows only CPU.
  7. The GC marks concurrently with short pauses, and goroutines that allocate fast must help (GC assist).

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.