Profiling with pprof

Profiling with pprof in Go: A supermarket manager wants to know which part of the shop is the bottleneck.

The Analogy: The Clipboard Round

A supermarket manager wants to know which part of the shop is the bottleneck. One option is to tag every trolley and log every movement: perfectly accurate, ruinously expensive, and the logging itself would slow the shop down enough to change the answer. So instead the manager walks the floor every ten seconds with a clipboard and writes down where each shopper is standing right now. Then again ten seconds later. The round costs almost nothing and nobody notices it happening.

After an hour there are three hundred and sixty snapshots. No individual shopper's journey survives in them, and somebody who spent four seconds at the wine shelf may never have been seen there at all. But if two fifths of every snapshot has people bunched at the deli counter, the deli counter is where the time goes, and no amount of sampling error will hide that. This is the whole idea behind a sampling profiler. Go's CPU profiler takes the clipboard round a hundred times a second, on every operating system thread, and each entry is the stack of whatever was running at that instant.

The clipboard has a second column, and it is the one that makes the survey useful: not just where the shopper is standing, but which aisle they came down to get there. That is the call stack. "Two fifths of the time is spent in the memory allocator" is a fact you can do nothing with. "Two fifths of the time is in the allocator, reached from parseRow, reached from handleUpload" names a function you can go and edit. Every good session with a profiler is a walk from a leaf you cannot change to a caller you can.

And a survey answers only the question it was built for. The clipboard round records where people stand; it cannot distinguish a shopper reading a label from one stuck behind a jammed till, because both look identical in a snapshot -- and it cannot see the shopper who gave up and went to sit in the car park at all. A CPU profile has exactly this blindness: it samples threads that are running, so time spent waiting on a lock, a channel, a disk or a network round trip is invisible in it. Go ships separate profiles for those, and reaching for the CPU profile to explain a latency problem is the most common wrong turn there is.


Syntax or Core Structure

There are three ways to get a profile out of a Go program, and this is the most explicit one: ask for it in code.

// main.go
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
	"strings"
)

var cpuProfile = flag.String("cpuprofile", "", "write a CPU profile to this file")

// normalize is deliberately wasteful: it rebuilds the row string per field.
func normalize(rows []string) []string {
	out := make([]string, 0, len(rows))
	for _, r := range rows {
		s := ""
		for _, f := range strings.Split(r, ",") {
			s += strings.ToUpper(strings.TrimSpace(f)) + "|"
		}
		out = append(out, s)
	}
	return out
}

func main() {
	flag.Parse()
	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		if err := pprof.StartCPUProfile(f); err != nil {
			log.Fatal(err)
		}
		// Nothing below may call os.Exit or log.Fatal. A deferred Stop that
		// never runs leaves a truncated file that pprof cannot read.
		defer pprof.StopCPUProfile()
	}

	rows := make([]string, 200000)
	for i := range rows {
		rows[i] = " a" + strconv.Itoa(i) + " , b , c "
	}
	out := normalize(rows)
	fmt.Println("rows:", len(out), "last:", out[len(out)-1])
}

Build it, run it, and open the profile:

go build -o normalize .
./normalize -cpuprofile=cpu.out
go tool pprof -top -nodecount=10 cpu.out

Output:

The program prints one line, and then pprof prints the survey. As with any measurement, the absolute times are this machine's; the ordering and the ratios are the content. The header lines naming the file and the capture time are omitted here.

rows: 200000 last: A199999|B|C|
Showing nodes accounting for 1.42s, 93.42% of 1.52s total
Dropped 47 nodes (cum <= 0.01s)
      flat  flat%   sum%        cum   cum%
     0.46s 30.26% 30.26%      0.46s 30.26%  runtime.memmove
     0.22s 14.47% 44.73%      0.31s 20.39%  runtime.mallocgc
     0.18s 11.84% 56.57%      1.32s 86.84%  main.normalize
     0.14s  9.21% 65.78%      0.71s 46.71%  runtime.concatstrings
     0.11s  7.24% 73.02%      0.31s 20.39%  strings.Split
     0.09s  5.92% 78.94%      0.16s 10.53%  strings.ToUpper
     0.07s  4.61% 83.55%      0.09s  5.92%  strings.TrimSpace
     0.06s  3.95% 87.50%      0.06s  3.95%  runtime.scanobject
     0.05s  3.29% 90.79%      0.05s  3.29%  runtime.nextFreeFast
     0.04s  2.63% 93.42%      0.11s  7.24%  runtime.gcDrain

