Profiling & Performance
- Run a measure → hypothesise → change → re-measure loop driven by a stated goal (p99, throughput, cost).
- Collect and read every pprof profile type, including flat vs cumulative time, alloc vs in-use memory, and block/mutex contention.
- Use
go tool trace(and the Go 1.25 flight recorder) for latency problems a CPU profile can't explain. - Apply profile-guided optimization (PGO) safely in a CI/CD pipeline.
- Recognise the common Go hot spots in services and benchmark changes with statistical rigour.
TL;DR
- Start from a goal and a symptom (checkout p99 rose from 120 ms to 300 ms), confirm it's in the Go process (not the DB or network), then profile.
- CPU profile shows where time is spent running; trace shows where time is spent waiting (scheduler, GC, syscalls, blocking). Latency problems often need the trace.
- Heap profile:
inuse_spacefor leaks and footprint,alloc_space/alloc_objectsfor GC pressure. Compare snapshots with-diff_base. - Block and mutex profiles are off by default; enable them at a sampling rate to find contention.
- PGO (GA in Go 1.21): commit a representative production CPU profile as
default.pgoin the main package; the Go team reports typical gains of a few percent CPU. - Common wins in services: fewer allocations, no per-request regex/template compilation, batched DB calls, right-sized pools, less lock contention, cheaper logging.
- Trust only
-count≥ 10 +benchstatfor micro-benchmarks and constant-rate load tests for latency.
Why it matters
- Latency SLOs: card authorization and checkout APIs have tight p99 budgets; an extra 50 ms in your service is 50 ms the issuer or the customer waits.
- Capacity for peaks: a flash sale at 20× normal traffic is a CPU problem first; 30% less CPU per request is 30% fewer pods to pre-scale.
- Cost: a service fleet's cloud bill is proportional to CPU-seconds; profiling is often the cheapest cost optimisation available (see Capacity Planning & Cost).
- Incidents: "the pods are at 100% CPU and we don't know why" is solved in minutes by someone who can grab a 30-second profile and read it.
Core concepts
Workflow
Before profiling Go, check the boring things: is the time in a slow SQL query (Query Optimization), a saturated connection pool, a downstream PSP, or the network? Distributed traces usually answer this first. OS-level tools are in Linux Performance Analysis.
Profile types
| Profile | What it samples | Enable | Use for |
|---|---|---|---|
profile (CPU) | Stacks of running goroutines, ≈100 samples/s | Always available | Hot code paths |
heap | Live allocations (sampled, ≈1 per 512 KB allocated) | Always on | Leaks, footprint (inuse_*), GC pressure (alloc_*) |
allocs | Same data, defaults to alloc_space view | Always on | Allocation hot spots |
goroutine | Stacks of all goroutines | Always available | Leaks, deadlocks, "what is everyone doing" |
block | Time goroutines spend blocked on channels, select, sync.Cond, mutexes | runtime.SetBlockProfileRate | Waiting on synchronisation |
mutex | Holders of contended mutexes (who made others wait) | runtime.SetMutexProfileFraction | Lock contention |
threadcreate | Stacks that created OS threads | Always | Thread explosions from syscalls/cgo |
goroutineleak | Goroutines blocked on unreachable primitives | Go 1.26 GOEXPERIMENT=goroutineleakprofile | Leak detection |
Collecting profiles
Expose net/http/pprof on an internal admin port only:
func startAdmin(addr string) {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
runtime.SetBlockProfileRate(10_000) // ≈1 sample per 10 µs spent blocked
runtime.SetMutexProfileFraction(100) // sample 1 in 100 contention events
srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
go func() { _ = srv.ListenAndServe() }()
}
(pprof.Index also serves the named profiles — heap, goroutine, block, mutex — under /debug/pprof/<name>.) Importing _ "net/http/pprof" registers handlers on http.DefaultServeMux; if your public API also uses the default mux, you have just published your profiler — use an explicit mux as above.
# 30 s CPU profile, opened in the browser UI (flame graph, source, graph views)
go tool pprof -http=:0 'http://localhost:6060/debug/pprof/profile?seconds=30'
# Heap: what's live now, and what has been allocated
go tool pprof -http=:0 -sample_index=inuse_space http://localhost:6060/debug/pprof/heap
go tool pprof -http=:0 -sample_index=alloc_space http://localhost:6060/debug/pprof/heap
# Goroutines grouped by stack, plain text
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=1' | head -50
# From benchmarks
go test -run='^$' -bench=Normalize -cpuprofile cpu.out -memprofile mem.out ./internal/events
go tool pprof -http=:0 cpu.out
In Kubernetes, kubectl port-forward pod/payments-api-7c9 6060 reaches the admin port without exposing it. Continuous profiling (Grafana Pyroscope, Parca, cloud profilers) samples every pod all the time at low overhead, so you can look at the profile from the incident window instead of trying to reproduce it.
Reading a profile
- flat: time in the function itself. cum: time in the function plus everything it calls. Sort by
flatto find leaf hot spots, bycumto find expensive subtrees. top,top -cum,list FuncName(annotated source),peek FuncName(callers/callees) in the interactive CLI; the web UI has the same plus flame graphs.- Flame graph: x-axis is the share of samples (not time order); y-axis is stack depth. Look for wide frames. A wide plateau of
runtime.mallocgcandruntime.gcBgMarkWorkermeans allocation/GC cost; widesyscallframes mean I/O;runtime.futex/lock2hints at contention. - Compare two profiles:
go tool pprof -diff_base before.pb.gz after.pb.gz— essential for "what grew?" in heap investigations. - Labels: tag work with
pprof.Do(ctx, pprof.Labels("route", route), func(ctx context.Context) { ... })and filter with-tagfocus=route=POST_/v1/paymentsto see one endpoint's cost.
Heap views decoded:
| View | Meaning | Question it answers |
|---|---|---|
inuse_space | Bytes live at the last GC | What holds memory now? (leaks, caches) |
inuse_objects | Objects live | Many small objects bloating GC mark time? |
alloc_space | Bytes allocated since start | What drives GC frequency? |
alloc_objects | Allocations since start | Where do allocs/op come from? |
Execution traces
A CPU profile can't see a goroutine that is waiting. If p99 is high while CPU is low, you need an execution trace: it records goroutine creation/blocking/unblocking, scheduler decisions, GC phases, syscalls and network waits with timestamps.
curl -s -o trace.out 'http://localhost:6060/debug/pprof/trace?seconds=5'
go tool trace trace.out
The viewer shows per-P timelines plus analyses: goroutine analysis (time running vs runnable vs blocked per function), scheduler latency, and network/sync/syscall blocking profiles. Typical findings: goroutines runnable but not running (CPU starvation or throttling — check GOMAXPROCS vs CPU limit), long GC assist stretches on request goroutines, a single goroutine serialising work, or time blocked in pgxpool waiting for a connection.
Tracing overhead dropped substantially in Go 1.21, making short traces in production practical. Annotate application work so it shows up in the trace:
ctx, task := trace.NewTask(ctx, "capturePayment")
defer task.End()
trace.WithRegion(ctx, "pspCall", func() { err = psp.Capture(ctx, id) })
Flight recorder (Go 1.25): keep the last few seconds of trace in memory and dump it only when something goes wrong — the trace of a slow request, captured after the fact:
fr := trace.NewFlightRecorder(trace.FlightRecorderConfig{
MinAge: 10 * time.Second,
MaxBytes: 32 << 20,
})
if err := fr.Start(); err != nil {
return err
}
// In middleware, after a request:
if elapsed > 2*time.Second && dumpLimiter.Allow() {
f, err := os.Create(fmt.Sprintf("/tmp/slow-%d.trace", time.Now().Unix()))
if err == nil {
_, _ = fr.WriteTo(f)
_ = f.Close()
}
}
Profile-guided optimization (PGO)
PGO feeds a CPU profile into the compiler so it can optimise what's hot in production: more aggressive inlining of hot calls and devirtualization of hot interface calls (an interface call whose concrete type is almost always *pgPaymentRepo gets a fast direct path).
# 1. Grab representative CPU profiles from production (several pods, normal traffic)
curl -s -o pod1.pprof 'http://payments-api-0:6060/debug/pprof/profile?seconds=60'
curl -s -o pod2.pprof 'http://payments-api-1:6060/debug/pprof/profile?seconds=60'
# 2. Merge and place in the main package directory
go tool pprof -proto pod1.pprof pod2.pprof > cmd/api/default.pgo
# 3. Build normally: -pgo=auto (the default since Go 1.21) picks up default.pgo
go build -o payments-api ./cmd/api
- Gains: the Go team reported roughly 2–7% CPU improvement on a representative set of programs at Go 1.21; your service may see more or less. Measure.
- Profiles are robust to source changes — a slightly stale profile still helps — and profiles taken from PGO-built binaries are fine to feed back in.
- Costs: longer builds and a profile file in the repository to refresh periodically (e.g. monthly or per major release).
- Use a profile from realistic traffic. A profile from a load test that only hits health checks optimises the wrong code.
Common optimisations in Go services
Ordered roughly by how often they matter:
- Algorithmic and I/O fixes: N+1 queries → one
IN/ANY($1)or batch; per-item API calls → batch endpoints; missing indexes. These dwarf everything below. - Allocation reduction: preallocation, buffer reuse, avoiding
fmtandanyboxing on hot paths (details in Memory, GC & Escape Analysis). - Compile once:
regexp.MustCompile,template.Must(template.ParseFS(...)), prepared statements — at init or construction, never per request. - Serialization:
encoding/jsonuses reflection; for very hot payloads consider code-generated encoders or the experimentalencoding/json/v2(Go 1.25,GOEXPERIMENT=jsonv2). Often simply decoding into smaller structs helps. - Contention: shard hot mutexes, use atomics for counters,
atomic.Pointerfor read-mostly config; check the mutex profile. - Pools and limits: DB pool waits (
pgxpool.Stat().EmptyAcquireCount()), HTTP transportMaxIdleConnsPerHost, worker pool sizes. - Logging cost: disabled debug logs that still format arguments, JSON logs on every inner loop iteration. Use
slog.LogAttrsand level checks (log.Enabled(ctx, slog.LevelDebug)) for expensive attributes. - Syscalls: buffered I/O (
bufio), fewer small writes, keep-alive connections.
A small real example (one laptop, Apple M5, Go 1.26; your numbers will differ): an event normaliser that compiled a regexp and used fmt.Sprintf per call, versus one with a package-level regexp and string concatenation:
BenchmarkNormalizeSlow-10 1835229 646.2 ns/op 1065 B/op 19 allocs/op
BenchmarkNormalizeFast-10 3309271 361.1 ns/op 233 B/op 7 allocs/op
The CPU profile pointed at regexp.compile and fmt.(*pp).printArg; the fix was two lines.
Benchmarking discipline
- Micro-benchmarks (
go test -bench): useb.Loop(Go 1.24),-benchmem, realistic inputs, and-count=10withbenchstatfor old vs new. Run on an idle machine; don't compare across machines. See Testing & Benchmarking. - Load tests for latency: use a constant arrival rate (vegeta, k6 constant-arrival-rate, wrk2). Closed-loop tools that wait for each response before sending the next under-report tail latency when the server slows down — the "coordinated omission" problem.
- Report percentiles (p50, p95, p99, p99.9) and throughput at a fixed error budget, not averages.
- Verify in production: canary the change and compare CPU per request and p99 from real metrics. The micro-benchmark is a hypothesis; production is the experiment.
- Write down the result, including "no improvement, reverted". Teams waste weeks re-trying the same micro-optimisations.
Trade-offs
| Tool / technique | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| CPU profile | Low overhead, precise hot spots | Blind to waiting | CPU-bound, high utilisation |
| Heap / alloc profile | Shows footprint and GC drivers | Sampled; no lifetime info | Memory growth, GC CPU |
| Block / mutex profiles | Pinpoints contention | Must be enabled; sampling overhead | High latency with low CPU, lock-heavy code |
| Execution trace | Full timeline incl. scheduler and GC | Large files; short windows | Tail latency, scheduling, GC assist questions |
| Flight recorder | Captures the moment after it happened | Memory for the ring buffer | Rare slow requests in production |
| Continuous profiling | Historical profiles from every pod | Agent and storage cost | Fleets with recurring performance questions |
| PGO | Free CPU gains, no code change | Profile management, longer builds | Stable, CPU-significant services |
| Micro-benchmarks | Fast, precise, repeatable | Can mislead about system behaviour | Hot functions, library code |
| Load tests | Realistic latency under concurrency | Setup cost, environment drift | Capacity planning, release gates |
In practice
Investigating "checkout p99 doubled after release 2.14":
- Traces show the extra time is inside
payments-api, not PostgreSQL. CPU per request is up ≈30%. - Pull CPU profiles from a 2.13 canary and a 2.14 pod;
go tool pprof -diff_base v213.pprof v214.pprofhighlightsencoding/json.(*encodeState).reflectValueunder a new audit-logging middleware. - The heap
alloc_spacediff shows the middleware marshals the full request body for every request. - Fix: log a bounded set of fields via
slog.LogAttrs; redact by type. Benchmark the middleware (benchstat: −85% allocs/op), canary, confirm p99 and CPU per request return to baseline. - Add a performance regression check: a benchmark for the middleware in CI with an alert on significant regressions.
For contention: if p99 is high but CPU is low, take a mutex profile and a 5-second trace; a common finding is a single sync.Mutex around a map used by every request (fix: shard or atomic.Pointer copy-on-write).
Common pitfalls
- Optimising without a goal — weeks spent on a function that is 0.5% of CPU.
- Profiling the wrong thing — a CPU profile of an idle service, or a load test that doesn't resemble production traffic.
- Reading
flatonly — missing that an innocent-looking function's callees take 40% (cum). - Confusing
inuseandalloc— chasing allocation hot spots to fix a leak, or vice versa. - pprof on the public port via
_ "net/http/pprof"andhttp.DefaultServeMux— information disclosure and a DoS vector. - Forgetting block/mutex profiles are off — empty profiles, wrong conclusion that there's no contention.
- Single-run benchmarks or closed-loop load tests — noise and hidden tail latency reported as results.
- Benchmark bodies optimised away with the old
b.Nstyle — useb.Loop. - Stale or unrepresentative PGO profiles — optimises yesterday's hot path; refresh periodically.
- CPU throttling mistaken for slow code — check container CPU limits and
GOMAXPROCSbefore rewriting anything.
Interview angle
Prompts: "How would you find why a Go service is slow?", "Your service uses 100% CPU — walk me through it", "p99 latency is high but CPU is low — what now?", "How do you find a memory leak in Go?", "What is PGO?", "How do you know an optimisation worked?"
A strong answer starts from the goal and the distributed trace, then picks the right tool: CPU profile for running time, trace and block/mutex profiles for waiting, heap inuse diffs for leaks, alloc for GC pressure; reads flat vs cum; knows block/mutex must be enabled; protects the pprof endpoint; uses PGO with a representative merged profile; validates with benchstat and constant-rate load tests, then a canary.
Follow-ups: "What's coordinated omission?", "How does PGO devirtualize?", "What's the overhead of profiling in production?" (CPU profiling and short traces are low single-digit percent; continuous profilers are designed for always-on use).
Red flags: "I'd add more pods" as the only answer, optimising by intuition, average latency as the metric, never having read a flame graph.
Self-check
1. What's the difference between flat and cum, and which do you sort by to find a slow subtree?
Flat is time spent in the function's own code; cum includes everything it calls. Sort by cum (top -cum) to find expensive subtrees like a handler whose callees dominate; sort by flat to find leaf hot spots like hashing or JSON encoding.
2. p99 latency tripled but CPU utilisation is 25%. Which tools do you use and what might you find?
An execution trace plus block and mutex profiles, since time is spent waiting rather than running. Likely findings: goroutines blocked acquiring DB connections (pool too small or slow queries holding connections), a contended mutex, GC assists during allocation bursts, or CPU throttling from a low container CPU limit (runnable-but-not-running goroutines in the trace).
3. Memory grows steadily for hours. Which heap view do you use, and how do you confirm the culprit?
inuse_space (and inuse_objects), taken twice some time apart, compared with go tool pprof -diff_base old new. The growing stacks show who allocated the retained memory. Also check the goroutine count — leaked goroutines retain their stacks and references.
4. Why must the pprof handlers not be on the public listener, and what's the safe setup?
They expose internal details (stack traces, command lines, source structure) and allow anyone to trigger expensive CPU profiles or traces — information disclosure and DoS. Register them on an explicit mux on an internal admin port reachable only via port-forward or the internal network.
5. Describe the PGO workflow and two optimisations it enables.
Collect CPU profiles from production under representative traffic, merge them with go tool pprof -proto, commit as default.pgo in the main package, and build normally (-pgo=auto). The compiler inlines hot call sites more aggressively and devirtualizes hot interface calls by adding a direct-call fast path for the dominant concrete type.
6. Scenario: a PR claims a 20% latency improvement from a load test with 50 concurrent users. What do you check?
Whether the tool used a constant arrival rate (closed-loop tools hide tail latency via coordinated omission), whether percentiles rather than averages were compared, repeated runs and environment parity, error rates during the test, and whether CPU per request changed. Then insist on a canary comparison in production.
Exercise
- Take a service with a JSON endpoint (or the one from Building Production Services) and load it with vegeta at a constant 500 req/s for 2 minutes; record p50/p99 and CPU.
- Capture a 30 s CPU profile and a heap
alloc_spaceprofile during the load. Identify the top three cum-sorted functions in your code and the top allocation sites. - Fix one CPU and one allocation hot spot. Benchmark before/after with
-count=10andbenchstat; re-run the load test. - Add a deliberate
sync.Mutexaround a shared map used by every request; enable the mutex profile and show it in the profile and the trace; then fix it with sharding. - Build with PGO from a merged profile of your load test; compare CPU per request with and without PGO over three runs each.
- Add a flight recorder that dumps a trace when a request exceeds 1 s; trigger it with an artificial delay and analyse the dump.
Done when: you have before/after numbers for each change, a short write-up of what you tried and kept, and can explain each finding from the profile or trace.
Further reading
- Go documentation: "Diagnostics" (go.dev/doc/diagnostics) and "Profile-guided optimization" (go.dev/doc/pgo).
- Go blog: "Profiling Go Programs" (Russ Cox; updated by others).
- Go blog: "More powerful Go execution traces" (Michael Knyszek) and the flight recorder post for Go 1.25.
runtime/pprof,net/http/pprofandruntime/tracepackage documentation.- Brendan Gregg, Systems Performance and his flame graph articles.
- Gil Tene, "How NOT to Measure Latency" (talk) — coordinated omission.
- Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — optimisations chapter.
- Grafana Pyroscope documentation — continuous profiling for Go.
Related
- Memory, GC & Escape Analysis — what allocation profiles are telling you.
- Testing & Benchmarking —
b.Loop,-benchmemandbenchstat. - Goroutines & Channels — goroutine profiles and the scheduler behind traces.
- Linux Performance Analysis — USE method, perf, and throttling at the OS level.
- Observability & SLOs — the metrics and traces that tell you where to profile.
- Capacity Planning & Cost — turning CPU per request into fleet size and cost.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).