How to Collect Go pprof Profiles: Every Endpoint and Flag

net/http/pprof endpoints and parameters, runtime/pprof, go test flags, enabling block and mutex profiles, safe exposure and Kubernetes, from the Go docs.

By · · 11 min read

Illustration for How to Collect Go pprof Profiles: Every Endpoint and Flag

A Go service is burning CPU, holding memory or piling up goroutines, and you need a profile before the incident ends. For a long-running server, import _ "net/http/pprof", serve it on a private port, and fetch what you need:

  • CPU: go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
  • memory: go tool pprof http://localhost:6060/debug/pprof/heap
  • every goroutine's stack: curl 'http://localhost:6060/debug/pprof/goroutine?debug=2'

For a program you can edit or a benchmark, use runtime/pprof or go test -cpuprofile. This guide is written from the official documentation and the Go source as of go1.27.4. Go was not run to produce it, so the figures are documented defaults, with the source file named for each. The pprof Profile Analyzer reads the resulting .pb.gz files in your browser without uploading them.

Every way to get a profile

MethodCode changeBest for
net/http/pprof endpoints + go tool pprof <url>one import and a listenerservers in production
runtime/pprof (StartCPUProfile, Lookup(...).WriteTo)a few linesCLIs, batch jobs, profiling one code path
go test -cpuprofile and friendsnonebenchmarks and tests
runtime.SetBlockProfileRate, SetMutexProfileFractionone call eachturning on the two profiles that are off by default

net/http/pprof: import, and expose it privately

The package doc says it is "typically only imported for the side effect of registering its HTTP handlers", and that "the handled paths all begin with /debug/pprof/". Its init function calls http.HandleFunc, so the handlers land on http.DefaultServeMux. That is exactly the risk. Any server in the binary that serves DefaultServeMux, which means any ListenAndServe(addr, nil), now publishes them on that address.

Register the handlers on a mux of your own, on a port that only localhost can reach:

import (
	"log"
	"net/http"
	"net/http/pprof"
)

func startPprof() {
	mux := http.NewServeMux()
	mux.HandleFunc("/debug/pprof/", pprof.Index) // also serves /debug/pprof/heap, /goroutine, ...
	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)
	go func() { log.Println(http.ListenAndServe("127.0.0.1:6060", mux)) }()
}

pprof.Index hands any path below /debug/pprof/ to the named profile (the source calls handler(name).ServeHTTP), so those five lines cover every endpoint. The doc's instruction for this case is "If you are not using DefaultServeMux, you will have to register handlers with the mux you are using". If you import the package by name as above, the side-effect handlers on DefaultServeMux still register. That only matters if something serves DefaultServeMux.

Why "never public":

  • /debug/pprof/cmdline returns the process's command line, and flags carry secrets more often than they should.
  • goroutine?debug=2 prints every goroutine's stack with function arguments as raw words. Heap profiles name your types and call sites.
  • profile?seconds=N turns on CPU profiling for N seconds, and anyone who can reach it can keep it on.

Since Go 1.22 every path must be requested with GET, according to the package doc.

Every endpoint and its parameters

EndpointWhat it holdsCollected howOn by default
profileCPU samplesover seconds (default 30), at 100 Hzyes
heapsampled allocations of live objectsas of the last completed GCyes
allocsthe same samples, viewed as everything allocated since startsince startyes
goroutineevery goroutine's stacknowyes
blockwhere goroutines waited on sync primitives and channelssince enabledno
mutexholders of contended mutexessince enabledno
threadcreatestacks that created OS threadssince startyes
traceexecution trace for go tool traceover seconds (default 1)yes
cmdline, symbolcommand line; program counter to name lookupnowyes
goroutineleakgoroutines blocked forevera GC with leak detection, then nowGo 1.27; behind GOEXPERIMENT=goroutineleakprofile in 1.26
Go pprof profile types by when they are collected and whether they work without setup: CPU and trace over a window; heap, allocs, goroutine, threadcreate and goroutine leak at a point or since start; block and mutex off until runtime.SetBlockProfileRate or SetMutexProfileFraction is called
Go pprof profile types by when they are collected and whether they work without setup: CPU and trace over a window; heap, allocs, goroutine, threadcreate and goroutine leak at a point or since start; block and mutex off until runtime.SetBlockProfileRate or SetMutexProfileFraction is called

The defaults come from src/net/http/pprof/pprof.go: sec = 30 in Profile and sec = 1 in Trace. The 100 Hz rate is const hz = 100 in runtime/pprof's StartCPUProfile, whose comment explains that operating systems "cannot trigger signals at more than about 500 Hz". The query parameters, in the doc's words:

  • debug=N (all profiles): "N = 0: binary (default), N > 0: plaintext". For goroutine, debug=1 groups identical stacks with counts, and debug=2 prints every goroutine "in the same format as an unrecovered panic". That is the Go equivalent of a Java thread dump, and it is the first thing to fetch when a service hangs.
  • gc=N (heap): "N > 0: run a garbage collection cycle before profiling". The heap profile otherwise "reports statistics as of the most recently completed garbage collection", so gc=1 makes it current, at the cost of a GC.
  • seconds=N on allocs, block, goroutine, heap, mutex and threadcreate returns a delta: what changed during those N seconds. That suits a leak that grows under load. The handler rejects seconds combined with debug ("seconds and debug params are incompatible"), and rejects it on profiles outside that list.