Two columns, and everything depends on telling them apart. flat is time spent in that function's own instructions, with everything it called excluded. cum is flat plus everything underneath it in the stack. runtime.memmove has the largest flat time and is the least useful line in the table, because you cannot edit memmove; main.normalize has a modest flat time and a cum of 86.84%, and it is the only function on the list you own. Sort by flat to find where the cycles are burning, sort by cum to find the function whose deletion would remove them.


Technical Depth: Several Profiles and Two Columns

Pick the profile that matches the complaint

ProfileAnswersNotes
cpuWhich code is burning cyclesSampled at 100 Hz per thread. Blind to all waiting.
heap (inuse_space, inuse_objects)What is alive right nowA snapshot. This is the leak profile.
allocs (alloc_space, alloc_objects)What has been allocated since startChurn and GC pressure, including objects long since freed.
goroutineHow many goroutines exist and where they are parked?debug=2 gives full stacks. First stop for a goroutine leak.
blockWhere goroutines wait on channels and sync primitivesOff by default; needs runtime.SetBlockProfileRate.
mutexWhich locks are contended, and for how longOff by default; needs runtime.SetMutexProfileFraction.
threadcreateWhere OS threads are being createdRarely useful, and historically unreliable.
execution traceScheduling, GC pauses, syscall latency, per-goroutine timelinesNot a pprof profile. go tool trace, and see below.

Three ways to collect one

RouteHowBest for
Benchmark flagsgo test -run=^$ -bench=X -cpuprofile=cpu.out -memprofile=mem.outA known hot function, in a repeatable harness.
HTTP endpointimport _ "net/http/pprof", then go tool pprof http://host/debug/pprof/profile?seconds=30A running server, under real load.
Explicit callspprof.StartCPUProfile / StopCPUProfile, pprof.Lookup("heap").WriteToBatch jobs and CLI tools, as above.

The blank import registers handlers on http.DefaultServeMux as a side effect. /debug/pprof/ lists them; profile takes a CPU sample for seconds (30 by default), heap, allocs, goroutine, block, mutex and threadcreate return their profiles immediately, trace returns an execution trace, and cmdline returns the process's argument vector.

Reading a profile

go tool pprof cpu.out opens an interactive prompt; go tool pprof -http=:8080 cpu.out opens a browser with the same data and is what you should reach for first.

CommandWhat it gives you
top, top20Ranked by flat. Where the cycles are.
top -cumRanked by cum. Which subtree owns them.
list <regexp>Annotated source, line by line, with flat and cum per line.
peek <regexp>The callers and callees of one function, with the split between them.
treeThe call graph as text.
web, svgThe call graph as a picture, thicker edges for more time.
granularity=linesAttribute samples to lines rather than functions.
-diff_base=old.outShow new minus old, so you profile the change rather than the program.
Flame Graph viewIn -http mode. Width is time, depth is stack. The fastest way to see shape.

Every number here is a sample, and the rate matters

The CPU profiler fires 100 times a second per thread, so a 1 second profile of a single threaded program contains about 100 samples and a function taking 5% of the time contributes five of them. Five samples cannot tell 5% from 9%. Profile for thirty seconds, not one, and be suspicious of any line with a single-digit sample count. runtime.SetCPUProfileRate can raise the rate, but it must be called before profiling starts and higher rates begin to perturb what they measure.

The heap profiler samples too: by default it records roughly one allocation per 512 KB and scales the result up, which is set by runtime.MemProfileRate. That estimate is good for totals and poor for rare large objects, so -memprofilerate=1 (or setting MemProfileRate = 1 at the top of main) is the switch to flip when you are chasing one specific allocation. Setting it to 0 disables heap profiling entirely.

Inlined calls do appear in profiles -- Go records inline frames, and pprof expands them -- so a function you cannot find is more likely absent because it never ran than because it was inlined away.

inuse versus alloc: two completely different questions

inuse_space is a census of what is on the heap at the moment the profile is taken. If it grows every time you sample and nothing is freed, you have a leak, and the stacks name whoever allocated the surviving objects. alloc_space is the total ever allocated, including everything already collected. A program with a healthy flat inuse_space and an enormous alloc_space does not leak; it churns, and churn shows up as CPU time in mallocgc, scanobject and gcDrain rather than as growing memory. Diagnosing churn from the inuse profile finds nothing, and diagnosing a leak from the alloc profile finds everything, which is the same as finding nothing. Switch views in -http mode from the SAMPLE menu, or pass -sample_index=alloc_space.

Off-CPU time, and the profiles that see it

