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 Redbison Dev · · 11 min read

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
| Method | Code change | Best for |
|---|---|---|
net/http/pprof endpoints + go tool pprof <url> | one import and a listener | servers in production |
runtime/pprof (StartCPUProfile, Lookup(...).WriteTo) | a few lines | CLIs, batch jobs, profiling one code path |
go test -cpuprofile and friends | none | benchmarks and tests |
runtime.SetBlockProfileRate, SetMutexProfileFraction | one call each | turning 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/cmdlinereturns the process's command line, and flags carry secrets more often than they should.goroutine?debug=2prints every goroutine's stack with function arguments as raw words. Heap profiles name your types and call sites.profile?seconds=Nturns 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
| Endpoint | What it holds | Collected how | On by default |
|---|---|---|---|
profile | CPU samples | over seconds (default 30), at 100 Hz | yes |
heap | sampled allocations of live objects | as of the last completed GC | yes |
allocs | the same samples, viewed as everything allocated since start | since start | yes |
goroutine | every goroutine's stack | now | yes |
block | where goroutines waited on sync primitives and channels | since enabled | no |
mutex | holders of contended mutexes | since enabled | no |
threadcreate | stacks that created OS threads | since start | yes |
trace | execution trace for go tool trace | over seconds (default 1) | yes |
cmdline, symbol | command line; program counter to name lookup | now | yes |
goroutineleak | goroutines blocked forever | a GC with leak detection, then now | Go 1.27; behind GOEXPERIMENT=goroutineleakprofile in 1.26 |
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". Forgoroutine,debug=1groups identical stacks with counts, anddebug=2prints 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", sogc=1makes it current, at the cost of a GC.seconds=Nonallocs,block,goroutine,heap,mutexandthreadcreatereturns a delta: what changed during those N seconds. That suits a leak that grows under load. The handler rejectssecondscombined withdebug("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'
-secondssets thesecondsquery parameter for you. In pprof'sfetch.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 isPPROF_TMPDIRif set, otherwise$HOME/pprof, otherwise the system temp directory. Clean that directory after incidents, because it collects production profiles. -http=host:portopens the web UI with the flame graph, source and graph views. Bind it to localhost too.curl -okeeps 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
| Flag | Documented behaviour |
|---|---|
-cpuprofile cpu.out | CPU profile written before exiting |
-memprofile mem.out | allocation profile "after all tests have passed" |
-memprofilerate n | sets runtime.MemProfileRate; 1 records every allocation |
-blockprofile block.out | blocking profile when tests complete |
-blockprofilerate n | without it, "all blocking events are recorded, equivalent to -test.blockprofilerate=1" |
-mutexprofile mutex.out | mutex contention profile |
-mutexprofilefraction n | "Sample 1 in n"; the flag's default in testing.go is 1 |
-trace trace.out | execution trace |
-outputdir dir | where 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".1includes every event, andrate <= 0turns it off.SetMutexProfileFraction(rate): "On average 1/rate events are reported". It returns the previous rate.0turns 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.MemProfileRatedefaults to512 * 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=1expensive. - 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
| Situation | Use |
|---|---|
| Server pegging CPU now | go tool pprof -seconds 30 http://.../debug/pprof/profile |
| Memory climbing | heap?gc=1, then again later, or heap?seconds=60 for the delta |
| Service hung or slow, CPU idle | goroutine?debug=2 first, then block |
| Lock contention suspected | SetMutexProfileFraction in code, then mutex |
| Goroutine count only rises | goroutine?debug=1 twice, then goroutineleak on Go 1.27 |
| A benchmark regressed | go test -bench -cpuprofile -memprofile |
| CLI or batch job | runtime/pprof around the work |
| Latency spikes, GC or scheduler | trace?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.gzfrom 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.