CPU and heap profiling
You can capture CPU and heap profiles during a load test to locate expensive code and goroutines that remain blocked under pressure.
Learning outcomes
- Explain how Go's pprof endpoints expose CPU, heap, goroutine and synchronization profiles.
- Capture a 20-second CPU profile while the API handles a k6 workload and interpret its top functions and flame graph.
- Distinguish CPU consumption, memory allocation, retained heap, goroutine leaks and mutex contention.
- Correlate profiling results with request latency, MySQL activity and connection-pool metrics to identify the first bottleneck.
Your restaurant API can return successful responses while p99 latency rises under 300 concurrent browsing users. The next exercise, "Find and fix the first bottleneck", uses a 20-second CPU profile during a k6 run to identify where the backend spends its time. You need evidence before changing the implementation.
Go profiling
Go includes a built-in profiler called pprof. It exposes runtime information through runtime/pprof and net/http/pprof.
The HTTP package provides several profiling endpoints:
| Endpoint | Information |
|---|---|
/debug/pprof/ | Available profiling endpoints |
/debug/pprof/profile | CPU profile |
/debug/pprof/heap | Heap allocation information |
/debug/pprof/goroutine | Goroutine stacks |
/debug/pprof/mutex | Mutex contention |
/debug/pprof/block | Blocking information |
You can expose these endpoints through a separate HTTP listener. Keep this listener separate from the public chi router.
A simplified setup looks like this:
import (
"log"
"net/http"
_ "net/http/pprof"
)
func startProfiler() {
go func() {
err := http.ListenAndServe("127.0.0.1:6060", nil)
if err != nil {
log.Printf("pprof server: %v", err)
}
}()
}The blank import registers the profiling handlers on http.DefaultServeMux. Passing nil to ListenAndServe uses that default mux.
The API continues serving public requests through its chi router on port 8080. The profiler listens separately on 127.0.0.1:6060.
This separation matters because profiling endpoints expose internal execution information. They can also consume CPU and memory while collecting profiles.
In the course backend, the profiler listener is configured separately from the public API. The default address is 127.0.0.1:6060.
CPU profiles
A CPU profile records sampled CPU execution over a fixed period. It helps identify which functions consume the process's CPU time.
This is useful when a request becomes slower under load and you suspect expensive application code.
For example, you might investigate:
- JSON encoding in restaurant responses.
- Repeated menu assembly.
- Allocation and garbage collection work.
- Contention in the in-memory rate limiter.
A CPU profile is useful only when the application is performing representative work. Profiling an idle API tells you very little about the cost of processing restaurant and order requests.
Start your k6 workload first. While requests are flowing, capture a 20-second profile:
go tool pprof -http=:0 \
"http://127.0.0.1:6060/debug/pprof/profile?seconds=20"Go collects CPU samples for 20 seconds. The -http=:0 flag starts a local profiling interface on an available port.
You can inspect the same profile in the terminal:
go tool pprof -top \
"http://127.0.0.1:6060/debug/pprof/profile?seconds=20"The -top command lists functions ranked by their sampled CPU consumption.
CPU profile measurements
The output contains several columns:
| Column | Meaning |
|---|---|
flat | CPU time spent directly inside a function |
flat% | Percentage of sampled CPU time spent directly inside it |
cum | CPU time inside the function and its callees |
cum% | Cumulative CPU percentage |
sum% | Running total of flat percentages in the displayed order |
Consider a function with these profile measurements:
flat: 20 ms
cum: 80 msThe function itself consumed 20 milliseconds of sampled CPU time. Its complete call path, including the functions it called, consumed 80 milliseconds.
This distinction helps you find expensive child operations. A function can have a small flat value but a large cumulative value because its callees perform most of the work.
Expensive application functions
Functions near the top of a profile deserve investigation, but their names alone do not prove that they are the bottleneck.
For example, encoding/json may appear prominently when the API repeatedly constructs and serializes large responses.
runtime.mallocgc may appear when the application creates many short-lived objects. Those allocations increase the work performed by the garbage collector.
If sync.(*Mutex).Lock appears frequently, investigate whether request handlers are competing for a shared lock.
You should follow the call path back to your application code before changing anything.
CPU time versus waiting time
A CPU profile does not measure all the time a request spends waiting.
A handler might spend most of its time waiting for MySQL or Redis. That waiting time can increase HTTP latency without producing a large amount of application CPU activity.
The same applies to network reads and writes. Functions such as syscall.rawsyscalln and runtime.kevent can indicate time associated with network operations.
One reference run of the course backend collected 2.44 seconds of CPU samples over a 20-second profile. That represents approximately 12% of one CPU core.
Its profile contained:
- 66% of CPU samples in
syscall.rawsyscalln, primarily network reads and writes. - 10% in
runtime.kevent. - Less than 3% in JSON encoding.
These results do not indicate a CPU-bound browse handler. Optimising JSON encoding based on this profile would be unlikely to address the dominant cost.
Your measurements may differ. The useful lesson is to identify what the profile actually measures instead of assuming that high request latency means high CPU usage.
Flame graphs and call graphs
The browser interface provides several ways to explore a CPU profile.
A flame graph represents sampled CPU consumption across nested function calls. Wider blocks represent more sampled time.
Look for wide blocks associated with application functions. Follow their call paths to identify the request handler or dependency responsible for the work.
The graph view shows relationships between functions and their CPU costs. It helps you move from an expensive runtime operation to the application code that triggered it.
Use flat and cum together when interpreting these views. A function with substantial cumulative time but little flat time may be calling an expensive operation rather than performing the work itself.
Do not assume that the widest block is automatically the correct place to optimise. Check how frequently that code runs and whether the measured workload actually depends on it.
Heap profiles
A Heap profile shows where memory is allocated and how much memory remains reachable.
A CPU profile helps identify expensive computation. A heap profile helps identify allocation pressure and retained memory.
You can capture the heap profile while the backend handles representative traffic:
go tool pprof -http=:0 \
"http://127.0.0.1:6060/debug/pprof/heap"For a terminal summary:
go tool pprof -top \
"http://127.0.0.1:6060/debug/pprof/heap"Two measurements are particularly useful.
alloc_space
alloc_space measures the total memory allocated by a call site over the profiling history.
Consider a restaurant handler that repeatedly creates temporary response objects. It may allocate a large amount of memory even though most objects become unreachable shortly after the request finishes.
High allocation volume can increase garbage collection work.
inuse_space
inuse_space measures memory currently retained by live objects.
A function with high inuse_space may be creating objects that remain reachable for a long time.
For example, an application might retain old restaurant responses in an in-memory map without removing entries that are no longer needed.
The distinction is important:
| Measurement | What it reveals |
|---|---|
alloc_space | Total allocation volume |
inuse_space | Memory currently retained |
Suppose a profile reports 900 MB of alloc_space and 40 MB of inuse_space for a call site.
That function allocated substantial memory, but relatively little remains live. You should investigate unnecessary temporary allocations rather than assume that all 900 MB remains in memory.
You can select the measurement when inspecting a profile:
go tool pprof -sample_index=alloc_space \
"http://127.0.0.1:6060/debug/pprof/heap"
go tool pprof -sample_index=inuse_space \
"http://127.0.0.1:6060/debug/pprof/heap"A heap profile contains sampled allocation information. It is not a complete record of every allocation. Use it to find suspicious call sites, inspect their code and repeat the measurement after a change.
Goroutine lifecycle
A Goroutines is a lightweight execution unit managed by the Go runtime. Your HTTP handlers, background workers and asynchronous operations can all start goroutines.
Every goroutine should have a defined Goroutine lifecycle. It should have a reason to start and a condition under which it exits.
Consider a request handler that starts a goroutine waiting for a result:
go func() {
result := <-resultChannel
processResult(result)
}()If nobody sends a value to resultChannel, that goroutine remains blocked.
The problem becomes more serious when this happens for every incoming request. Goroutines accumulate and continue consuming memory and scheduler resources.
Goroutine leaks
A Goroutine leak occurs when goroutines remain alive after their intended work should have finished.
Common causes include:
- Goroutines waiting indefinitely on channels.
- Background operations without cancellation.
- Network operations without deadlines.
- Workers that cannot exit during shutdown.
- Send operations blocked because nobody receives from a channel.
The Go context package provides a standard mechanism for cancellation. Use context.Context to propagate cancellation and deadlines into work started by a request.
For example:
go func(ctx context.Context) {
select {
case result := <-resultChannel:
processResult(result)
case <-ctx.Done():
return
}
}(ctx)When the request context is cancelled, the goroutine can stop waiting and exit.
This is particularly relevant to the backend's per-call timeouts. A request that times out should not leave background work running indefinitely.
Goroutine profile inspection
You can retrieve a goroutine snapshot through the private profiling endpoint:
curl -s \
"http://127.0.0.1:6060/debug/pprof/goroutine?debug=1" \
| head -n 5The first line reports the current goroutine count:
goroutine profile: total NThe remaining output contains stack information grouped by execution location.
For more detailed stack information, use debug=2:
curl -s \
"http://127.0.0.1:6060/debug/pprof/goroutine?debug=2"The count alone does not establish a leak. Your API also has legitimate background work, active requests and runtime goroutines.
Compare snapshots under equivalent conditions:
- Record the goroutine count before the load test.
- Start representative traffic.
- Stop the workload.
- Allow active requests and background work to finish.
- Record the count again.
- Repeat the test and compare the snapshots.
A healthy service should return close to its previous baseline once temporary work has finished.
Suppose a backend starts with 60 goroutines. After a ten-minute soak, it has 420 even though traffic has stopped and requests have completed.
That increase deserves investigation. Inspect the additional goroutine stacks and look for repeated channel receives, blocked network operations and background loops that do not terminate.
Mutex and block profiles
A mutex protects shared data from concurrent modification. It also introduces the possibility that several request handlers wait for the same lock.
For example, the in-memory rate limiter may need to protect shared state while processing requests. If many handlers contend for that state, mutex waiting can contribute to latency.
The mutex profile identifies where goroutines spend time waiting to acquire contended locks.
You can enable mutex sampling explicitly:
runtime.SetMutexProfileFraction(5)This configures sampling for mutex contention events. Profiling introduces overhead, so enable it deliberately.
The block profile records time spent blocked on synchronization operations such as channel and mutex operations. It can help investigate waits that do not appear as significant CPU consumption.
Use these profiles when CPU and heap measurements do not explain the observed latency.
Data races and profiling
A Data race occurs when goroutines access the same memory concurrently and at least one access is a write, without appropriate synchronization.
Mutex profiling and race detection answer different questions.
A mutex profile shows contention. It tells you where goroutines spend time waiting for locks.
The Go race detector identifies unsynchronized concurrent memory access. You can run it with:
go test -race ./...A program can have a data race without showing significant mutex contention. It can also experience mutex contention without having a data race.
Do not use CPU profiles as a substitute for race detection.
Profiling alongside database metrics
A CPU profile cannot tell you whether the database connection pool is saturated.
Your backend already exposes request metrics. Combine those measurements with pprof to understand where requests spend their time.
The Connection pool controls how many MySQL connections the API can use concurrently.
The next exercise, "Find and fix the first bottleneck", exports pool measurements including:
| Metric | Meaning |
|---|---|
db_connections_max_open | Maximum permitted open connections |
db_connections_open | Current open connections |
db_connections_in_use | Connections currently in use |
db_connection_waits_total | Total connection waits |
db_connection_wait_seconds_total | Total time spent waiting for connections |
A high maximum-open value does not prove that the pool is saturated.
Look at connections in use and the wait counters together. If connections are mostly idle and wait counters remain unchanged, pool exhaustion is not supported by the evidence.
MySQL's SHOW PROCESSLIST provides another perspective. It shows the current connection and query activity.
You can also use EXPLAIN to investigate the query plan for a slow database operation. These tools answer different questions:
- pprof identifies CPU work, allocations and goroutine behaviour.
SHOW PROCESSLISTreveals current database activity.EXPLAINreveals how MySQL plans a query.- Pool metrics reveal connection availability and waiting.
A request can have high latency without being CPU-bound or waiting for a database connection. Consider Redis operations, network activity and mutex contention before deciding which resource is responsible.
Profiling during representative traffic
A useful profiling session requires the same workload conditions as the measurements you want to investigate.
Start the API and its dependencies. Confirm that the public API is responding before starting k6.
Run the browse workload with the same configuration used for the before numbers. While k6 sends requests, capture the CPU profile.
After collecting the profile, inspect its top functions and flame graph. Use heap and goroutine profiles when memory allocation or persistent goroutine growth needs investigation.
Correlate the findings with request latency, errors and dependency measurements.
Change one suspected bottleneck per run. Then repeat the same workload and compare its before numbers with the after numbers.
This comparison matters because percentages alone can mislead you. If a function's CPU percentage falls, the process may still be consuming more absolute CPU time because the workload or total throughput changed.
Compare the workload, achieved throughput and measured latency alongside the profiles.
Common profiling mistakes
Several mistakes can lead to an incorrect bottleneck diagnosis.
Profiling an idle process
An idle API does not represent the real request workload. Capture profiles while k6 is generating representative traffic.
Using a short or unrepresentative sample
A brief sample during a traffic spike may capture an unusual execution path. Use the 20-second collection period specified for the bottleneck investigation.
Optimising the wrong function
A function consuming a small percentage of sampled CPU time is unlikely to explain a major latency problem by itself. Follow expensive call paths and correlate them with request measurements.
Confusing waiting with CPU consumption
A slow MySQL query can increase p99 without appearing as significant application CPU time. Check query plans, process-list activity and connection-pool waits.
Ignoring goroutine cancellation
A goroutine waiting indefinitely on a channel or network operation can survive after its originating request finishes. Propagate contexts and ensure background work has an exit condition.
Exposing profiling endpoints publicly
A public pprof endpoint can reveal internal execution details and consume server resources. Keep the listener private.
Profiling evidence for the bottleneck investigation
The exercise "Find and fix the first bottleneck" uses the same 300 VU browse workload established by "Browse and order k6 scripts". You capture a 20-second CPU profile from 127.0.0.1:6060 while k6 is running.
The profile helps you determine whether application CPU work explains the latency. You then compare its findings with MySQL query plans, SHOW PROCESSLIST and the database pool metrics.
The exercise also requires you to make one targeted change and preserve the after measurements. Its results belong in the load-test documentation alongside the before and after p50, p95, p99 and error rate.
Do not assume that MySQL is the first bottleneck merely because the API uses MySQL. A rate limiter mutex, menu assembly allocations or network waits may deserve investigation instead.
The goal is to explain which resource limits the measured workload and whether your change actually improved it.
Check your understanding
Your API has high p99 latency during a browse workload. A 20-second CPU profile contains only 2.44 seconds of CPU samples. What should you investigate next?
References
Everything above is explained on this page; these are where it comes from (Go, net/http/pprof).