A request that takes 400 ms of which 390 ms is a database round trip produces a CPU profile in which nothing is interesting, because for 390 ms the goroutine was not on a CPU at all. The instruments for that are different:

func main() {
	runtime.SetBlockProfileRate(1000000)  // sample blocking events over 1 ms
	runtime.SetMutexProfileFraction(100)  // sample 1 in 100 contention events
	// ...
}

Both are off by default because both cost something, and both being off is why so many people conclude their program has no contention. Once enabled, the block profile ranks channel and sync waits by duration, and the mutex profile ranks lock handoffs by how long the next holder waited. Above those sits go tool trace, which is not a sampling profiler at all: it records every scheduling event, GC phase and syscall boundary, so it can answer "why did this one request take 900 ms" in a way no profile can. It produces far more data and is the right tool only once you have a specific latency question.

The debug endpoints are not for the public internet

import _ "net/http/pprof" installs its handlers on http.DefaultServeMux with no authentication of any kind. If your public listener uses that mux -- and http.ListenAndServe(addr, nil) does -- then anybody who can reach your service can read your full function and file names, pull a heap profile that may contain fragments of live data, read your command line arguments and environment from /debug/pprof/cmdline, and start a thirty second CPU profile on demand, repeatedly, which is a cheap way to degrade the process. Treat it as an administrative interface:

func main() {
	admin := http.NewServeMux()
	admin.HandleFunc("/debug/pprof/", pprof.Index)          // net/http/pprof
	admin.HandleFunc("/debug/pprof/profile", pprof.Profile) // registered by hand
	go func() {
		// Loopback only. Reach it with an SSH tunnel or a sidecar.
		log.Println(http.ListenAndServe("127.0.0.1:6060", admin))
	}()

	public := http.NewServeMux()
	public.Handle("/", myAPI())
	log.Fatal(http.ListenAndServe(":8080", public))
}

Bind the admin listener to 127.0.0.1, or put it on a port your firewall does not publish, or wrap it in the same authentication middleware as the rest of your admin surface. Never pass nil as the handler on a listener that faces users.

Labels, and profiling the change instead of the program

pprof.Do attaches key/value labels to every sample taken by the goroutine inside it, and the labels survive into child goroutines:

pprof.Do(ctx, pprof.Labels("endpoint", "/upload", "tenant", tenantID), func(ctx context.Context) {
	handleUpload(ctx, r)
})

In -http mode you can then filter or group the whole profile by endpoint, which turns "the service spends 30% of its CPU in JSON decoding" into "one endpoint, for one customer, spends 30% of the service's CPU in JSON decoding". Labels apply to the CPU, block and mutex profiles; the heap profile does not carry them.

Finally, -diff_base is the pprof equivalent of benchstat. Capture a profile before your change and one after, then run go tool pprof -diff_base=before.out after.out, and the report shows negative numbers where you removed time and positive ones where you added it. It is the fastest way to notice that your optimisation moved the cost somewhere else rather than removing it.


Real World Example: From a Hot Line to a Confirmed Win

top named main.normalize as the subtree that owns 86.84% of the time. That is a function, not a fix. list narrows it to a line:

go tool pprof -list='main.normalize$' cpu.out

The $ anchors the pattern, so it matches normalize and not the normalizeFast we are about to write. The file path in the header is whatever the compiler recorded on the machine that built the binary.

Output:

Total: 1.52s
ROUTINE ======================== main.normalize in /home/dev/normalize/main.go
     180ms      1.32s (flat, cum) 86.84% of Total
         .          .     17:func normalize(rows []string) []string {
         .       30ms     18:	out := make([]string, 0, len(rows))
      20ms       20ms     19:	for _, r := range rows {
         .          .     20:		s := ""
      30ms      310ms     21:		for _, f := range strings.Split(r, ",") {
     130ms      960ms     22:			s += strings.ToUpper(strings.TrimSpace(f)) + "|"
         .          .     23:		}
         .          .     24:		out = append(out, s)
         .          .     25:	}
         .          .     26:	return out
         .          .     27:}

Line 22 holds 960 ms of the 1.52 s total, and line 21 holds another 310 ms. That is the entire investigation: one += inside a loop, and one Split that allocates a slice per row to produce three substrings nobody keeps. Everything in the top table -- memmove, concatstrings, mallocgc, and the garbage collector's own gcDrain and scanobject -- is downstream of those two lines.

The fix follows from the profile rather than from taste. Replace the growing string with one buffer, and replace Split with strings.Cut, which returns two substrings of the original and allocates nothing.

