Nov 23, 20265 min read

Profile a Go Service with pprof

How to find out why a Go service is slow or uses too much memory: expose pprof safely, capture CPU, heap, goroutine, block and mutex profiles, read flame graphs, compare before and after, and profile from benchmarks and tests.

Illustration for Profile a Go Service with pprof

A slow Go service usually points at one of a few causes: a hot loop, too many allocations, goroutines that never finish, or code waiting on a lock. Guessing between them wastes days, while a 30-second profile shows where the time goes.

Go ships the tool for this, pprof, and it is safe enough to use against production traffic when it is exposed carefully.

Which profile answers which question?

SymptomProfileEndpoint
High CPUCPU/debug/pprof/profile?seconds=30
Memory growsHeap (in use)/debug/pprof/heap
GC pressure, many allocationsAllocs/debug/pprof/allocs
Goroutine count climbsGoroutine/debug/pprof/goroutine?debug=2
Requests wait, CPU is lowBlock and mutex/debug/pprof/block, /debug/pprof/mutex

The Go diagnostics guide describes these profiles and the other tools, such as tracing and the runtime's execution tracer, and the net/http/pprof reference lists every handler.

How do you expose pprof safely?

Importing the package registers its handlers on http.DefaultServeMux. Serve that mux on a loopback or internal-only port, separate from the public server:

package main import ( "log" "net/http" _ "net/http/pprof" // registers /debug/pprof/ on the default mux "runtime" ) func init() { // Off by default. Enable block and mutex profiles only while investigating. runtime.SetBlockProfileRate(1_000_000) // sample blocking events of 1 ms or more runtime.SetMutexProfileFraction(100) // sample 1 in 100 mutex contention events go func() { // Internal only. Reach it through a port-forward, ECS Exec or an SSH tunnel. log.Println(http.ListenAndServe("127.0.0.1:6060", nil)) }() }

Never put these handlers on a public listener or behind the same load balancer as the API. Collecting a CPU profile costs some performance for its duration, which is why you take it for 30 seconds and not continuously.

How do you read a CPU profile?

Capture it while the service handles realistic traffic, then open the web UI:

~
$ go tool pprof -http=127.0.0.1:8081 "http://localhost:6060/debug/pprof/profile?seconds=30"Serving web UI on http://localhost:8081

The flame graph shows the call stack with wider boxes for more time. The top view lists functions by flat time, the time inside the function itself, and by cumulative time, which includes its callees. High flat time is where the CPU burns, and high cumulative with low flat is a caller to follow. The list FuncName command shows source lines with their cost. Typical finds are JSON encoding of large structs, regular expressions compiled in a loop, string concatenation and fmt.Sprintf in hot paths.

How do you find memory problems?

The heap profile shows live memory by default, so take one profile, wait, take another, and compare them with -base to show only the growth:

~
$ curl -s localhost:6060/debug/pprof/heap > heap1.out$ sleep 600$ curl -s localhost:6060/debug/pprof/heap > heap2.out$ go tool pprof -http=127.0.0.1:8081 -base heap1.out heap2.out

Switch the view to alloc_space to find what allocates the most over time, which matters for garbage collection cost even when nothing leaks. A rising goroutine count in /debug/pprof/goroutine?debug=2 usually means goroutines stuck on a channel or a missing context cancellation, and the dump shows the exact line each one waits on.

What about profile-guided optimization?

Once you have a representative CPU profile, Go can use it at build time. Save it as default.pgo in the main package directory and go build applies profile-guided optimization automatically, which the Go team measured at about 2 to 14 percent improvement on representative programs as of Go 1.22. Treat it as a final step after fixing the hot spots you can see.

How do you profile an Encore service?

Encore

Encore is a backend framework with built-in infrastructure, and it helps with the first half of the problem: finding which request and which query is slow. The local development dashboard shows a trace for every request and every test, with the database queries and API calls inside it, so you can see that an endpoint spends 400 ms in one query before touching a profiler. For the second half, encore test is a wrapper around go test that supports the same flags, so a benchmark of the hot function produces a normal pprof profile.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

// reports/summary.go package reports import ( "fmt" "strings" ) type Order struct { Customer string Cents int64 } // Summarize builds a CSV line per order. The string concatenation in the loop // is the kind of hot spot a CPU profile points straight at. func Summarize(orders []Order) string { var sb strings.Builder for _, o := range orders { fmt.Fprintf(&sb, "%s,%d.%02d\n", o.Customer, o.Cents/100, o.Cents%100) } return sb.String() }
// reports/summary_test.go package reports import "testing" func BenchmarkSummarize(b *testing.B) { orders := make([]Order, 10_000) for i := range orders { orders[i] = Order{Customer: "customer", Cents: int64(i)} } b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { Summarize(orders) } }
~
$ encore test -run='^$' -bench=Summarize -cpuprofile=cpu.out ./reports$ go tool pprof -http=127.0.0.1:8081 cpu.out

-cpuprofile works on one package at a time, so name the package. The profile covers only the benchmark, which makes it a quick loop: change the function, rerun and compare allocations per operation. On deploy, Encore runs the service in your own AWS or GCP account as the AWS infrastructure docs describe, and the tracing docs cover the traces collected there. The metrics docs cover the counters and gauges you can add to watch a fix in production. A coding agent asked to speed up an endpoint can run the same benchmark and read the allocation count before and after, instead of guessing.

Best fit: Teams running Go services who want request-level traces to locate the problem and standard pprof to fix it.

Frequently asked questions

How do you enable pprof in a Go web service?

Import net/http/pprof for its side effects and serve the default mux on a separate internal port, for example localhost:6060. The handlers appear under /debug/pprof/. Never register them on your public listener, because profiles expose internals and a CPU profile is expensive to collect.

How do you capture a CPU profile with pprof?

Run go tool pprof -http=127.0.0.1:8081 http://localhost:6060/debug/pprof/profile?seconds=30 while the service is under realistic load. After 30 seconds it opens a web UI with the flame graph, top functions and source view.

What is the difference between flat and cumulative in pprof?

Flat is the time spent in the function itself, and cumulative includes everything the function called. A function with high cumulative and low flat time is a caller to follow down, while high flat time is where the CPU time is spent.

How do you profile a Go service built with Encore?

With Encore, use the local development dashboard traces to find which endpoint or query is slow, then run encore test with the usual go test flags such as -bench and -cpuprofile on the package to get a pprof profile of the hot function.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders