How can you observe the scheduler? (schedtrace, go tool trace, pprof)
Question 172HardGo 1.22 to 1.25
GODEBUG=schedtrace=1000prints a line every second withgomaxprocs,idleprocs,threads,spinningthreads,runqueue(global) and the per-P local queue lengths[..]. Addingscheddetail=1dumps every G, M and P.- Execution tracer (
runtime/trace,go test -trace, or/debug/pprof/trace?seconds=5) opened withgo tool trace. It shows per-P timelines, when goroutines were created, blocked and unblocked, syscalls, GC, and the scheduler latency profile. Tracing overhead fell to about 1–2% in Go 1.21. The flight recorder (Go 1.25) keeps a rolling buffer you can snapshot. - pprof: the
goroutineprofile shows counts and stacks. Theblockprofile (enable withruntime.SetBlockProfileRate) and themutexprofile (SetMutexProfileFraction) show where goroutines wait. - runtime/metrics:
/sched/latencies:secondsis a histogram of how long goroutines sit runnable before they run./sched/goroutines:goroutinesis the goroutine count.
f, _ := os.Create("trace.out")
defer f.Close()
trace.Start(f)
defer trace.Stop()
What the interviewer wants to hear: high scheduler latency together with CPU below saturation points to lock contention, GOMAXPROCS throttling or GC assists. The tools let you tell these causes apart.
More on Goroutines & the Scheduler
- Q170Concurrency vs. parallelism in Go — can goroutines run in parallel with GOMAXPROCS=1?
- Q171What are the goroutine states and what transitions happen on a channel block?
- Q173Why can many CPU-bound goroutines hurt performance, and how do you size a worker pool?
- Q174How do goroutines interact with cgo, and why can cgo calls be expensive?
- Q175Implement a bounded, cancellable fan-out that returns the first error and does not leak goroutines.
- Q176Is creating a goroutine per request (e.g., in net/http) a good design? What are the risks?