Recipe

Go pprof primer

A focused walkthrough for instrumenting a Go service with the standardnet/http/pprofpackage, pulling CPU and heap profiles in production, and reading the resulting flame graphs without guessing.

1.Wire the endpoint

Import the side-effect package so it registers handlers on the default mux. If your service uses its own mux, mount the routes explicitly under an internal-only port so the profiles never leak to the public internet.

import _ "net/http/pprof"

go func() {
  // bind to loopback only
  log.Println(http.ListenAndServe("127.0.0.1:6060", nil))
}()

2.Pull a profile

Use the go tool pprof CLI against the running service. A 30-second CPU sample is the default starting point; switch to the heap endpoint when chasing allocator pressure.

# 30s CPU profile
go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30

# live heap snapshot
go tool pprof http://127.0.0.1:6060/debug/pprof/heap

# goroutine fan-out at this instant
curl http://127.0.0.1:6060/debug/pprof/goroutine?debug=2

3.Read the output

Open the interactive web UI with -http. The flame graph view is the fastest path to the hot frame; the top view ranks self-time and is best for shipping a concise finding to the rest of the team.

go tool pprof -http=:8081 cpu.pb.gz

# inside the REPL
(pprof) top10
(pprof) list MyHotFunction
(pprof) web