Two version traps live in the same file. Through Go 1.22, a profile longer than the server's WriteTimeout was refused with profile duration exceeds server's WriteTimeout. From Go 1.23 the handler extends the write deadline by the requested seconds instead, via configureWriteDeadline. And goroutineleak exists only from Go 1.26: the 1.26 release notes call it an experiment enabled by GOEXPERIMENT=goroutineleakprofile, and the 1.27 notes make it generally available.

go tool pprof: fetching from a URL

go tool pprof -seconds 30 http://localhost:6060/debug/pprof/profile
go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof -http=:8080 http://localhost:6060/debug/pprof/heap
curl -o cpu.pb.gz 'http://localhost:6060/debug/pprof/profile?seconds=30'
  • -seconds sets the seconds query parameter for you. In pprof's fetch.go, the HTTP timeout becomes the duration plus half again, so a 30-second profile allows 45 seconds.
  • Where fetched profiles go: the same file saves a copy, and prints Saved profile in .... The directory is PPROF_TMPDIR if set, otherwise $HOME/pprof, otherwise the system temp directory. Clean that directory after incidents, because it collects production profiles.
  • -http=host:port opens the web UI with the flame graph, source and graph views. Bind it to localhost too.
  • curl -o keeps the raw gzipped protobuf. Use it when the person reading the profile is not the person with network access, or when you want the pprof Profile Analyzer to read it locally.

runtime/pprof: profiling from inside the program

f, _ := os.Create("cpu.pb.gz")
pprof.StartCPUProfile(f)          // error if a CPU profile is already running
defer pprof.StopCPUProfile()      // returns after all writes complete

h, _ := os.Create("heap.pb.gz")
runtime.GC()                      // optional: make the heap profile current
pprof.Lookup("heap").WriteTo(h, 0)

pprof.Lookup("goroutine").WriteTo(os.Stderr, 2) // panic-style stacks

WriteTo(w, debug) takes the same debug levels as the HTTP parameter. The doc says debug=0 writes "the gzip-compressed protocol buffer", debug=1 "the legacy text format with comments translating addresses to function names and line numbers", and for goroutine, debug=2 prints each stack. WriteHeapProfile(w) is "shorthand for Lookup("heap").WriteTo(w, 0)", kept for backwards compatibility. The runtime/pprof package comment shows Lookup("allocs") for a profile "similar to go test -memprofile". Use heap when live memory is the question.

StartCPUProfile has one documented catch. In a binary built with -buildmode=c-archive or c-shared, it does not work by default on Unix-like systems, because SIGPROF goes to the host program's handler.

go test: profiles from benchmarks

go test -run='^
#x27; -bench=. -cpuprofile cpu.out -memprofile mem.out ./internal/pricing go test -run='^
#x27; -bench=. -blockprofile block.out -mutexprofile mutex.out ./internal/pricing go test -trace trace.out ./internal/pricing
FlagDocumented behaviour
-cpuprofile cpu.outCPU profile written before exiting
-memprofile mem.outallocation profile "after all tests have passed"
-memprofilerate nsets runtime.MemProfileRate; 1 records every allocation
-blockprofile block.outblocking profile when tests complete
-blockprofilerate nwithout it, "all blocking events are recorded, equivalent to -test.blockprofilerate=1"
-mutexprofile mutex.outmutex contention profile
-mutexprofilefraction n"Sample 1 in n"; the flag's default in testing.go is 1
-trace trace.outexecution trace
-outputdir dirwhere the files go; default is the directory go test runs in

The profiling flags write the test binary as go test -c would. The cmd/go docs say they "leave the test binary in pkg.test for use when analyzing the profiles". -run='^

#x27; skips the unit tests so the profile shows only the benchmark.

Turning on block and mutex profiles

The diagnostics page is explicit that the block profile "is not enabled by default; use runtime.SetBlockProfileRate to enable it", and the same for mutex with SetMutexProfileFraction. An endpoint that was never enabled returns a profile with no samples, which is easy to misread as "no contention".

runtime.SetBlockProfileRate(1)      // aim for one sample per 1 ns blocked: every event
runtime.SetMutexProfileFraction(5)  // report on average 1 in 5 contention events
  • SetBlockProfileRate(rate): "The profiler aims to sample an average of one blocking event per rate nanoseconds spent blocked". 1 includes every event, and rate <= 0 turns it off.
  • SetMutexProfileFraction(rate): "On average 1/rate events are reported". It returns the previous rate. 0 turns it off, and a negative value only reads the current rate.