// normalizeFast reuses one Builder and never materialises a slice of fields.
func normalizeFast(rows []string) []string {
	out := make([]string, 0, len(rows))
	var b strings.Builder
	for _, r := range rows {
		// Reset drops the buffer rather than truncating it, so the string
		// returned for the previous row is unaffected by what follows.
		b.Reset()
		b.Grow(len(r) + 4) // a hint, not a promise: ToUpper can lengthen
		rest := r
		for {
			field, more, found := strings.Cut(rest, ",")
			b.WriteString(strings.ToUpper(strings.TrimSpace(field)))
			b.WriteByte('|')
			if !found {
				break
			}
			rest = more
		}
		out = append(out, b.String())
	}
	return out
}

Now prove it, with a test that the two agree and a benchmark that says by how much.

// main_test.go
package main

import (
	"strconv"
	"testing"
)

func rows(n int) []string {
	in := make([]string, n)
	for i := range in {
		in[i] = " a" + strconv.Itoa(i) + " , b , c "
	}
	return in
}

// The awkward rows at the end are the ones that break rewrites of this shape:
// empty, no separator, only a separator, and a trailing empty field.
func TestFastMatchesSlow(t *testing.T) {
	in := append(rows(2000), "", "one", ",", " x , ")
	got, want := normalizeFast(in), normalize(in)
	if len(got) != len(want) {
		t.Fatalf("length: got %d, want %d", len(got), len(want))
	}
	for i := range want {
		if got[i] != want[i] {
			t.Fatalf("row %d (%q): got %q, want %q", i, in[i], got[i], want[i])
		}
	}
}

func BenchmarkNormalize(b *testing.B) {
	in := rows(2000)
	b.ReportAllocs()
	for b.Loop() {
		normalize(in)
	}
}

func BenchmarkNormalizeFast(b *testing.B) {
	in := rows(2000)
	b.ReportAllocs()
	for b.Loop() {
		normalizeFast(in)
	}
}

Output:

goos: linux
goarch: amd64
pkg: example.com/normalize
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkNormalize-8         1478    794512 ns/op    288045 B/op    18001 allocs/op
BenchmarkNormalizeFast-8     3336    357104 ns/op    128041 B/op     8001 allocs/op
PASS
ok      example.com/normalize   2.431s

The workflow is the point, not the numbers. top picked the subtree, list picked the line, and the edit was aimed at that line rather than at the function or at the program. Ten thousand allocations per call disappeared, and the time fell by 55%. To confirm it is not noise, run each side with -count=10 and hand the two files to benchstat; to confirm the cost moved out of the program rather than sideways within it, capture a second CPU profile and run go tool pprof -diff_base=before.out after.out, where memmove, concatstrings and mallocgc should all appear with negative times.

Notice which parts of the original top table were never under main.normalize at all. runtime.gcDrain and runtime.scanobject accounted for 7.24% and 3.95% of cum, and they sit in their own subtree because the garbage collector runs on its own goroutines. That is the cost of the eighteen thousand allocations showing up somewhere the caller cannot see, and it is the reason allocs/op is worth optimising even when the allocation itself looks cheap: you pay once to allocate and again, elsewhere, to collect.

The obvious next step is to profile again rather than to guess. normalizeFast still makes four allocations per row -- one for the buffer and three inside strings.ToUpper, which allocates whenever the input contains a lower case letter. Uppercasing ASCII into the builder by hand would remove three of the four, and a fresh profile would say whether that is now the top line or whether something else has taken over. Every optimisation changes the shape of the profile, so the profile you are working from is stale the moment your fix lands.

One caution to carry out of this lesson. Everything above was a CPU profile, and it worked because the complaint was "this batch job takes too long" -- a throughput problem, where the program really was on a CPU the whole time. Had the complaint been "our p99 latency is 900 ms", this profile might have been almost empty, and the answer would have been in the block or mutex profile, or in go tool trace. Match the instrument to the symptom before you spend an afternoon reading the wrong graph.


