How-To Guide

How to Implement Continuous Profiling

Run always-on, low-overhead profiling in production to attribute CPU and memory cost to specific functions and find regressions before users do.

On this page

  1. Introduction
  2. What Continuous Profiling Measures
  3. Keeping Overhead Low
  4. Labeling Profiles for Comparability
  5. Comparing Profiles Across Versions
  6. Memory and Allocation Profiling
  7. Joining Profiles to Traces and Metrics
  8. Common Pitfalls and Conclusion

Introduction

Traditional profiling is a debugging tool you run when someone is already complaining. Continuous profiling flips that: it samples the call stack across the fleet at low, fixed overhead, all the time, and turns the profiles into a queryable dataset. You can then ask “which function consumes the most CPU in the checkout service this week”, compare it to last week, and catch a regression the moment it ships rather than the moment it causes an incident.

What Continuous Profiling Measures

A profiler periodically records which functions are on the call stack, sampled many times per minute, and aggregates the samples into a flame graph. CPU profiles attribute processor time; heap and allocation profiles attribute memory; goroutine or thread profiles show concurrency. Sampling at a fixed rate gives a statistically representative picture without instrumenting every function, which is why overhead can stay in the low single-digit percent.

The key property is attribution. A high-level metric says the service uses four cores; a profile says function X uses thirty percent of that, called from path Y, in request type Z. That specificity is what makes optimisation tractable instead of guesswork.

# A sampled CPU profile, simplified
Total samples: 10,000
  └─ http handler                 92%
      ├─ json.decode                41%   <- optimisation target
      ├─ db.query                    28%
      │   └─ pgx.scanRows            19%
      └─ business logic              23%

Keeping Overhead Low

Continuous profiling only works if it is cheap enough to leave on. Use a sampling profiler rather than an instrumenting one, cap the sampling frequency, and rotate the profile buffers so memory is bounded. As a rule, aim for overhead you can measure but not see: a few percent of CPU and a small, fixed memory footprint.

Measure the overhead yourself rather than trusting a benchmark. Run a load test with profiling on and off and compare throughput and latency. If the overhead is unacceptable, lower the sampling rate; a coarser profile that runs always beats a precise one that is disabled in production.

package main

import (
	"net/http"
	_ "net/http/pprof" // exposes /debug/pprof on the default mux
)

// With net/http/pprof imported, a pull-based profiler can scrape
// CPU and heap profiles from the running process, or you can push
// profiles to a backend. Sampling overhead stays low because the
// runtime samples, it does not trace every call.
func main() {
	http.ListenAndServe(":6060", nil) // pprof endpoints
}

Labeling Profiles for Comparability

A raw profile is a picture of one process at one moment. To compare across time and services you need labels: service, version, environment and ideally the request route or tenant. With labels, profiles from every replica aggregate into one flame graph per service and version, so you can see the effect of a release directly.

Keep label cardinality controlled. Route templates are fine; user ids are not. The same discipline that keeps metrics queryable applies here: labels that change per request make aggregation meaningless and storage unbounded.

// Attach low-cardinality labels so profiles aggregate across replicas.
const profileLabels = {
  service_name: 'checkout-api',
  service_version: process.env.GIT_SHA ?? 'dev',
  deployment_environment: process.env.ENV ?? 'prod',
  region: process.env.REGION ?? 'unknown',
  // never a request id or user id here
};

Comparing Profiles Across Versions

The highest-value use is the diff. Compare the profile of version N with version N+1 and look for functions that got slower or hotter. A regression introduced by a new dependency or an accidentally quadratic loop shows up as a function moving up the flame graph between two versions, which is far more actionable than a p99 that rose by ten percent.

Automate the comparison. After each deploy, compute a diff against the previous version and alert when a function’s share grows beyond a threshold. Treat the profile as a first-class artifact of the release, the way you treat the container image, so every version has a reference profile.

# Version diff (share of total CPU samples)
function                 v1.8.0    v1.9.0   delta
json.decode               12%       11%     -1pp
inventory.enrich          9%        31%    +22pp  <- regression
pgx.scanRows              18%       17%     -1pp

Memory and Allocation Profiling

CPU is half the story. Heap and allocation profiles show where memory is allocated and which data structures retain it, which is how you find the leak that grows for days before an OOM. Alloc-heavy code also drives garbage collection pauses, so reducing allocations often improves latency even when CPU looks fine.

Sample both types on a schedule and compare their trends, not just their snapshots. A slowly rising heap with a stable working set is a leak; a step change after a deploy is a regression in allocation behaviour. Keep profiles long enough to see the trend, which is days, not minutes.

Joining Profiles to Traces and Metrics

Profiles answer “what code is hot”; traces answer “which requests are slow”; metrics answer “how often”. Joining them closes the loop. Some backends link a slow trace to a profile of the exact process that served it, and an exemplar on a latency spike can open both. When the three signals agree, you know not just that something is slow but which function in which request path is responsible.

Start with labels that let you pivot: service, version and route are enough to correlate most problems. Add finer links such as a trace id only when the backend supports it, because the join is only useful if it resolves end to end.

Common Pitfalls and Conclusion

Do not run an instrumenting profiler in production. Do not put high-cardinality labels on profiles. Do not enable profiling only during incidents, because then you have no baseline to compare against. And do not treat a single profile as the truth; it is a sample, so aggregate many before drawing conclusions.

Continuous profiling makes performance a queryable property of your system. Sample cheaply, label by service and version, compare across releases, and join with traces and metrics. The payoff is catching the regression on the deploy that caused it, which is far cheaper than the incident it would otherwise become.

Sources: Google: Continuous profiling, Go: pprof profiling, Parca: continuous profiling.

FAQ

Is continuous profiling safe to run in production?
Yes, when it uses a sampling profiler with a bounded buffer and you measure the overhead. Sampling keeps cost in the low single digits, and the benefit of always having a baseline outweighs the small overhead.
What labels should profiles carry?
Low-cardinality identity: service name, version, environment and region, plus route templates if useful. Never per-request or per-user labels, because they explode cardinality and make aggregation meaningless.

Related Examples