The docs put no number on the overhead of either. Every-event settings suit a benchmark. In production, pick a sampled rate and measure the service before and after.

Kubernetes and containers

kubectl port-forward -n shop pod/pricing-7d9f 6060:6060
go tool pprof -seconds 30 http://localhost:6060/debug/pprof/profile

The kubectl reference shows the LOCAL:REMOTE form and notes that forwarding ends when the pod terminates. Keep the pprof port out of the Service and any Ingress. If your pprof listener binds only to 127.0.0.1 inside the pod, test once that port-forward reaches it on your cluster before you rely on it during an incident. The fallback that always works is kubectl exec with curl -o inside the pod, then kubectl cp, which needs tar in the image. For a distroless image with neither, fetch from a debug container in the same pod.

What each profile costs

The Go diagnostics page answers the production question directly: "It is safe to profile programs in production, but enabling some profiles (e.g. the CPU profile) adds cost". It also says collecting profiles "can interfere with each other, so it is recommended to collect only a single profile at a time". The documented constants turn into sizing figures:

  • CPU: at 100 Hz, each sample stands for 10 ms. A 30-second profile of a process keeping 4 cores busy carries about 12,000 samples. A profile with only a few dozen samples says the process was mostly idle, not that nothing is slow.
  • Heap: runtime.MemProfileRate defaults to 512 * 1024. The profiler "aims to sample an average of one allocation per MemProfileRate bytes allocated", so 1 GiB of allocation yields about 2,048 samples. Setting it to 1 records every allocation, which is what makes -memprofilerate=1 expensive.
  • Execution trace: the Go blog's 2024 trace post says tracing cost 10 to 20% CPU for many applications before Go 1.21, and 1 to 2% since. That is still the reason the endpoint's default is 1 second.

Which method for which situation

SituationUse
Server pegging CPU nowgo tool pprof -seconds 30 http://.../debug/pprof/profile
Memory climbingheap?gc=1, then again later, or heap?seconds=60 for the delta
Service hung or slow, CPU idlegoroutine?debug=2 first, then block
Lock contention suspectedSetMutexProfileFraction in code, then mutex
Goroutine count only risesgoroutine?debug=1 twice, then goroutineleak on Go 1.27
A benchmark regressedgo test -bench -cpuprofile -memprofile
CLI or batch jobruntime/pprof around the work
Latency spikes, GC or schedulertrace?seconds=5 and go tool trace

For Node services the equivalent capture is how to take a Node.js heap snapshot. When the slowness is between services rather than inside one, how to capture network packets and how to capture a HAR file cover the wire and the browser.

Tools for this job

  • pprof Profile Analyzer: drop a .pb.gz from any endpoint above. It shows sample types, duration and the top functions by flat and cum, gunzipped and parsed in the browser.
  • Java Thread Dump Analyzer: for the JVM services next to your Go ones, the same "who is blocked on what" question as goroutine?debug=2.

The binary files reading guide explains flat versus cum and what the analyzer's top table means once you have the file.

Frequently asked questions

Is it safe to run pprof in production?

The Go diagnostics page says profiling production programs is safe but some profiles, the CPU profile among them, add cost. Collect one profile at a time. The bigger risk is exposure: serve the handlers on a private port and never on the public mux.

Why is my block or mutex profile empty?

Both are off by default. Call runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction with a positive rate, then wait for contention to happen. The profiles only record events after the call, so enable them before the slow period, not during the fetch.

What is the difference between heap and allocs?

The same sampled data with a different default view. The runtime/pprof docs say heap shows live objects, inuse_space, as of the last completed GC. allocs defaults to alloc_space, everything allocated since the program started, including memory already collected. Use heap for leaks and allocs for churn.

How do I get a goroutine dump like a Java thread dump?

Fetch /debug/pprof/goroutine?debug=2. It prints every goroutine's full stack in the format of an unrecovered panic. With debug=1 the stacks are grouped with counts, which is shorter when thousands of goroutines share one stack.

Sources and further reading

  • net/http/pprof, The Go Authors. Side-effect registration, endpoints, the debug, gc and seconds parameters (go1.27.4).
  • pprof.go (net/http/pprof), The Go Authors on GitHub. Default seconds for profile and trace, delta profiles, the WriteTimeout handling.
  • runtime/pprof, The Go Authors. Predefined profiles, StartCPUProfile, WriteTo debug levels, heap versus allocs.
  • runtime, The Go Authors. SetBlockProfileRate, SetMutexProfileFraction and MemProfileRate.
  • Testing flags (cmd/go), The Go Authors. The profiling flags of go test and the pkg.test binary.
  • Diagnostics, The Go Authors. Production profiling, block and mutex off by default, one profile at a time.
  • Go 1.27 release notes, The Go Authors. The goroutineleak profile made generally available after the 1.26 experiment.
  • pprof README, Google pprof project on GitHub. Fetching from URLs, -seconds and -http.

Browse all tools