Skip to Content
Skip to content
Go Advanced: Performance, Concurrency, and Production
Advanced
Courses
Go Advanced: Performance, Concurrency, and Production

Find CPU and Heap Hotspots With pprof

Capture a CPU or heap profile with runtime/pprof and inspect top functions using go tool pprof -top. After this, you can locate real bottlenecks before rewriting code.

Course content

Sign in to save your progress.

Course Home

When a production Go service spikes to 80% CPU or burns 40% of its time in garbage collection, guessing which function is to blame almost always wastes hours. One small line—compiling a regex per request, or concatenating strings inside a loop—can account for 90% of all heap allocations while the rest of the service barely registers.

Go builds pprof directly into go test and net/http/pprof so you can capture real CPU and memory profiles, read flat vs. cum totals in your terminal, and verify with numbers that your fix eliminated the hotspot.

Skip ahead

If you already capture -cpuprofile and -memprofile, distinguish flat vs. cum and alloc_space vs. inuse_space, and isolate net/http/pprof on localhost, continue to "Catch Goroutine Leaks and Slow Tests Early."

Experiment 1: Capturing a memory profile of a real regex bottleneck

Here is a realistic metrics helper that normalizes paths like /users/42/orders/991 into /users/:id/orders/:id, accidentally compiling the regex on every single call:

package norm

import (
	"regexp"
	"testing"
)

func normalizeSlow(path string) string {
	re := regexp.MustCompile(`/[0-9]+`)
	return re.ReplaceAllString(path, "/:id")
}

func BenchmarkNormalizeSlow(b *testing.B) {
	for b.Loop() {
		_ = normalizeSlow("/users/42/orders/991")
	}
}

Record a memory profile and print the top 5 allocating functions with go tool pprof -top:

$ go test -run=^$ -bench=BenchmarkNormalizeSlow -memprofile=mem.out -benchtime=200ms .
$ go tool pprof -top -nodecount=5 mem.out
File: adv5.test
Type: alloc_space
Showing nodes accounting for 331.05MB, 90.31% of 366.57MB total
      flat  flat%   sum%        cum   cum%
  142.03MB 38.75% 38.75%   142.03MB 38.75%  regexp/syntax.(*compiler).inst (inline)
  103.01MB 28.10% 66.85%   103.01MB 28.10%  regexp/syntax.(*parser).newRegexp (inline)
   42.01MB 11.46% 78.31%   342.55MB 93.45%  regexp.compile
      30MB  8.19% 86.49%   141.51MB 38.61%  regexp/syntax.parse
      14MB  3.82% 90.31%    18.52MB  5.05%  regexp.(*Regexp).replaceAll

Experiment 2: Reading flat vs. cum—and verifying the fix

Look carefully at line 3 of the profile:

  • flat (42.01 MB / 11.46%): Bytes allocated directly inside regexp.compile itself.
  • cum (342.55 MB / 93.45%): Cumulative bytes allocated by regexp.compile plus every helper it called (parse, newRegexp, inst).

If you only sorted by flat%, you would look at internal regexp/syntax functions instead of spotting that regexp.compile—triggered by regexp.MustCompile inside normalizeSlow—caused 93.45% of all heap churn! Hoisting var idRe = regexp.MustCompile(`/[0-9]+`) once at package init drops allocations from 1,565 B/op (`22 allocs/op`) down to 96 B/op (`5 allocs/op`) and makes the function 4× faster:

$ go test -run=^$ -bench=. -benchmem -benchtime=200ms .
BenchmarkNormalizeSlow-2   	  281642	       785.9 ns/op	    1565 B/op	      22 allocs/op
BenchmarkNormalizeFast-2   	 1210044	       197.6 ns/op	      96 B/op	       5 allocs/op

Experiment 3: Line-by-line inspection and alloc_space vs. inuse_space

Two terminal flags turn go tool pprof into a surgical debugging tool:

# See exact allocations annotated next to each line of your function:
$ go tool pprof -list=normalizeSlow mem.out

# Check memory STILL LIVE on the heap (for hunting memory leaks):
$ go tool pprof -top -inuse_space mem.out

# Open an interactive flame graph in your browser:
$ go tool pprof -http=:8081 mem.out

Know the difference between alloc_space and inuse_space: high alloc_space means rapid temporary garbage (high GC CPU, flat RSS); high inuse_space means objects never got freed (climbing RSS / memory leak).

Experiment 4: Live profiling with net/http/pprof safely

For staging or production servers, never import _ "net/http/pprof" on your public router—that registers /debug/pprof/ on http.DefaultServeMux. Bind a dedicated internal admin listener on loopback only:

go func() {
	// Accessible only via localhost / SSH tunnel / kubectl port-forward
	_ = http.ListenAndServe("127.0.0.1:6060", nil)
}()

Then capture a live 30-second CPU profile remotely without restarting the server: go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30.

Common mistakes

  • Exposing /debug/pprof/ on your public port 8080: Leaks internal symbol names, stack traces, and lets anyone trigger expensive CPU profiles on demand.
  • Profiling a 10 ms run: CPU profiling samples at 100 Hz (every 10 ms)—a 20 ms benchmark collects only ~2 samples and produces misleading noise. Pass -benchtime=2s for CPU profiles.
  • Ignoring cum%: Wrapper functions that call JSON encoders or database drivers often show 0% in flat and 85% in cum; always inspect pprof -top -cum too.

💡 Tip

You can compare two profiles directly with go tool pprof -base=old.out new.out—positive numbers show regressions and negative numbers show exactly how many megabytes or milliseconds your optimization removed.

What happens if you skip this step

Without pprof, teams guess wrong about bottlenecks—rewriting clean code that uses 2% of CPU while a single unhoisted regex or JSON encoder burns 90% of heap allocations.

A service's RSS memory grows steadily by 50 MB every hour until it OOMs, while CPU stays low. Should you inspect -alloc_space or -inuse_space in go tool pprof to find the leak, and why?

About

Capture a CPU or heap profile with runtime/pprof and inspect top functions using go tool pprof -top. After this, you can locate real bottlenecks before rewriting code.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.