Common Mistakes

  1. Exiting before StopCPUProfile runs. os.Exit, log.Fatal and an unrecovered panic all skip deferred functions, so the profile file is left truncated and pprof reports a parse error on an empty or malformed profile. Once profiling has started, every exit path has to go through the Stop.
  1. Chasing the biggest flat number. runtime.memmove, runtime.mallocgc and syscall.Syscall are frequently at the top and are never the thing to edit. Follow them upward with top -cum or peek until you reach a function in your own package.
  1. Reading cum as if it were flat. main.main has a cum of nearly 100% in every profile ever taken. A high cum means "the time is somewhere below here", which is a direction to walk, not a place to fix.
  1. Exposing /debug/pprof on a public listener. The blank import registers on DefaultServeMux, and http.ListenAndServe(":8080", nil) publishes it to anyone who can reach the port -- along with a repeatable thirty second CPU profile they can trigger at will. Bind it to loopback or authenticate it.
  1. Concluding there is no contention from an empty block or mutex profile. Both are disabled by default. Without runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction those endpoints return almost nothing, no matter how badly your locks are fighting.
  1. Profiling for one second. A hundred samples cannot separate a 4% function from an 8% one. Use ?seconds=30 on a server, or a longer -benchtime in a harness, and distrust any line backed by a handful of samples.
  1. Confusing the heap profiles. inuse_space answers "what is alive", alloc_space answers "what has ever been allocated". Looking for a leak in alloc_space shows you every allocation the program has ever made, including all the ones that were correctly freed.
  1. Using a CPU profile to explain latency. Time spent waiting on a lock, a channel, a disk or a network call is not on a CPU and does not appear. If the profile looks flat while the service feels slow, you are holding the wrong instrument.
  1. Profiling an unrepresentative workload. An idle server, a synthetic input, a cold cache, or a run with the race detector enabled all produce a profile of something other than production. -race in particular multiplies memory-access costs and will point you at completely different lines.
  1. Optimising something with a 3% cum. Making it infinitely fast buys 3%. Sort by cum, work top down, and stop when the remaining entries are not worth the change -- which is usually much sooner than it feels.
  1. Losing the source or the binary. list needs the source file at the path recorded at build time, and disasm needs the binary. A profile captured from a go run binary in a temporary directory, or from a container image you have since rebuilt, will still give you top but not annotated source. Archive the profile with the commit hash and, for release builds, the binary.

Best Practices

  • Let the symptom choose the profile. Slow throughput points at cpu; growing memory at heap with inuse_space; GC churn at allocs; a stuck or ballooning process at goroutine; unexplained latency at block, mutex and go tool trace. Picking the instrument first saves more time than reading any graph faster.
  • Walk top down: top -cum, then peek, then list. Find the subtree that owns the time, find the call edge that carries it, then find the line. Stop at a line you can actually change.
  • Open profiles with -http=:8080. The flame graph shows the shape of a program in seconds, the Source view is list with the arithmetic done for you, and the SAMPLE menu switches between inuse and alloc without a second command.
  • Profile in production, or as close to it as you can get. Real inputs, real concurrency, real data volumes. net/http/pprof behind an admin listener costs essentially nothing when nobody is scraping it, and having it already there is what turns a 3 a.m. incident into a five minute investigation.
  • Keep the debug surface administrative. Its own mux, bound to loopback or reachable only through your existing authenticated admin path. Assume a heap profile can contain fragments of user data, because it can.
  • Label the samples you will want to slice. pprof.Do with an endpoint, a tenant or a job type costs almost nothing and turns a whole-service profile into a per-caller one, which is usually where the surprise is hiding.
  • Archive profiles as artefacts. Name them with the commit and the scenario, keep the before for every change you make, and use -diff_base rather than eyeballing two top outputs side by side.
  • Re-profile after every fix, and pair the profile with a benchmark. The profile says what to change and the benchmark says whether the change helped; neither substitutes for the other, and the profile you started with stops being true the moment the first fix lands.

Practice Exercises

  1. Flat Against Cum: Build and profile the normalize program, then print the top ten by flat and the top ten by cum. Write down which entries appear in only one of the two lists, and for each of those explain in one sentence why. Then use peek runtime.memmove to find which of your own functions is responsible for it.
  1. Fix the Line, Prove the Fix: Use list to identify the most expensive line, apply the strings.Builder and strings.Cut rewrite, and confirm the improvement two ways: -count=10 on both benchmarks through benchstat, and go tool pprof -diff_base=before.out after.out. Report what -diff_base says about runtime.mallocgc.
  1. An Admin Listener That Is Not Public: Take any HTTP service and add pprof on a second ServeMux bound to 127.0.0.1:6060, leaving the public mux without it. Capture a 30 second CPU profile while a load generator runs, then write two sentences describing exactly what an attacker could do with the DefaultServeMux version on a public port.
  1. See the Waiting: Write a program where several goroutines contend for one sync.Mutex around a short critical section. Profile its CPU and note how little it explains. Then set SetBlockProfileRate and SetMutexProfileFraction, capture both profiles, and identify the lock. Finally record an execution trace and describe what go tool trace shows that neither profile did.