Columns › 5. Going live and operating › Part 27
CPU and Memory Problems in Production Go Services: How to Track Them Down
線上 Go 服務的 CPU 與記憶體問題:怎麼追、用什麼工具定位
When a production service burns CPU, keeps growing in memory or gets OOMKilled, which metrics do you check first and which profile do you take? This article walks through an incident triage flow: runtime/metrics and container signals, exposing pprof safely in Kubernetes, diffing two heap snapshots to find leaks, goroutine leaks, lock contention, GC pressure, execution traces and the flight recorder, and when continuous profiling is worth it.
In this article
- What this article solves
- Step 1: The triage flow: mitigate first, then gather evidence
- Step 2: Signals to collect all the time
- Step 3: Exposing pprof safely in production
- Step 4: CPU spikes: profiles, flame graphs and before-and-after comparison
- Step 5: Memory keeps growing: subtracting two heap snapshots
- Step 6: OOMKilled in Kubernetes
- Step 7: Goroutine leaks
- Step 8: Lock contention and blocking
- Step 9: GC pressure
- Step 10: Latency spikes without high CPU: execution traces and the flight recorder
- Step 11: Continuous profiling: when it is worth it
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “Performance Tuning in Go: pprof and Benchmarks”, covered benchmarks, the basics of pprof, escape analysis and settings such as GOGC and GOMEMLIMIT; that is performance work you do when you have time to measure carefully. This article deals with a different situation: the service is already in production, an alert has fired, the CPU is saturated or memory keeps growing, and you have limited time to find the code responsible. The tools are mostly the same, but how and in what order you use them is not.
What this article solves
A few weeks after the order system went live, two things happened:
- One evening, Kubernetes restarted the
orderservice's Pods roughly every 40 minutes, andkubectl describe podshowed the last termination reason asOOMKilled. Every restart cut off in-flight requests, and bursts of 5xx errors appeared at theapi-gateway. - During a sales promotion,
order's p99 latency rose from 80ms to 2 seconds, yet the CPU usage on the dashboard was only 60% of the limit and looked as if there was "room to spare".
Both times the first reaction was "add resources": raise the memory limit from 512Mi to 1Gi, double the replicas. The first problem merely went from a restart every 40 minutes to one every 80; doubling the replicas did little for the second. The real causes had to be found with evidence: which function was holding on to the memory, and whether the latency was spent computing or waiting.
This article follows the order in which you handle an incident, and for each step explains which tool to use, why, and when not to use it:
- The incident triage flow, and a "symptom → first tool → what to look for" table.
- Signals to collect all the time:
runtime/metrics, the Prometheus Go collector, container CPU throttling and memory, and the difference between RSS and the Go heap. - Exposing pprof safely in production: a separate internal port, not on the public router,
kubectl port-forward, and the cost of profiling. - CPU spikes: a 30-second CPU profile, flame graphs, comparing before and after a fix with
-diff_base, plus cgroup throttling andGOMAXPROCS. - Memory that keeps growing:
inuse_spaceversusalloc_space, two snapshots taken minutes apart and subtracted with-base, and the common causes of leaks. - OOMKilled in Kubernetes: how to confirm it, why
GOMEMLIMITmust sit below the limit, and the problem of evidence disappearing when the Pod restarts. - Goroutine leaks: grouping by stack, blocked channel sends, missing cancellation.
- Lock contention and blocking: the mutex and block profiles.
- GC pressure: reading
gctrace, reducing allocations, and care withsync.Pool. - Latency spikes without high CPU: execution traces and the flight recorder.
- Continuous profiling: when it is worth deploying.
The example is a module, example.com/shop, that compiles and has tests. It contains a deliberately broken quote handler and shows how to "diff out" the leak with code and a script. The code was compiled and tested with Go 1.27; behaviour that depends on the version is called out explicitly.
Step 1: The triage flow: mitigate first, then gather evidence
The most common mistake in an incident is fighting the fire and hunting for the cause at the same time, and doing both badly; or opening pprof straight away and getting lost among hundreds of functions. A more effective order is:
Figure: mitigate first, use metrics to decide which resource is the problem, take the matching profile to find the function and line, then fix it and verify with metrics and a before-and-after profile comparison.
- Mitigate first: roll back to the previous version, scale out, raise the limit temporarily, switch off a feature flag. The goal is to restore service for users, not to solve the problem. But before mitigating, if you can, take one piece of evidence (a heap or goroutine profile takes seconds), because after a rollback or restart the scene is gone.
- Use metrics to identify the resource: is it CPU, memory, the number of goroutines, or high latency while every resource looks normal? Each answer points to a different profile. This usually takes a few dashboards.
- Take a profile to locate it: only the kind that matches the symptom, and ideally while the problem is happening.
- Fix and verify: once the fix is live, the same metrics must return to normal and the same profile must show the hot spot gone; the incident is closed only when you see both.
The table below is the index to the whole article; you can check against it during an incident:
| Symptom | Metrics to check first | First tool | What to look for |
|---|---|---|---|
| High CPU usage | process_cpu_seconds_total, container CPU | CPU profile (/debug/pprof/profile?seconds=30) | Functions with high flat; the share taken by GC functions |
| CPU not high but latency is, as if "stuck" | container_cpu_cfs_throttled_periods_total, scheduling latency | Throttling and GOMAXPROCS first, then an execution trace | Share of periods throttled; how long goroutines wait to run |
| Memory keeps growing | go_gc_heap_live_bytes, process_resident_memory_bytes | Two heap profiles, subtracted with -base | Allocation sites still growing between the two |
| Restarts with OOMKilled | kube_pod_container_status_last_terminated_reason, working set | kubectl describe pod, then the row above | Whether the Go heap grows, or memory outside the heap |
| Goroutine count only grows | go_goroutines | Goroutine profile (debug=1) | The largest group of identical stacks that keeps growing |
| Throughput stalls, CPU not saturated | Latency distribution, go_sched_latencies_seconds | Mutex and block profiles | Where goroutines wait longest for locks or channels |
| Frequent GC, CPU eaten by GC | go_gc_duration_seconds, go_gc_heap_goal_bytes | GODEBUG=gctrace=1, alloc_space | The functions that allocate most |
| Occasional latency spikes, invisible in averages | p99, p999 | Execution trace or flight recorder | What goroutines were waiting for at that moment: GC, scheduling, syscalls, locks |
The key column is "metrics to check first": metrics are cheap and always on, and tell you when the problem happened and which resource is affected; profiles cost more, and you need to know which kind to take and when.
Step 2: Signals to collect all the time
Adding monitoring once the incident has started is usually too late. These signals should be collected from the day each service goes live:
Go runtime signals. Go's runtime/metrics package provides a set of metrics with stable names that are cheap to read. The most useful are:
| runtime/metrics name | Prometheus name (client_golang) | Use |
|---|---|---|
/sched/goroutines:goroutines | go_goroutines | Number of goroutines; only ever rising signals a leak |
/gc/heap/live:bytes | go_gc_heap_live_bytes | Heap marked live by the last GC; the most direct leak signal |
/gc/heap/goal:bytes | go_gc_heap_goal_bytes | Target size for the next GC |
/memory/classes/total:bytes | go_memory_classes_total_bytes | All memory the Go runtime obtained from the OS |
/memory/classes/heap/released:bytes | go_memory_classes_heap_released_bytes | The part already returned to the OS |
/cpu/classes/gc/total:cpu-seconds | (compute the ratio yourself) | CPU time spent on GC |
/sched/latencies:seconds | go_sched_latencies_seconds | How long goroutines wait between runnable and running |
/sched/gomaxprocs:threads, /gc/gogc:percent, /gc/gomemlimit:bytes | go_sched_gomaxprocs_threads and so on | The settings actually in effect, not the ones you assume |
Scheduling latency deserves a special mention: it measures how long a goroutine that is ready to run spends queueing. When it is high, the CPU is insufficient (throttled, or GOMAXPROCS too low) rather than the code itself being slow, and a CPU profile cannot show you that.
If the service does not use Prometheus, or you want a summary directly on the debug endpoint, you can read runtime/metrics yourself:
package obs
import (
"math"
"runtime/metrics"
"time"
)
// RuntimeStats holds the runtime numbers to look at first during an incident.
type RuntimeStats struct {
Goroutines uint64 // current number of goroutines
HeapLiveBytes uint64 // heap marked live by the last GC
HeapGoalBytes uint64 // heap size goal for the next GC
HeapObjBytes uint64 // objects on the heap (live + not yet collected)
ReleasedBytes uint64 // heap returned to the OS
GoTotalBytes uint64 // all memory the runtime obtained from the OS
GCCycles uint64 // total number of GCs
GCCPUFraction float64 // share of CPU used by GC (since start)
SchedP99 time.Duration // p99 wait from runnable to running
GOMAXPROCS uint64
GOGC uint64
GOMEMLIMITByte uint64
}
var sampleNames = []string{
"/sched/goroutines:goroutines",
"/gc/heap/live:bytes",
"/gc/heap/goal:bytes",
"/memory/classes/heap/objects:bytes",
"/memory/classes/heap/released:bytes",
"/memory/classes/total:bytes",
"/gc/cycles/total:gc-cycles",
"/cpu/classes/gc/total:cpu-seconds",
"/cpu/classes/total:cpu-seconds",
"/sched/latencies:seconds",
"/sched/gomaxprocs:threads",
"/gc/gogc:percent",
"/gc/gomemlimit:bytes",
}
// ReadRuntimeStats reads all samples at once; runtime/metrics is cheap to read, so call it on every scrape.
func ReadRuntimeStats() RuntimeStats {
s := make([]metrics.Sample, len(sampleNames))
for i, n := range sampleNames {
s[i].Name = n
}
metrics.Read(s)
u := func(i int) uint64 {
if s[i].Value.Kind() != metrics.KindUint64 {
return 0 // older Go versions lack this metric
}
return s[i].Value.Uint64()
}
f := func(i int) float64 {
if s[i].Value.Kind() != metrics.KindFloat64 {
return 0
}
return s[i].Value.Float64()
}
st := RuntimeStats{
Goroutines: u(0),
HeapLiveBytes: u(1),
HeapGoalBytes: u(2),
HeapObjBytes: u(3),
ReleasedBytes: u(4),
GoTotalBytes: u(5),
GCCycles: u(6),
GOMAXPROCS: u(10),
GOGC: u(11),
GOMEMLIMITByte: u(12),
}
if total := f(8); total > 0 {
st.GCCPUFraction = f(7) / total
}
if s[9].Value.Kind() == metrics.KindFloat64Histogram {
st.SchedP99 = time.Duration(Quantile(s[9].Value.Float64Histogram(), 0.99) * float64(time.Second))
}
return st
}
// Quantile returns the upper bound of the bucket holding the q-th quantile (a conservative estimate).
func Quantile(h *metrics.Float64Histogram, q float64) float64 {
var total uint64
for _, c := range h.Counts {
total += c
}
if total == 0 {
return 0
}
target := uint64(math.Ceil(q * float64(total)))
var seen uint64
for i, c := range h.Counts {
seen += c
if seen >= target {
upper := h.Buckets[i+1]
if math.IsInf(upper, 1) {
return h.Buckets[i] // the last bucket has no upper bound, fall back to its lower bound
}
return upper
}
}
return h.Buckets[len(h.Buckets)-1]
}A few design considerations:
- Read all samples at once.
metrics.Readtakes a slice and fills it in one go; do not call it once per metric. - Check
Kind(). Metric names are stable, but older Go versions may lack some metrics, in which caseKind()isKindBad. The code must tolerate reading 0 rather than panicking. The tests usemetrics.All()to confirm that every name used here exists in the current version. - Compute quantiles from histograms yourself.
/sched/latencies:secondsis a histogram;Quantilereturns the upper bound of the bucket containing the quantile, a conservative estimate.
With Prometheus, the Go collector in client_golang already converts these metrics. By default it exports only the traditional metrics such as go_memstats_*; you need to switch on the GC, memory and scheduler runtime metrics explicitly:
package obs
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
)
// NewRegistry adds the GC, memory and scheduler runtime/metrics on top of the default go_memstats_*.
func NewRegistry() *prometheus.Registry {
reg := prometheus.NewRegistry()
reg.MustRegister(
collectors.NewGoCollector(collectors.WithGoCollectorRuntimeMetrics(
collectors.MetricsGC, collectors.MetricsMemory, collectors.MetricsScheduler,
)),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), // process_resident_memory_bytes and friends
)
return reg
}Container signals. The Go runtime cannot see problems caused by container limits; for those you rely on cAdvisor (built into the kubelet) and kube-state-metrics:
container_cpu_cfs_throttled_periods_totaldivided bycontainer_cpu_cfs_periods_total: the share of CPU periods that were throttled. If average CPU usage is modest but this ratio is high, you have the throttling problem described in step 4.container_memory_working_set_bytes: the number the kubelet uses to judge memory pressure, and whatkubectl top podshows. It includes part of the file cache, so it is a little larger than the memory Go reports itself.kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}and the restart count: the record of OOM kills.
Why RSS and the Go heap do not match. This is the most common question in memory problems. The container sees the resident memory of the whole process (RSS), while a heap profile sees only the "live objects" within it. There are several layers in between:
Figure: RSS covers everything; what the Go runtime manages, minus pages returned to the OS, is what GOMEMLIMIT counts; inuse in a heap profile corresponds only to the live objects at the bottom.
From the bottom up:
- Live objects: this is the layer a heap profile's
inuse_spaceshows, andgo_gc_heap_live_bytesis its size at the last GC. - Garbage awaiting collection: objects nothing refers to any more, but the next GC has not happened yet. By default GC triggers when the heap reaches about twice the live size (
GOGC=100), so this layer can routinely be as large as the live objects. - Free heap: space kept after a GC for future allocations. The runtime gradually returns unused pages to the OS in the background, and once returned they no longer count towards RSS.
- Goroutine stacks and runtime metadata: this layer thickens when goroutines leak, as each goroutine has a stack of at least a few KB.
- Memory Go does not manage: memory allocated by C libraries called through cgo, and the image of the program itself.
GOMEMLIMITdoes not count this layer.
So the rule of thumb is: if RSS and go_gc_heap_live_bytes grow together, the problem is in Go's live objects and a heap profile will find it; if RSS grows but the live heap does not, look at the goroutine count (stacks), at which of the go_memory_classes_* classes is growing, and at whether cgo is involved.
Step 3: Exposing pprof safely in production
The previous article already showed how to mount pprof on its own ServeMux. When you actually deploy to Kubernetes you must also decide three things: which address pprof, metrics and the business API each listen on; who may connect; and who controls the cost of profiling.
Figure: the business API is exposed through Ingress; /metrics listens on the Pod IP for Prometheus; pprof listens only on 127.0.0.1 and is reachable only through kubectl port-forward.
How the three ports divide the work:
| Port | Listen address | Who connects | Why split it this way |
|---|---|---|---|
:8080 business API | all interfaces | Ingress, other services | Its own mux with business routes only; /debug/pprof/ cannot leak in |
:9090 /metrics | all interfaces | Prometheus | Prometheus scrapes the Pod IP; NetworkPolicy restricts the source |
127.0.0.1:6060 | loopback only | Engineers (port-forward) | pprof reveals internals and a CPU profile consumes resources; no direct network access |
The debug server:
package obs
import (
"encoding/json"
"net/http"
"net/http/pprof"
"runtime"
"time"
)
// EnableContentionProfiling turns on the mutex and block profiles (off by default).
// The rates are deliberately conservative: leaving them on in production costs very little.
func EnableContentionProfiling() {
runtime.SetMutexProfileFraction(100) // record about 1 in 100 contention events
runtime.SetBlockProfileRate(int(time.Millisecond)) // sample about once per 1ms spent blocked
}
// NewDebugMux is internal only: pprof and a runtime summary, never on the public router.
func NewDebugMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index) // heap, goroutine, allocs, mutex, block...
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile) // CPU, ?seconds=30
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace) // execution trace, ?seconds=5
mux.HandleFunc("/debug/runtime", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(ReadRuntimeStats())
})
return mux
}
// NewDebugServer listens on 127.0.0.1 by default; from outside it is reachable only through kubectl port-forward.
func NewDebugServer(addr string) *http.Server {
return &http.Server{
Addr: addr,
Handler: NewDebugMux(),
ReadHeaderTimeout: 5 * time.Second,
}
}Compared with the previous article there are two additions: /debug/runtime returns a JSON summary built from step 2's ReadRuntimeStats, so during an incident one curl shows the goroutine count, live heap, GC goal and the real GOMAXPROCS; and the mutex and block profile rates are set to conservative fixed values, so the data is already there when step 8 needs it, without a redeploy.
main wires up the three servers:
package main
import (
"context"
"log/slog"
"net/http"
"os"
"runtime/trace"
"time"
"example.com/shop/internal/obs"
"example.com/shop/internal/order"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
obs.EnableContentionProfiling()
// Flight recorder: always keeps roughly the last 10 seconds of execution trace, written out only when something goes wrong.
fr := trace.NewFlightRecorder(trace.FlightRecorderConfig{MinAge: 10 * time.Second, MaxBytes: 16 << 20})
if err := fr.Start(); err != nil {
slog.Warn("flight recorder disabled", "err", err)
}
// 1. pprof: listens on 127.0.0.1 only, reached through kubectl port-forward.
debug := obs.NewDebugServer(envOr("DEBUG_ADDR", "127.0.0.1:6060"))
go serve("debug", debug)
// 2. Metrics: Prometheus must scrape it, so it listens on the Pod IP, but no Service exposes it.
metricsMux := http.NewServeMux()
metricsMux.Handle("/metrics", promhttp.HandlerFor(obs.NewRegistry(), promhttp.HandlerOpts{}))
go serve("metrics", &http.Server{Addr: ":9090", Handler: metricsMux, ReadHeaderTimeout: 5 * time.Second})
// 3. The public application: its own mux, with no /debug paths at all.
q := &order.Quoter{Fetch: fetchQuote, Timeout: 300 * time.Millisecond, MaxItems: 10_000}
app := http.NewServeMux()
app.Handle("GET /quote", obs.SnapshotOnSlow(fr, time.Second, "/tmp/slow.trace", q))
serve("app", &http.Server{Addr: ":8080", Handler: app, ReadHeaderTimeout: 5 * time.Second})
}
func serve(name string, s *http.Server) {
slog.Info("listening", "server", name, "addr", s.Addr)
if err := s.ListenAndServe(); err != nil {
slog.Error("server stopped", "server", name, "err", err)
os.Exit(1)
}
}
func envOr(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
// fetchQuote stands in for a call to the inventory service; here it returns fixed content.
func fetchQuote(ctx context.Context, sku string) []byte {
return []byte(`{"price":1990}`)
}Graceful shutdown is left out here; in production, handle signals and Shutdown as in “Configuration and Graceful Shutdown in Go”. The flight recorder is explained in step 10.
Connecting to take profiles:
# Find the problem Pod (for example the one using most memory)
kubectl -n shop top pod -l app=order --sort-by=memory
# Forward the Pod's 127.0.0.1:6060 to your own machine
kubectl -n shop port-forward pod/order-7c9f8d6b5-x2k4q 6060:6060
# In another terminal: look at the summary first, then save profiles
curl -s http://localhost:6060/debug/runtime
curl -so heap-1.pb.gz http://localhost:6060/debug/pprof/heap
curl -so goroutine-1.pb.gz http://localhost:6060/debug/pprof/goroutinekubectl port-forward relays through the API server and the kubelet to localhost inside the Pod's network namespace, so a debug server listening only on 127.0.0.1 is still reachable. Whether someone may port-forward is decided by RBAC permission on the pods/portforward subresource; in production grant it only to whoever is on call. See “A Kubernetes Configuration Reference: What to Write in Each Field, and Why” for how to write those permissions.
Save first, analyse later. Running go tool pprof http://... directly is convenient, but during an incident it is better to save with curl first: name the file with the Pod and the time, and you can compare it later, attach it to the incident report, and still have it after the Pod restarts.
The cost of profiling:
| Profile | Cost | Advice for production |
|---|---|---|
| heap, allocs | Sampling is always on (by default about once per 512 KB allocated); reading just writes it out | Take it any time |
| goroutine | Collects every goroutine's stack; with very many goroutines it takes time and briefly pauses | Fine to take, but do not poll it frequently |
| CPU | Extra cost while sampling, usually small; only one CPU profile can run at a time | 30 seconds at a time, not several people at once |
| mutex, block | Depends on the rate; SetBlockProfileRate(1) records every blocking event and is expensive | Leave on at a conservative rate, or raise it only during an incident |
| execution trace | More than a CPU profile, and the file is large | Take only a few seconds |
"Only one CPU profile at a time" is a runtime restriction: a second request gets the error cpu profiling already in use. If a continuous profiling agent is fetching CPU profiles periodically, your manual one may collide with it.
Step 4: CPU spikes: profiles, flame graphs and before-and-after comparison
When CPU usage is high, take a 30-second CPU profile while the problem is happening; taken after it has passed, it only shows normal behaviour.
curl -so cpu-incident.pb.gz 'http://localhost:6060/debug/pprof/profile?seconds=30'
# Web UI: flame graph, call graph, source
go tool pprof -http=:8081 cpu-incident.pb.gz
# Text: sorted by flat and by cum
go tool pprof -top -nodecount=15 cpu-incident.pb.gz
go tool pprof -top -cum -nodecount=15 cpu-incident.pb.gz
# Who calls a function, and what it calls
go tool pprof -peek 'json.Marshal' cpu-incident.pb.gz
# Per-line cost (needs matching source; use -source_path or -trim_path if paths differ)
go tool pprof -list 'Quoter..ServeHTTP' cpu-incident.pb.gzFigure: width is the share of samples, not time order; wide frames at the top have high flat; GC background work forms its own tower, a sign of too many allocations.
When reading a flame graph during an incident, these are the shapes you see most:
- One wide, tall plateau: a business function is itself heavy, for example JSON serialisation repeated in a loop, or a regular expression recompiled every time. The fix is to compute less or cache the result.
runtime.mallocgcis wide, with agcBgMarkWorkertower beside it: the time goes on allocating and collecting memory, not on computation. Look at GC pressure in step 9 and start from the biggest allocators rather than optimising the algorithm.syscallorruntime.futexis wide: many system calls or thread switches, common with lots of small log writes, unbuffered I/O or too many goroutines contending.- Standard library packages such as
regexp,encoding/jsonorfmttake a large share: usually the library is not slow; it is being called too often. Use-peekto see who calls it.
After the fix, take another profile the same way and compare it with the one from the incident:
curl -so cpu-after.pb.gz 'http://localhost:6060/debug/pprof/profile?seconds=30'
go tool pprof -http=:8081 -diff_base=cpu-incident.pb.gz cpu-after.pb.gz-diff_base uses the older profile as the baseline and shows how much each function grew or shrank. If the traffic differed between the two samples, absolute numbers are meaningless; add -normalize to scale by the baseline's total and compare proportions instead.
CPU not saturated but slow: cgroup throttling. The second incident (p99 up to 2 seconds while CPU used only 60% of the limit) was exactly this. Kubernetes implements the CPU limit with a CFS quota: each period is 100ms, and a limit of 2 means at most 200ms of CPU time per period. If Go is running on 16 threads at once, the 200ms quota can be used up a dozen or so milliseconds into the period, after which the whole process is paused until the next period. Average CPU usage stays low, but every period contains a stretch where nothing can run, and latency stretches accordingly.
Check in this order:
- Look at the throttling ratio (step 2's cAdvisor metrics). If it is high, this is your problem.
- Look at
go_sched_gomaxprocs_threads, orGOMAXPROCSin/debug/runtime, and compare it with the container's CPU limit.
The default GOMAXPROCS depends on the version: from Go 1.25, on Linux the default takes the cgroup CPU limit into account (rounding up to a whole number, and never below 2 unless the machine itself has fewer than 2 CPUs) and updates automatically when the limit changes. But this behaviour depends on the go version in the main module's go.mod: modules whose go version is 1.24 or lower keep the old behaviour (machine CPU count only), even when built with a newer toolchain. go doc runtime.GOMAXPROCS shows the description for your version.
| Situation | Advice |
|---|---|
go.mod at 1.25 or later, Linux, CPU limit set | Nothing extra needed; confirm the actual value with metrics |
go.mod at 1.24 or lower | Raise the go version; if you cannot, set the GOMAXPROCS environment variable explicitly, or use a community package (for example go.uber.org/automaxprocs) to set it from the cgroup at start-up |
| No CPU limit | GOMAXPROCS equals the node's CPU count and there is no throttling, but make sure requests are sensible so services do not starve each other |
Another option is to set no CPU limit at all, only requests, so the service can use idle CPU on the node. That is a legitimate trade-off that depends on your team's resource policy; but whenever a limit is set, make sure GOMAXPROCS agrees with it.
Step 5: Memory keeps growing: subtracting two heap snapshots
Rising memory is not necessarily a leak. First look at the shape of the curve:
Figure: the peaks of the sawtooth are the GC goal and the lower edge is the live heap; healthy, the lower edge stays flat; while a cache warms up it rises then flattens; with a leak it keeps rising.
Go's memory curve is naturally a sawtooth: allocation pushes the heap up and GC pulls it back to the live size. Watch the lower edge of the sawtooth, which is go_gc_heap_live_bytes. Just after start-up a cache is filling and the lower edge rises, but it levels off once the cache is full; with a leak the lower edge keeps climbing until it hits the limit. So judge leaks over a long enough window, at least past the point where "the cache should be full by now".
inuse_space and alloc_space answer different questions:
| View | Answers | Use during an incident |
|---|---|---|
inuse_space | Who allocated the objects alive right now | Memory keeps growing, OOMKilled: find who is holding memory |
inuse_objects | How many objects are alive right now | Huge numbers of small objects (millions of entries in a map) |
alloc_space | How much has been allocated since start | GC is busy and eating CPU: find who creates short-lived objects (step 9) |
alloc_objects | How many objects allocated since start | Hot spots that allocate often but little each time |
A single heap profile has a trap: the biggest entry is not necessarily the problem. Connection pools and preloaded product data are supposed to take memory. What you want is the entry that "keeps growing", and the way to find it is to take two snapshots a few minutes apart and subtract them with -base:
Figure: the second snapshot minus the first; steady allocations cancel out, leaving only fetchSlow, which keeps growing.
Here is a deliberately broken handler to demonstrate. The order service has a quote endpoint that asks inventory for a price and returns 504 on timeout:
package order
import (
"context"
"net/http"
"sync"
"time"
)
// Fetcher asks downstream (for example inventory) for a quote and returns the raw content.
type Fetcher func(ctx context.Context, sku string) []byte
// LeakyQuoter is a handler that "looks fine" but has two leaks.
type LeakyQuoter struct {
Fetch Fetcher
Timeout time.Duration
mu sync.Mutex
cache map[string][]byte
}
func (q *LeakyQuoter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sku := r.URL.Query().Get("sku")
// Leak one: the key contains the request ID, so every request is a new key, and nothing is ever evicted.
key := sku + ":" + r.Header.Get("X-Request-Id")
// Leak two: an unbuffered channel; after a timeout nobody receives, so the sender blocks forever.
ch := make(chan []byte)
go func() {
b := q.Fetch(context.Background(), sku) // and the request context is not passed either
q.mu.Lock()
if q.cache == nil {
q.cache = make(map[string][]byte)
}
q.cache[key] = b
q.mu.Unlock()
ch <- b
}()
select {
case b := <-ch:
_, _ = w.Write(b)
case <-time.After(q.Timeout):
http.Error(w, "upstream timeout", http.StatusGatewayTimeout)
}
}
// Quoter is the fixed version: the cache key is just the SKU and bounded, and the goroutine always ends.
type Quoter struct {
Fetch Fetcher
Timeout time.Duration
MaxItems int
mu sync.Mutex
cache map[string][]byte
}
func (q *Quoter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sku := r.URL.Query().Get("sku")
if b, ok := q.get(sku); ok {
_, _ = w.Write(b)
return
}
ctx, cancel := context.WithTimeout(r.Context(), q.Timeout)
defer cancel()
ch := make(chan []byte, 1) // capacity 1: the send never blocks even if nobody receives
go func() { ch <- q.Fetch(ctx, sku) }()
select {
case b := <-ch:
q.put(sku, b)
_, _ = w.Write(b)
case <-ctx.Done():
http.Error(w, "upstream timeout", http.StatusGatewayTimeout)
}
}
func (q *Quoter) get(sku string) ([]byte, bool) {
q.mu.Lock()
defer q.mu.Unlock()
b, ok := q.cache[sku]
return b, ok
}
func (q *Quoter) put(sku string, b []byte) {
q.mu.Lock()
defer q.mu.Unlock()
if q.cache == nil {
q.cache = make(map[string][]byte)
}
// shortcut: clears everything when full; switch to an LRU or add a TTL when hit rate matters.
if len(q.cache) >= q.MaxItems {
clear(q.cache)
}
q.cache[sku] = b
}LeakyQuoter has two leaks, both written in ways that are common in production:
- The cache key includes the request ID: the intent was "cache by SKU", but every request becomes a new key, and there is no eviction at all. The map only grows.
- After a timeout, the goroutine is stuck on an unbuffered channel: once
selecttakes the timeout branch, nobody ever receives fromchagain; the background goroutine'sch <- b, after it gets its result, blocks forever. The result it holds is never collected either.
Quoter is the fixed version: the cache key is just the SKU and the cache is bounded (here with the simplification "clear everything when full", whose limit is noted with shortcut: in the code); the channel has capacity 1, so the send never blocks even if nobody receives; and the downstream call carries a context with a timeout, so the downstream request is cancelled after the timeout as well.
To find such a leak in production:
curl -so heap-1.pb.gz http://localhost:6060/debug/pprof/heap
sleep 300
curl -so heap-2.pb.gz http://localhost:6060/debug/pprof/heap
go tool pprof -top -sample_index=inuse_space -base heap-1.pb.gz heap-2.pb.gzTo reproduce it locally, the example module includes a small program that sends two rounds of requests to LeakyQuoter and saves a heap and a goroutine profile after each round:
// leakdemo sends a batch of requests to LeakyQuoter, saves a heap and a goroutine profile before and after,
// and leaves the comparison to go tool pprof -base.
package main
import (
"context"
"flag"
"log"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
"time"
"example.com/shop/internal/order"
)
func main() {
dir := flag.String("out", ".", "directory for the profiles")
n := flag.Int("n", 2000, "requests per round")
flag.Parse()
q := &order.LeakyQuoter{
Timeout: time.Millisecond,
Fetch: fetchSlow,
}
round := func(start int) {
for i := start; i < start+*n; i++ {
r := httptest.NewRequest("GET", "/quote?sku=SKU-1", nil)
r.Header.Set("X-Request-Id", strconv.Itoa(i))
q.ServeHTTP(httptest.NewRecorder(), r)
}
time.Sleep(200 * time.Millisecond) // let downstream reply so the goroutines block on send
}
round(0) // warm-up: it is already leaking before the first snapshot
snapshot(*dir, "1")
round(*n) // "a few minutes later": the same traffic again
snapshot(*dir, "2")
}
// fetchSlow is slower than the timeout and returns 16 KiB each time.
func fetchSlow(ctx context.Context, sku string) []byte {
time.Sleep(5 * time.Millisecond)
return make([]byte, 16<<10)
}
func snapshot(dir, tag string) {
runtime.GC() // the heap profile reflects the most recent GC
for _, name := range []string{"heap", "goroutine"} {
f, err := os.Create(filepath.Join(dir, name+"-"+tag+".pb.gz"))
if err != nil {
log.Fatal(err)
}
if err := pprof.Lookup(name).WriteTo(f, 0); err != nil {
log.Fatal(err)
}
f.Close()
}
// text form, the same as /debug/pprof/goroutine?debug=1
f, err := os.Create(filepath.Join(dir, "goroutine-"+tag+".txt"))
if err != nil {
log.Fatal(err)
}
defer f.Close()
if err := pprof.Lookup("goroutine").WriteTo(f, 1); err != nil {
log.Fatal(err)
}
}And the script that compares them:
#!/bin/sh
# Take two snapshots and compare them; run from the module root.
set -eu
out=$(mktemp -d)
go run ./cmd/leakdemo -out "$out" -n 2000
echo '== heap: inuse_space, 2 - 1 =='
go tool pprof -top -nodecount=8 -sample_index=inuse_space -base "$out/heap-1.pb.gz" "$out/heap-2.pb.gz"
echo '== goroutine: 2 - 1 =='
go tool pprof -top -nodecount=8 -base "$out/goroutine-1.pb.gz" "$out/goroutine-2.pb.gz"
echo '== goroutine?debug=1, largest group =='
head -12 "$out/goroutine-2.txt"The actual output (example output with some lines removed; numbers vary by machine):
== heap: inuse_space, 2 - 1 ==
Type: inuse_space
Showing nodes accounting for 31698.75kB, 100% of 31698.75kB total
flat flat% sum% cum cum%
30162.42kB 95.15% 95.15% 30674.46kB 96.77% main.fetchSlow
512.05kB 1.62% 96.77% 512.05kB 1.62% example.com/shop/internal/order.(*LeakyQuoter).ServeHTTP
0 0% 100% 30674.46kB 96.77% example.com/shop/internal/order.(*LeakyQuoter).ServeHTTP.func1
== goroutine: 2 - 1 ==
Type: goroutine
Showing nodes accounting for 2000, 99.90% of 2002 total
flat flat% sum% cum cum%
2000 99.90% 99.90% 2000 99.90% runtime.gopark
0 0% 99.90% 2000 99.90% example.com/shop/internal/order.(*LeakyQuoter).ServeHTTP.func1
0 0% 99.90% 2000 99.90% runtime.chansend1
== goroutine?debug=1, largest group ==
goroutine profile: total 4001
4000 @ 0x10264fdd8 0x1025e3524 0x1025e3138 0x102729d08 0x102656624
# 0x102729d07 example.com/shop/internal/order.(*LeakyQuoter).ServeHTTP.func1+0x1c7 .../internal/order/quote.go:37How to read it:
- The heap difference: almost all of the extra 30 MB or so between the rounds was allocated by
fetchSlowand retained throughServeHTTP.func1. 2000 requests at 16 KB each is about 31 MB, so the numbers add up.fetchSlowis "who allocated it", but the real question is "who is holding it": the allocation site is often innocent, and you followcumupwards to the code that keeps it alive. - The goroutine difference: exactly 2000 extra goroutines, all parked in
runtime.chansend1, a channel send. That points straight at leak two. - The debug=1 text: identical stacks are merged into one line, "4000 @ ..." (4000 across both rounds), and
quote.go:37below it is thech <- bline. - The heap profile is sampled: by default about once per 512 KB allocated, hence tidy numbers such as
512.05kB. It gives proportions and orders of magnitude, not exact byte counts.
The demo calls runtime.GC() before each snapshot because a heap profile reflects the state as of the most recently completed GC; when fetching from the live endpoint, add ?gc=1 to make the server run a GC before writing the profile.
Common causes of memory leaks:
| Cause | Typical code | Fix |
|---|---|---|
| Unbounded map or cache | Keyed by user ID or request ID, never deleted | A size bound and eviction (LRU, TTL); make sure the key space is finite |
| A sub-slice retaining a large array | Keeping b[:64] from a 10 MB response | Copy what you need with slices.Clone or bytes.Clone |
| A substring retaining a large string | Keeping a small piece cut from a large JSON string | strings.Clone |
| Goroutine leaks | Channels nobody receives from after a timeout; background work never cancelled | Buffered channels; pass a context and cancel it when done (step 7) |
| HTTP response bodies not closed | Forgetting resp.Body.Close() after resp, err := client.Do(req) | Always defer resp.Body.Close(); read the body to the end if the connection should be reused |
time.After in a loop (before Go 1.23) | A timer per iteration, not collected until it fires | From Go 1.23 unreferenced timers can be collected straight away; on older versions use time.NewTimer and Stop |
| A large map after deletions | Once held a million entries, now down to a hundred | The underlying space is not necessarily given back; rebuild a new map if needed |
The line between a warming cache and a leak is often simply "is the number of keys bounded?" Keyed by SKU, the number of products is finite and the cache eventually stops growing; keyed by request ID, it is a leak.
Step 6: OOMKilled in Kubernetes
The Pod in the first incident kept restarting, so start by confirming why:
kubectl -n shop describe pod order-7c9f8d6b5-x2k4qIn the container status of the output, look for this:
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
Restart Count: 6OOMKilled means the container's memory exceeded the limit and the kernel's OOM killer terminated it with SIGKILL (137 = 128 + 9). That is different from Go printing fatal error: runtime: out of memory: the latter means the runtime failed to get memory from the OS, which is less common in containers because the cgroup OOM killer usually acts first. A process killed with SIGKILL gets no chance to clean up, so the logs show no error at all, just an abrupt stop.
GOMEMLIMIT must sit below the limit. The previous article explained how GOMEMLIMIT works; in Kubernetes you set it like this:
apiVersion: apps/v1
kind: Deployment
metadata:
name: order
namespace: shop
spec:
template:
spec:
containers:
- name: order
image: registry.example.com/shop/order:1.8.2
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: '2'
memory: 512Mi
env:
# About 90% of the limit; leaves room for memory Go does not manage and for the kernel
- name: GOMEMLIMIT
value: 460MiBGOMEMLIMIT accepts units such as B, KiB, MiB and GiB; without a unit it is bytes. It counts memory the Go runtime manages and has not returned to the OS (/memory/classes/total:bytes minus /memory/classes/heap/released:bytes) and does not include memory allocated through cgo or the program image, so leave some headroom. Services that use cgo or mmap heavily need more.
But remember what GOMEMLIMIT can and cannot do:
- It can: when the live data is actually small and garbage merely piles up quickly, make the GC run earlier near the limit, so you are not OOMKilled just because "the garbage had not been collected yet".
- It cannot: when the live data itself keeps growing (a leak),
GOMEMLIMITonly makes GC run more and more often and CPU climb higher, and you are still OOMKilled in the end. In that case, the early part of the incident often shows the GC CPU share rising and latency worsening first.
The evidence vanishes when the Pod restarts. The hardest thing about an OOMKilled service is that nobody is there to take a profile at the moment it dies, and the new process after a restart starts with clean memory. A few countermeasures:
- Take it while it grows: leaks build up gradually, so two heap profiles a few minutes apart in the tens of minutes before the restart are enough (step 5). Use the
go_gc_heap_live_bytescurve to pick the moment. - Buy time with a higher limit: raise the limit temporarily so restarts are further apart and you have time to gather evidence. This is mitigation, not a fix.
- Continuous profiling: if this kind of problem recurs, it is worth deploying the continuous profiling from step 11, which lets you look back at the heap profile from just before the restart.
Step 7: Goroutine leaks
The signal for a goroutine leak is clear: go_goroutines only rises and does not follow the ups and downs of traffic. Each leaked goroutine carries its own stack and every object it references, so a goroutine leak eventually becomes a memory problem too.
Figure: the request goroutine ends after a timeout, but the background goroutine is stuck on a channel nobody receives from; every timeout adds one more.
The goroutine profile has three output formats:
| Parameter | Format | Good for |
|---|---|---|
debug=0 (default) | protobuf, for go tool pprof | Comparing two moments with -base |
debug=1 | text, identical stacks merged into one group, count first | Seeing at a glance which group is largest |
debug=2 | text, each goroutine listed separately with its state and wait time | How long individual goroutines have been stuck (for example [chan send, 12 minutes]) |
The quickest approach during an incident is debug=1, because leaked goroutines usually have identical stacks and are merged into the largest group:
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=1' | head -30
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=2' | grep -A12 'chan send' | head -40In debug=2, each goroutine's header shows what it is waiting for and for how long; goroutines that have waited minutes or hours are almost certainly leaked.
The same grouping logic can be written as code and put in a test, so leaks are caught in CI:
package order
import (
"bufio"
"bytes"
"runtime/pprof"
"strconv"
"strings"
)
// GoroutinesByFunc counts goroutines by the first function outside the runtime package.
// It parses the debug=1 text format, the same as /debug/pprof/goroutine?debug=1.
func GoroutinesByFunc() (map[string]int, error) {
var buf bytes.Buffer
if err := pprof.Lookup("goroutine").WriteTo(&buf, 1); err != nil {
return nil, err
}
out := map[string]int{}
count, found := 0, false
sc := bufio.NewScanner(&buf)
for sc.Scan() {
line := sc.Text()
// each group starts like "12 @ 0x1023 0x1045 ..."
if n, _, ok := strings.Cut(line, " @ "); ok {
if c, err := strconv.Atoi(n); err == nil {
count, found = c, false
continue
}
}
// stack lines look like "# 0x1023 example.com/shop/internal/order.(*LeakyQuoter).ServeHTTP.func1+0x84 /src/quote.go:36"
if found || !strings.HasPrefix(line, "#\t") {
continue
}
fields := strings.Split(line, "\t")
if len(fields) < 3 {
continue
}
fn, _, _ := strings.Cut(fields[2], "+")
if strings.HasPrefix(fn, "runtime.") {
continue
}
out[fn] += count
found = true
}
return out, sc.Err()
}
// Grown returns the functions that have at least min more goroutines in after than in before.
func Grown(before, after map[string]int, min int) map[string]int {
g := map[string]int{}
for fn, n := range after {
if d := n - before[fn]; d >= min {
g[fn] = d
}
}
return g
}package order
import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
// slowFetch is slower than the handler's timeout and respects the context.
func slowFetch(ctx context.Context, sku string) []byte {
select {
case <-time.After(20 * time.Millisecond):
return make([]byte, 64<<10)
case <-ctx.Done():
return nil
}
}
func hit(h http.Handler, n int) {
for i := range n {
r := httptest.NewRequest("GET", "/quote?sku=SKU-1", nil)
r.Header.Set("X-Request-Id", strconv.Itoa(i))
h.ServeHTTP(httptest.NewRecorder(), r)
}
}
func grownFor(t *testing.T, h http.Handler, n int) map[string]int {
t.Helper()
before, err := GoroutinesByFunc()
if err != nil {
t.Fatal(err)
}
hit(h, n)
time.Sleep(100 * time.Millisecond) // wait for downstream so goroutines that should end can end
after, err := GoroutinesByFunc()
if err != nil {
t.Fatal(err)
}
return Grown(before, after, n/2)
}
func TestLeakyQuoterLeaks(t *testing.T) {
q := &LeakyQuoter{Fetch: slowFetch, Timeout: time.Millisecond}
grown := grownFor(t, q, 200)
const fn = "example.com/shop/internal/order.(*LeakyQuoter).ServeHTTP.func1"
if grown[fn] < 200 {
t.Fatalf("want >= 200 goroutines stuck in %s, got %v", fn, grown)
}
if len(q.cache) != 200 {
t.Fatalf("cache size = %d, want 200 (one entry per request)", len(q.cache))
}
}
func TestQuoterDoesNotLeak(t *testing.T) {
q := &Quoter{Fetch: slowFetch, Timeout: time.Millisecond, MaxItems: 100}
for fn, n := range grownFor(t, q, 200) {
if strings.Contains(fn, "Quoter") {
t.Fatalf("%s grew by %d goroutines", fn, n)
}
}
}
func TestQuoterCacheIsBounded(t *testing.T) {
q := &Quoter{
Fetch: func(context.Context, string) []byte { return []byte("ok") },
Timeout: time.Second,
MaxItems: 3,
}
for i := range 10 {
r := httptest.NewRequest("GET", "/quote?sku=SKU-"+strconv.Itoa(i), nil)
q.ServeHTTP(httptest.NewRecorder(), r)
}
if len(q.cache) > 3 {
t.Fatalf("cache size = %d, want <= 3", len(q.cache))
}
}TestLeakyQuoterLeaks sends 200 requests that time out and asserts that at least 200 goroutines are stuck in (*LeakyQuoter).ServeHTTP.func1; TestQuoterDoesNotLeak does the same to the fixed version and asserts that no goroutines related to Quoter were added. The benefit of this kind of test is that it checks behaviour, not the way the code is written: if a later refactor makes the channel unbuffered again, the test fails.
In Go 1.27, which this article uses, runtime/pprof also has a built-in goroutineleak profile, which uses a special GC cycle to find goroutines that "can never be woken" (for example, blocked on a channel nothing else refers to any more); it is available at /debug/pprof/goroutineleak?debug=1 in the same way. The leak in the example above is listed by it directly. Earlier Go versions do not have this profile or still treat it as experimental, so check with go doc runtime/pprof before relying on it.
Common goroutine leak stacks and their causes:
| Stack parked in | Common cause |
|---|---|
runtime.chansend1 | Sending on a channel nobody receives from: results after a timeout, a consumer that returned early |
runtime.chanrecv1, chanrecv2 | Waiting on a channel that is never closed: the producer forgot to close |
runtime.selectgo | A select without <-ctx.Done(), or a context that is never cancelled |
net/http.(*persistConn).readLoop, writeLoop | HTTP response bodies not closed; or a new http.Client/Transport per request |
sync.(*WaitGroup).Wait, sync.(*Mutex).Lock | Waiting for a WaitGroup that never reaches Done, or a deadlock |
time.Sleep or timer loops | A background loop with no stop condition, started again every time the service reconfigures |
The principle behind every fix is the same: every go statement must know when it ends. Pass a context and listen for ctx.Done() in select; a channel sender must have a way out if the receiver may leave (a buffer, or select with ctx.Done()). These patterns are covered in full in “Goroutines, Channels and Concurrency Patterns in Go” and “Go context: Cancellation, Timeouts and Request-Scoped Values”.
Step 8: Lock contention and blocking
When throughput will not rise, the CPU is not saturated and latency is high, goroutines are mostly waiting: for locks, for channels, for a connection pool. A CPU profile records only time spent running and cannot see waiting; for that you need the mutex and block profiles.
| Profile | What it records | How to enable |
|---|---|---|
| mutex | Lock contention: how long holders kept a lock while other goroutines waited | runtime.SetMutexProfileFraction(n): on average 1 in n contention events recorded |
| block | Time goroutines spend blocked on synchronisation: locks, channels, select, WaitGroup | runtime.SetBlockProfileRate(ns): on average one sample per ns nanoseconds blocked |
Both are off by default, which is why step 3's EnableContentionProfiling turns them on at start-up with conservative rates: 1 in 100 contention events for mutex, and on average one sample per 1ms blocked for block. That costs little and can stay on, so the data is there during an incident.
go tool pprof -top -nodecount=10 http://localhost:6060/debug/pprof/mutex
go tool pprof -top -nodecount=10 http://localhost:6060/debug/pprof/blockWhen reading them, note:
- The mutex profile points at the side causing the wait, the code holding the lock too long, so fixes start by shrinking the critical section: move I/O, serialisation and downstream calls out of the lock.
- Block profile numbers are cumulative, the total time blocked since sampling was enabled. To see what is happening "now", take two and subtract with
-baseas well. - The block profile contains places that are meant to wait, such as
Acceptwaiting for new connections, or background workers receiving from a job channel. Those are not problems; look for blocking on the request path. - An exhausted connection pool also shows up as blocking: when all
database/sqlconnections are in use, new queries wait to obtain one. Besides the block profile,WaitCountandWaitDurationfromsql.DB.Stats()are more direct indicators.
For concrete fixes for lock contention (smaller critical sections, sharding by key, lock-free designs), see “Concurrency Pitfalls: From Data Races to Overselling”.
Step 9: GC pressure
The symptoms of GC pressure: functions such as runtime.mallocgc, runtime.gcBgMarkWorker and runtime.scanobject take a large share of the CPU profile, or requests are drafted into helping the GC (mark assist) while allocating, and latency becomes erratic.
The quickest way to observe it is GODEBUG=gctrace=1, which prints one line to standard error for every GC. Here is real output from step 5's example program (example output):
gc 6 @1.855s 0%: 0.077+1.0+0.005 ms clock, 0.92+0.081/2.8/6.4+0.060 ms cpu, 34->34->29 MB, 35 MB goal, 0 MB stacks, 0 MB globals, 12 P
gc 8 @3.672s 0%: 0.12+3.3+0.012 ms clock, 1.4+0.033/8.3/5.8+0.14 ms cpu, 65->66->53 MB, 67 MB goal, 1 MB stacks, 0 MB globals, 12 PField by field:
| Field | Meaning |
|---|---|
gc 8 | The 8th GC |
@3.672s | Time since the program started |
0% | Share of time spent in GC since start; persistently high means GC pressure |
0.12+3.3+0.012 ms clock | Wall-clock time of three phases: stop-the-world sweep termination, concurrent mark, stop-the-world mark termination |
… ms cpu | CPU time for the same three phases; the middle one is split into assist / background / idle mark time |
65->66->53 MB | Heap at GC start, heap at GC end, live heap |
67 MB goal | The heap size goal for this cycle |
12 P | Number of processors used, i.e. GOMAXPROCS |
These two lines already show the leak: the live heap grew from 29 MB to 53 MB, and the GC goal followed from 35 MB to 67 MB. If the live size were flat but GCs were frequent and % high, the problem would be too many allocations rather than a leak. A trailing (forced) means the GC was triggered by the program calling runtime.GC(). The official documentation says the format of this line "is subject to change", so do not write code to parse it; for long-term observation, use step 2's metrics.
gctrace is set through an environment variable and needs a service restart; you can switch it on temporarily for a single Pod.
The order for reducing GC pressure:
- Find the biggest allocators:
go tool pprof -sample_index=alloc_space, or fetch/debug/pprof/allocsdirectly (the same data as heap, with a different default view). - Reduce allocations on hot paths: preallocate capacity, avoid unnecessary
[]byte/stringconversions, usestrconvinstead offmton hot paths. The escape analysis from the previous article explains where allocations come from. - Tune
GOGCorGOMEMLIMIT: with memory to spare, raiseGOGCto trade memory for CPU. This is tuning, not fixing the code, so consider it only after the first two steps.
Care with sync.Pool. sync.Pool is often treated as a cure-all for allocations, but there are several easy mistakes:
- Objects in a pool may be dropped at any time; each GC may clear some of them. It is not a cache, and you cannot assume you get the same object back.
- Reset before putting back: a
bytes.BufferneedsReset(), or the next user reads the previous request's data, which is a data leak risk. - Do not mix objects of very different sizes in one pool: put an occasional 10 MB buffer back and it keeps being reused, effectively holding 10 MB forever. A common approach is not to return buffers above a certain size.
- Use it only after a profile proves allocation is the hot spot. Adding
sync.Poolwithout evidence only adds complexity.
Step 10: Latency spikes without high CPU: execution traces and the flight recorder
There is a class of problem where every profile looks normal: average latency is low, CPU is modest, no obvious hot spot, but every so often a batch of requests is several hundred milliseconds slower. The question then is not "which function takes the time" but "what happened at that moment": a GC pause, goroutines unable to get a CPU, a stuck system call, or waiting on some lock.
A profile is a statistic that flattens time; an execution trace records events on a timeline: when each goroutine was created, started running, blocked and was woken, when GC started, and what each P was doing.
curl -so trace.out 'http://localhost:6060/debug/pprof/trace?seconds=5'
go tool trace trace.outgo tool trace opens a web UI showing the timeline of each P, goroutine analysis, and profiles derived from the trace for blocking, network, system calls and scheduling latency. A trace costs more than a CPU profile and the file is large, so take only a few seconds.
The problem is that an occasional latency spike is hard to catch within those 5 seconds. That is what the flight recorder is for. From Go 1.25, the standard library's runtime/trace provides FlightRecorder: it continuously keeps the most recent stretch of execution trace in memory and writes nothing normally; when the program itself notices "a slow request just happened", it writes that stretch out.
package obs
import (
"log/slog"
"net/http"
"os"
"runtime/trace"
"sync"
"time"
)
// SnapshotOnSlow writes the last few seconds of execution trace from the flight recorder to path when a request exceeds threshold.
// It writes only once per process, so a burst of slow requests cannot fill the disk.
func SnapshotOnSlow(fr *trace.FlightRecorder, threshold time.Duration, path string, next http.Handler) http.Handler {
var once sync.Once
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
if time.Since(start) < threshold || !fr.Enabled() {
return
}
once.Do(func() {
f, err := os.Create(path)
if err != nil {
slog.Error("flight recorder", "err", err)
return
}
defer f.Close()
if _, err := fr.WriteTo(f); err != nil {
slog.Error("flight recorder", "err", err)
return
}
slog.Warn("slow request, trace saved", "path", path, "url", r.URL.Path)
})
})
}In step 3's main, the flight recorder starts recording at start-up (keeping about 10 seconds, at most 16 MB), and the quote endpoint is wrapped in SnapshotOnSlow: as soon as a request takes longer than 1 second, the last 10 seconds of trace are written to a file. Afterwards you retrieve the file and open it with go tool trace to see what every goroutine and the GC were doing around that slow request.
Practical considerations:
- Write only once: the example uses
sync.Once, so a widespread slowdown does not write a trace for every slow request and fill the disk. In practice you might change this to "at most once per interval". - Where to write and how to retrieve it: the container's root file system is often read-only, so mount an
emptyDirat/tmp; the file disappears when the Pod restarts. If the image containstaryou can usekubectl cp; images withouttar, such as distroless, cannot, so add a download endpoint to the debug server or upload directly to object storage. - Only one flight recorder can be active at a time, but it can run alongside a regular
trace.Start.
Common findings when reading traces: a GC was in progress at the moment of the slow request, and the request's goroutine was drafted into mark assist; goroutines were runnable but waited a long time for a P (compare with step 4's throttling); or all the slow requests were stuck on the same lock at the same moment.
Step 11: Continuous profiling: when it is worth it
All the methods above assume that someone is there when the problem happens, or that it lasts until someone arrives to gather evidence. Continuous profiling removes that assumption: a resident agent periodically (for example every 10 to 60 seconds) collects CPU, heap, goroutine and other profiles from each instance and stores them, so you can later query and compare them by time range.
Figure: metrics answer when and which resource is wrong; profiles answer which function; execution traces answer why it is waiting; continuous profiling lets you compare before and after an incident.
Common options:
| Option | How it collects | Suits |
|---|---|---|
| Grafana Pyroscope | An in-process SDK pushes profiles; or Grafana Alloy scrapes pprof endpoints | Teams already on the Grafana stack (Prometheus, Loki, Tempo) |
| Parca | An eBPF agent on each node collects CPU profiles; it can also scrape pprof endpoints | Collecting CPU profiles across the whole cluster without code changes |
| Profilers from cloud providers and APM vendors | An in-process agent library | Teams already using that cloud's or vendor's monitoring |
When it is worth deploying:
- Problems are intermittent and over by the time you connect; or Pods are OOMKilled and the evidence disappears with the restart (step 6).
- You want to answer "why did CPU rise 15% after this release?": comparing profiles from the same time window before and after the release is far easier than reproducing it afterwards.
- There are many services, and manually port-forwarding every time is not practical.
- You want production profiles for the PGO mentioned in the previous article: continuous profiling already has representative CPU profiles.
When there is no hurry: few services, problems that reproduce reliably, and manual profiles are enough. Continuous profiling has costs: the agent's resources, storage, and one more system to operate. Also note that it conflicts with the security design in step 3: if the agent scrapes pprof endpoints from outside, pprof cannot listen only on 127.0.0.1; it must listen on a separate port on the Pod IP, with a NetworkPolicy that admits only the agent. Pushing from an in-process SDK avoids this. And because only one CPU profile can run at a time, a manual one may collide with the agent's.
Linking profiles to requests. Go's runtime/pprof supports labels on goroutines; labels are recorded in CPU profile samples, and later you can use -tagfocus to look only at samples for a given route:
// fragment: add a pprof label per route in middleware
pprof.Do(r.Context(), pprof.Labels("route", "/quote"), func(ctx context.Context) {
next.ServeHTTP(w, r.WithContext(ctx))
})go tool pprof -top -tagfocus='route=/quote' cpu-incident.pb.gzLabel values must come from a bounded set (route templates, service names), never user IDs or request IDs, or profiles become huge. Some continuous profiling platforms can also link profiles to the distributed traces from “Observability in Go: Logs, Metrics and Tracing”, letting you jump from a slow span to the CPU profile for that time; that is a bonus, not a requirement.
Common pitfalls
- Looking only at average CPU usage. Throttling from a CPU limit makes the average look healthy while latency suffers. Always look at the throttling ratio too.
- Taking a profile after the problem has passed. A CPU profile records only those 30 seconds; take one while the problem is happening, before analysing after mitigation. Before rolling back or restarting, spend a few seconds saving a heap and a goroutine profile.
- Drawing conclusions from a single heap profile. The biggest entry may be supposed to be that big; take two a few minutes apart and use
-baseto see what is growing. - Treating the allocation site as the cause of the leak. A heap profile tells you "who allocated" the memory, but the cause of a leak is "who still holds it"; follow
cumupwards to find the holder. - Mistaking a warming cache for a leak. Memory rising after start-up is normal; check whether the live size after GC levels off after a while, and whether the cache's keys are bounded.
- Assuming RSS equals the Go heap. In between are garbage, free heap, goroutine stacks and memory Go does not manage; use
go_memory_classes_*first to see which layer is growing. - Setting
GOMEMLIMITequal to the limit. It does not count cgo or the program image, so at 100% you will hit the container limit first; leave about 10% headroom. - Using
GOMEMLIMITto hide a leak. When live data keeps growing, it only makes GC more frequent and CPU higher, and you are still OOMKilled in the end. - Exposing pprof publicly, or using
DefaultServeMux. Importingnet/http/pprofregisters it onDefaultServeMuxautomatically; the business server must use its own mux, and pprof should listen only on127.0.0.1. - Setting the block profile rate to 1. Recording every blocking event is expensive; a conservative rate left on permanently is more useful than switching it on only during an incident.
- Several people taking CPU profiles at once. Only one can run at a time and the second fails; a continuous profiling agent counts as one.
- Comparing two profiles taken under different traffic. When traffic before and after the fix differs a lot, absolute numbers mean nothing; use
-normalizeor sample under similar traffic. - Assuming
GOMAXPROCSfollows the CPU limit whilego.modstill says 1.24 or lower. The new default follows the module'sgoversion, not the toolchain. - Putting objects back into
sync.Poolwithout resetting them. The next request reads the previous request's data; that is a security problem, not just a bug.
Key takeaways
- The order of incident handling: mitigate (but save a profile first), use metrics to identify the resource, take the matching profile to locate the cause, then verify the fix with metrics and a before-and-after profile comparison.
- Always collect
go_goroutines,go_gc_heap_live_bytes, the GC CPU share,go_sched_latencies_seconds, container throttling and working set, and OOMKilled counts.client_golangneeds runtime metrics switched on explicitly. - RSS is not the Go heap; if the live heap and RSS grow together, use a heap profile; if only RSS grows, look at the goroutine count,
go_memory_classes_*and cgo. - Mount pprof on its own mux listening only on
127.0.0.1, reached through RBAC-controlledkubectl port-forward; give/metricsits own port for Prometheus. Save first, analyse later. - For high CPU, use a 30-second CPU profile and a flame graph;
mallocgcplus a GC tower means too many allocations. Compare after the fix with-diff_base. If the CPU is not saturated yet things are slow, check cgroup throttling andGOMAXPROCSfirst. - When memory keeps growing, watch the live size after GC, take two heap profiles minutes apart and subtract them with
-base; look for "who holds it", not just "who allocated it". - Confirm OOMKilled with
kubectl describe pod; setGOMEMLIMITto about 90% of the limit, but it does not fix leaks. - For goroutine leaks, use
debug=1to group by stack anddebug=2to see how long they have waited; everygostatement must know when it ends. The grouping comparison can go into a test. - For waiting problems, use the mutex and block profiles (off by default; switch them on at start-up with conservative rates); for occasional latency spikes, use execution traces and the flight recorder.
- Continuous profiling pays off when problems are intermittent, Pods restart, or there are many services; plan it together with the "pprof only on localhost" design.
References
- metrics (Go standard library): stably named metrics such as
/gc/heap/live:bytes,/sched/latencies:secondsand/memory/classes/*, used in step 2. - pprof (Go standard library): the predefined profiles, including
goroutineleak, and goroutine labels, used in steps 5, 7 and 11. - net/http/pprof (Go standard library): the HTTP profile endpoints and the
debugandgcparameters, used in steps 3, 5 and 7. - runtime (Go standard library): the
GODEBUG=gctrace=1output format, the defaultGOMAXPROCS,SetMutexProfileFractionandSetBlockProfileRate, used in steps 4, 8 and 9. - A Guide to the Go Garbage Collector (official Go documentation): what memory
GOMEMLIMITcounts and how it works withGOGC, used in steps 6 and 9. - Container-aware GOMAXPROCS (Go blog):
GOMAXPROCSfollows the CPU limit from Go 1.25, enabled by thegoversion ingo.mod, used in step 4. - Flight Recorder in Go 1.25 (Go blog): the
FlightRecorderinruntime/traceand writing out a trace after the fact, used in step 10. - Resource Management for Pods and Containers (Kubernetes documentation): CPU limits are enforced by CFS throttling and memory limits by OOM kills, used in steps 4 and 6.
Next
By now, a single service has been taken all the way through code, testing, observability, deployment and production troubleshooting. Next we widen the view back to the whole system: how to run the api-gateway, order, payment and inventory services together with PostgreSQL and NATS on one machine, able to find each other, with only the entry point exposed. The next article, “Deploying a Whole Microservice System with Docker Compose”, starts from a single compose.yaml.