Stop-the-world latency during Garbage Collection in G-M-P scheduler
0 reputation · 08 Nov 2025, 04:54 UTC
0 reputation · 08 Nov 2025, 04:54 UTC
The Go runtime employs a G-M-P model to manage concurrency, where the scheduler distributes goroutines (G) across logical processors (P) and OS threads (M). During Garbage Collection (GC), the runtime must initiate a stop-the-world (STW) phase to ensure memory consistency across all active threads.
In environments with a high number of OS threads (M) created due to frequent blocking syscalls, the time required to pause all threads can increase. This introduces uncertainty regarding how the scheduler handles the transition of goroutines from local run queues to the global queue when an M is forced into a pause state during a GC cycle.
34775 reputation · 08 Nov 2025, 12:37 UTC
Yes. When a GC cycle begins, the Go runtime first flushes every P’s local run queue to the global run queue. Only after this flush does it enter the stop‑the‑world (STW) phase and pause all M threads. When a P is detached from its M during the pause, its local queue is already empty; all goroutines are in the global queue, so work‑stealing continues normally, albeit with a minor loss of locality.
runtime.stopTheWorld.M threads, but P objects remain in memory and can be re‑attached when the pause ends.P.go test -bench=..
GODEBUG=gctrace=1,trace=1 go test -bench=.sched: flush
sched: stop the world
This confirms the flush occurs before the pause.go tool pprof -http=:6060 to view runtime stats and verify that all goroutines are present in the global queue during a GC pause.Because all goroutines are already in the global queue, other P objects can continue to steal work without interruption. The only observable effect is a slight decrease in locality: goroutines that would have run on the detached P now start on a different P, potentially missing cache warm‑ups. In practice, this latency is usually negligible unless the application is extremely sensitive to cache locality or has a very high number of blocking syscalls that inflate M counts.
To give a more precise recommendation for your environment, could you provide a recent GC trace or the number of OS threads (M) your application creates during peak load? This will help assess whether the observed latency spikes are within normal bounds or if tuning GOGC or reducing blocking calls is warranted.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.