Execution Tracing and Block/Mutex Contention Profiling
Capture mutex contention profiles and execution traces with -mutexprofile and -trace to diagnose scheduler stalls. After this, lock contention and GC pauses are visible in real numbers.
Course content
Sign in to save your progress.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
Imagine your API's p99 latency just jumped from 15 ms to 280 ms under load, yet CPU usage is sitting peacefully at 18% and heap memory is completely flat. You capture a 30-second -cpuprofile—and nothing looks hot. Why?
Because CPU profiles only sample goroutines that are actively executing instructions on a CPU core. When 80 request goroutines are asleep waiting in line behind one contended sync.Mutex—or stalled on a channel or scheduler wakeup—they burn 0% CPU while tail latency explodes. Go gives you two diagnostics specifically for waiting delays: mutex/block profiles (-mutexprofile, -blockprofile) and the execution tracer (-trace).
Skip ahead
If you already capture -mutexprofile (enabling SetMutexProfileFraction), read Unlock attribution correctly, and inspect goroutine timelines in go tool trace, move on to "Reflection, Struct Tags, and go generate."
Experiment 1: Capturing a mutex contention profile and trace
Mutex profiling starts disabled (0) so unprofiled binaries pay zero overhead. Enable it inside a parallel benchmark with runtime.SetMutexProfileFraction(1) (or a sampled fraction like 100 in live production services) and pass both -mutexprofile and -trace:
package traceprof
import (
"runtime"
"sync"
"testing"
"time"
)
func BenchmarkContendedMutex(b *testing.B) {
runtime.SetMutexProfileFraction(1)
defer runtime.SetMutexProfileFraction(0)
var mu sync.Mutex
var n int
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
mu.Lock()
n++
time.Sleep(1 * time.Microsecond)
mu.Unlock()
}
})
}
$ go test -run=^$ -bench=BenchmarkContendedMutex -mutexprofile=mutex.out -trace=trace.out -benchtime=50ms .
$ go tool pprof -top -nodecount=4 mutex.out
File: traceprof.test
Type: delay
Showing nodes accounting for 81.65ms, 100% of 81.65ms total
flat flat% sum% cum cum%
81.65ms 100% 100% 81.65ms 100% sync.(*Mutex).Unlock (inline)
0 0% 100% 81.65ms 100% example.com/traceprof.BenchmarkContendedMutex.func1
0 0% 100% 81.65ms 100% testing.(*B).RunParallel.func1
Experiment 2: Why sync.(*Mutex).Unlock is at the top of the report
Seeing 81.65ms next to sync.(*Mutex).Unlock surprises almost everyone the first time: why isn't it on Lock()? Because Go measures how long waiting goroutines sat blocked and attributes that delay to the goroutine that held the lock and finally released it in Unlock()! That tells you directly which critical section held the lock too long. Look one frame up in cum—or run go tool pprof -list=BenchmarkContendedMutex mutex.out—to pinpoint the exact lines holding the mutex.
Experiment 3: Reading microsecond timelines in go tool trace
While pprof adds up totals across thousands of calls, go tool trace trace.out opens a visual timeline showing every single goroutine, OS thread, and CPU core down to the microsecond:
$ go tool trace trace.out
Inside the trace viewer, check three high-signal views:
- Goroutine analysis: Breaks down every goroutine's lifetime into execution time, sync-block wait time, network wait time, and scheduler wait time (runnable but waiting for a free CPU core).
- Synchronization blocking profile: Shows whether stalls came from mutexes, channels, or
sync.WaitGroup. - GC events: Reveals whether stop-the-world pauses or GC mark-assist work collided with your p99 latency spikes.
Experiment 4: Fixing a contended lock once you find it
When -mutexprofile confirms a single mutex is bottlenecking throughput, you normally fix it with one of three structural changes:
- Move I/O and formatting outside the lock: Never hold a
sync.Mutexwhile making an HTTP call, writing to disk, or encoding JSON—copy the minimal data under the lock, callmu.Unlock(), and do the slow work unlocked. - Shard one global map into N buckets: Replace one global
mu + mapwith 32 or 64 shards (shards[hash(key)%32]) so independent keys never wait on each other. - Switch a single counter or read-only config to
sync/atomic: Eliminates lock contention entirely.
Common mistakes
- Forgetting
runtime.SetMutexProfileFraction: Leaving it at default0produces an emptymutex.outon live services. - Recording multi-minute execution traces under heavy traffic: Traces capture every scheduler event and grow to hundreds of megabytes fast—capture 1–5 seconds at a time.
- Assuming low CPU means "network issue": Low CPU + high p99 latency is the classic signature of lock or channel contention.
💡 Tip
In live services running net/http/pprof on localhost, set runtime.SetMutexProfileFraction(100) at startup (sampling 1% of contention events with negligible overhead) so /debug/pprof/mutex always has real data ready when latency spikes.
What happens if you skip this step
Teams stuck on CPU-only profiling miss lock contention completely, blaming the database or load balancer while dozens of goroutines queue silently behind one shared sync.Mutex.
Your Go API's p99 latency spikes to 250 ms while CPU sits at 15%, and -cpuprofile shows nothing obvious. Why did the CPU profile miss the bottleneck, and which two flags expose it?
About
Capture mutex contention profiles and execution traces with -mutexprofile and -trace to diagnose scheduler stalls. After this, lock contention and GC pauses are visible in real numbers.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.