Continuous profiling
A trace tells you which span was slow; a profile tells you which line of code spent the time. Keep one running all the time and link the two
A payments span takes 2.4 s instead of 15 ms. You open the CPU profile for the payments service over the same minute and it looks exactly like yesterday's: no new function, no extra CPU. What is the most likely explanation?
Metrics tell you that something is slow. A trace tells you which service and which span. Inside the span, the trace goes dark: a 120 ms POST /charge with a 1 ms Redis call at each end and 118 ms of nothing in between. You could add more manual spans, but you would have to guess where, redeploy, and wait for the problem to recur. A profile answers the question without guessing: it is a statistical picture of which functions the process was executing, aggregated over thousands of samples.
Continuous profiling means the profiler is always on, in production, and every profile is stored as a time series with labels, so you can ask what the code was doing at 14:32 last Tuesday, compare it with the build before, and jump from a slow trace to the stacks that ran while it was open. This chapter covers how sampling profilers work, how to read a flame graph, what Google learnt running one across its whole fleet, how Pyroscope links profiles to spans, and what all of it costs.
How a sampling profiler works
There are two ways to find out where a program spends its time. An instrumenting profiler records every function entry and exit. It is exact and it is expensive: Python’s built-in cProfile can make a call-heavy program several times slower, which changes the thing you are measuring and rules it out for production.
A sampling profiler instead interrupts the program at a fixed rate, records the current call stack, and lets it carry on. Most run at about 100 Hz, one sample every 10 ms; Pyroscope’s Python SDK defaults to sample_rate=100. Over a minute that is 6,000 stacks per thread. Each stack is a list of frames from the entry point down to the function on the CPU, for example main → serve → handle_charge → fraud_score → sha256. Identical stacks are counted rather than stored, so the result is a table of (stack, count) pairs, which is what the pprof format holds and what every flame graph is drawn from.
The result is statistical. If a function is on the CPU 1% of the time, a minute at 100 Hz gives you about 60 samples of it, with a standard error of roughly the square root of that, about 8. Anything above a few percent is a reliable signal; anything under half a percent in a one-minute window is noise. More time or more instances fix that. A busy service over an hour gives you hundreds of thousands of samples, which is why continuous profiles are more trustworthy than the one you take by hand during an incident.
How the profiler gets the stack depends on the runtime:
| Runtime | How stacks are captured | Common tools |
|---|---|---|
| Go | built into the runtime: a SIGPROF timer, stacks via frame pointers |
net/http/pprof, Pyroscope Go SDK |
| JVM | AsyncGetCallTrace or JFR events, avoiding safepoint bias |
async-profiler, JFR, Pyroscope Java agent |
| CPython | read the interpreter’s frame objects out of process memory | py-spy, Pyroscope Python SDK (which embeds py-spy’s approach) |
| Native code, any language | kernel perf_event timer plus stack unwinding in eBPF |
Parca Agent, the OpenTelemetry eBPF profiler, perf |
CPython is the interesting row. py-spy reads the interpreter’s data structures from another process (or, in Pyroscope’s SDK, from a native thread inside the same process) without stopping the Python code. That is why it is cheap enough to leave on. It also explains two of its options. gil_only=True, the default, samples only the thread holding the Global Interpreter Lock, because only that thread can be running Python. oncpu=True, also the default, skips threads that are idle in a system call. Together they mean the default profile is an on-CPU profile: it shows where Python was doing work.
What kind of time: on-CPU, wall-clock, off-CPU
Pick the wrong profile type and you will stare at a correct picture of the wrong thing.
- An on-CPU profile counts samples only while a thread is running. It answers “what is burning CPU?” and is the default almost everywhere. It is blind to waiting.
- A wall-clock profile samples every thread whether it runs or not. It answers “where is time going, including waits?” In a thread-per-request server that maps cleanly to latency. In an asyncio server it does not: a coroutine that awaits a slow Redis call is not on any stack while it waits. The event loop thread is sitting in
select()and the wall-clock profile showsselect(). - An off-CPU profile, Brendan Gregg’s term, records the stack at the moment a thread blocks and the time until it wakes. It needs kernel scheduler events (eBPF or
perf), and it is the profile that explains lock contention and slow I/O. - Allocation and heap profiles sample memory allocations instead of time. They answer “who allocated these 2 GB?” and “why does GC run so often?” Pyroscope’s Python SDK has
mem_enabled, off by default.
The demo app’s FAULT_SLOW_PAYMENTS_PCT fault is an asyncio.sleep. The Predict above is about it, and the lab shows it: the trace is dramatic and the CPU profile is flat. Profiles and traces are complements. A trace measures waiting precisely and work vaguely; a profile measures work precisely and waiting not at all.
Reading a flame graph
A flame graph, which Brendan Gregg introduced in 2011, draws the (stack, count) table as stacked boxes. Each box is a frame. Its width is proportional to the number of samples whose stack contains it. Its parent is the box below it (or above, in the “icicle” layout Grafana and Pyroscope use, which grows downwards from the root).
Four rules make it readable:
- The x-axis is not time. Frames are sorted alphabetically so identical stacks merge. Left versus right means nothing. (Pyroscope’s timeline above the graph is time; the graph is an aggregate over the selected range.)
- Width is total time, including children. A wide frame is on the stack a lot, which does not mean it is doing the work.
mainis always 100% wide. - Self time is the width a frame has that no child covers. That is where the CPU was actually executing. Wide plateaus at the bottom (or top, in an icicle) are your hot spots. Pyroscope’s table view lists self and total side by side; sort by self first.
- Compare, do not stare. A single flame graph of a healthy service is a wall of framework code. The question is almost always “what changed?” Pyroscope’s diff view colours each frame by how much its share grew or shrank between two time ranges or two label sets, for example
service_version="1.0.0"against"1.1.0".
Two traps catch everyone. Inlined functions disappear into their callers in compiled languages, so a hot function may show up under a name you do not expect. And a profile aggregated over 20 instances hides the one instance that is different; filter by pod or instance label before you conclude “it’s spread evenly”.
Profiling the fleet: Google-Wide Profiling
The idea of always-on profiling is older than most of the tools. In 2010 Gang Ren and colleagues at Google published Google-Wide Profiling (GWP) in IEEE Micro, describing a system that had been profiling nearly every machine at Google for several years. Three of its decisions still define the field.
First, sample in two dimensions. Running a profiler on every machine all the time would cost too much, and running it at a low rate everywhere would make each machine’s profile too sparse to use. GWP instead picks a random subset of machines at any moment, profiles each for a short period, and moves on. The paper reports aggregate overhead of less than 0.01%. Across thousands of machines the random subset still produces stable fleet-wide profiles, which the authors checked by measuring how much the profiles varied from day to day.
Second, collect raw, symbolise later. Production binaries are stripped of debug symbols. GWP stores the addresses, keeps unstripped copies of every binary in a repository, and maps addresses to function names offline in a MapReduce job. Modern eBPF profilers face the same problem and use the same answer: Parca and the OpenTelemetry eBPF profiler upload addresses and resolve them against debug information stored separately.
Third, profiles are queryable data, not files. GWP loads samples into a dimensional database so anyone can ask “which functions use the most CPU across Google?” or “how did this binary change between builds?”. That shift, from a profile you take to a profile you query, is what Pyroscope, Parca and every vendor product inherited. The best-known result built on GWP’s data came five years later: Kanev and colleagues’ 2015 paper “Profiling a Warehouse-Scale Computer” found that a handful of shared functions (allocation, compression, serialisation, RPC, hashing) take a large share of all cycles, which they called the datacenter tax. Optimising one of them pays off in every service that links it.
Linking a profile to a span
The trace says POST /charge took 120 ms. The service profile for that minute says fraud_score used 70% of payments’ CPU. Are they the same thing? Usually, but in a busy service, one request’s profile is mixed with every other request’s. Span profiles narrow the profile to the samples taken while one span was open.
Pyroscope’s Python bridge, the pyroscope-otel package, does it with a span processor. Read its source and you find about thirty lines:
- On every local root span, a span with no parent or whose parent came over the network,
on_startsets the span attributepyroscope.profile.idto the span’s id. In the demo app that is payments’POST /chargeserver span. - It also calls
pyroscope.add_thread_tag()withspan_id,span_nameandtrace_id. The profiler attaches the current thread’s tags to every sample it takes from that thread, so samples taken while the span is open carry its id. on_endremoves the tags.
In Grafana, the Tempo data source’s tracesToProfiles setting points at the Pyroscope data source. Any span carrying pyroscope.profile.id gets a “Profiles for this span” link and an embedded flame graph that queries only the samples with that span_id.
The mechanism has limits you should know before you trust it:
- Only root spans. Child spans inherit the root’s tags because they run on the same thread, so a profile is per request in each service, not per span.
- Threads, not tasks. The tags belong to an OS thread. In an asyncio service every request shares the event loop thread, so while one request awaits, another request’s code runs under the first request’s tags until it sets its own. Work handed to another thread (
asyncio.to_thread, a thread pool, a sync FastAPI handler) runs with no tags at all. Grafana’s own Flask example for span profiles runs the server withthreaded=False. In the lab’s payments service it works because the slow code runs on the loop thread before the firstawait. - Short spans are noise. At 100 Hz a 5 ms span gets zero or one sample. Span profiles are for spans of 50 ms and up.
- Cardinality.
span_idandtrace_idare unique per request. Check what your Pyroscope’s series count does before you enable this across a fleet.
Go and Java have tighter integrations (Go’s pprof labels follow goroutines, not threads), so span profiles are most accurate there. In Python treat them as a strong hint, and confirm with the service-wide profile over the same window.
Cost and overhead
There are three costs, and vendors quote only the first.
CPU on the profiled process. A sampling profiler at 100 Hz takes 100 stack snapshots per second per thread. For py-spy-style reading of interpreter memory, each snapshot is microseconds of work on a separate native thread, so the overhead is typically low single-digit percent of one core or less, and often within measurement noise. eBPF profilers sample in the kernel at a lower rate (Parca Agent samples 19 times per second per logical CPU; an odd rate avoids lock-step with work that runs every 10 or 100 ms) and cost a fraction of that. Do not trust anyone’s number, including this one: the lab measures it.
Network and storage. The Python SDK uploads every 10 seconds (upload_interval=10). A profile is the set of unique stacks seen in that window with their counts. For a typical web service that is a few hundred to a few thousand unique stacks, tens of kilobytes compressed. Do the arithmetic for your fleet before you turn it on: 500 processes × 8,640 uploads per day × 30 KB is about 130 GB per day before the backend deduplicates symbols and compresses. Retention is the main knob; most teams keep raw profiles for days to weeks and rely on the backend’s downsampling after that.
Labels. Every distinct label set is a separate series, exactly as in Prometheus. service_name, service_version, region and pod are fine. user_id is not, and span profiles add per-request tags, which is the cardinality caveat above.
What you buy for that cost: the answer to “which function?” in seconds, for slowdowns you did not predict, after the fact. The alternative is reproducing a production slowdown under a manual profiler, which often fails because the workload that caused it is gone.
Where profiles mislead
- Waiting is invisible to on-CPU profiles. If latency is up and the CPU profile is unchanged, the time is in waits: go to the trace.
- Blocking work looks innocent. A CPU-bound function on an asyncio event loop shows up at its true size in the profile, say 50% of one core. What the profile does not show is that every other request queued behind it, which is the starvation the event loop starvation lesson animates. The trace shows that, in the latency of unrelated requests.
- Missing symbols turn frames into hex addresses. In containers this usually means the image has no debug info or the profiler cannot see the binary’s file system.
- Safepoint bias on the JVM: profilers built on
Thread.getStackTraceonly sample at safepoints and blame the wrong loop. Use async-profiler or JFR. - Survivorship in aggregates. A profile over 50 instances tells you about the average instance. If one instance is hot, its stacks are 2% of the picture.
You will plant a CPU-bound fault in payments, add Pyroscope to the stack, instrument payments with the Python SDK, find the fault in a flame graph, follow a slow span to the samples taken during it, and then measure what the profiler costs. Work in labs/observability.
1. Plant a CPU-bound fault in payments. The lab’s existing slow fault is a sleep, which a CPU profiler cannot see (step 7 proves it). Add one that burns CPU. In services/payments/app.py, add import hashlib to the imports, and this function above @asynccontextmanager:
def fraud_score(order_id: int, rounds: int) -> int:
"""FAULT_FRAUD_ROUNDS: a CPU-bound 'risk model' run inline on the event loop."""
digest = str(order_id).encode()
for _ in range(rounds):
digest = hashlib.sha256(digest).digest()
return digest[0]Then in charge(), directly after the line span.set_attribute("payment.idempotency_key", req.idempotency_key), add:
rounds = int(_env_float("FAULT_FRAUD_ROUNDS"))
if rounds > 0:
span.set_attribute("fault.fraud_rounds", rounds)
fraud_score(req.order_id, rounds)await in the handler, which matters for span profiles in step 6. With 100,000 rounds it takes roughly 50 to 120 ms of CPU per charge, depending on your machine.2. Add Pyroscope and the SDK. Append two pinned packages to services/requirements.txt:
pyroscope-io==1.2.5
pyroscope-otel==1.1.0In services/common/telemetry.py, inside setup_telemetry(), directly after the line tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())), add:
# Continuous profiling, only where PYROSCOPE_SERVER_ADDRESS is set (payments in this lab).
if os.getenv("PYROSCOPE_SERVER_ADDRESS"):
import pyroscope
from pyroscope.otel import PyroscopeSpanProcessor
pyroscope.configure(
application_name=os.environ["OTEL_SERVICE_NAME"], # becomes service_name, matching service.name
server_address=os.environ["PYROSCOPE_SERVER_ADDRESS"],
sample_rate=100,
tags={"service_version": os.getenv("SERVICE_VERSION", "1.0.0")},
)
tracer_provider.add_span_processor(PyroscopeSpanProcessor())In compose.yaml, add two lines to the payments service’s environment: block, after FAULT_LEAK_PII:
FAULT_FRAUD_ROUNDS: ${FAULT_FRAUD_ROUNDS:-0}
PYROSCOPE_SERVER_ADDRESS: ${PYROSCOPE_SERVER_ADDRESS:-}Add the Pyroscope service in the telemetry section, next to tempo:
pyroscope:
image: grafana/pyroscope:1.13.4
profiles: ["telemetry"]
restart: unless-stopped
ports: ["4040:4040"]And in the grafana service, replace the feature-toggle line so the trace view can show profiles:
GF_FEATURE_TOGGLES_ENABLE: traceqlEditor,traceToProfiles,tracesEmbeddedFlameGraphdown. Only payments gets the address, so only payments is profiled. application_name must equal the OTel service.name because Grafana maps the span’s service.name to Pyroscope’s service_name label when it builds the span query.3. Wire Grafana. In grafana/provisioning/datasources/datasources.yaml, add a data source at the end of the datasources: list:
- name: Pyroscope
uid: pyroscope
type: grafana-pyroscope-datasource
access: proxy
url: http://pyroscope:4040
editable: trueAnd inside the Tempo data source’s jsonData: block, next to tracesToMetrics:, add:
tracesToProfiles:
datasourceUid: pyroscope
profileTypeId: "process_cpu:cpu:nanoseconds:cpu:nanoseconds"
customQuery: false
tags:
- key: service.name
value: service_nameprocess_cpu:cpu:nanoseconds:cpu:nanoseconds is the profile type the Python SDK sends: CPU time in nanoseconds. The tags mapping turns the span’s resource attribute service.name="payments" into the label selector {service_name="payments"}.4. Start everything and check profiles arrive.
cat > .env <<'EOF'
OTEL_SDK_DISABLED=false
LOG_FORMAT=json
OTEL_SEMCONV_STABILITY_OPT_IN=http/dup
LOADGEN_RPS=5
PYROSCOPE_SERVER_ADDRESS=http://pyroscope:4040
FAULT_FRAUD_ROUNDS=0
EOF
docker compose --profile telemetry up -d --build
sleep 45
curl -s -H 'Content-Type: application/json' \
-d '{"name":"service_name","start":'$(( $(date +%s) - 600 ))000',"end":'$(date +%s)000'}' \
localhost:4040/querier.v1.QuerierService/LabelValues{"names":["payments"]}. If it is empty, wait another 20 seconds (the SDK uploads every 10 s) and check docker compose logs payments | head -30 for an import error, which means the image was not rebuilt.5. Read the baseline. Save this as prof-top.sh and make it executable (chmod +x prof-top.sh). It fetches a merged profile from Pyroscope’s render API and prints the functions with the most self time:
#!/bin/sh
# usage: ./prof-top.sh '{service_name="payments"}' [window, default 2m]
curl -sG localhost:4040/pyroscope/render \
--data-urlencode "query=process_cpu:cpu:nanoseconds:cpu:nanoseconds$1" \
--data-urlencode "from=now-${2:-2m}" --data-urlencode until=now --data-urlencode format=json \
| python3 -c '
import json, sys, collections
fb = json.load(sys.stdin)["flamebearer"]
names, total = fb["names"], fb["numTicks"] or 1
selfc, totc = collections.Counter(), collections.Counter()
for level in fb["levels"]:
for i in range(0, len(level), 4): # [offset, total, self, name index] per frame
totc[names[level[i + 3]]] += level[i + 1]
selfc[names[level[i + 3]]] += level[i + 2]
print(f"{total} ticks")
print(" self% total% function")
for name, t in selfc.most_common(8):
print(f"{100 * t / total:5.1f} {100 * totc[name] / total:6.1f} {name[:90]}")
'./prof-top.sh '{service_name="payments"}' 2m6. Turn on the fault and follow a slow span to its profile.
FAULT_FRAUD_ROUNDS=100000 docker compose --profile telemetry up -d payments
sleep 120
curl -sG localhost:9090/api/v1/query --data-urlencode \
'query=histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket{job="payments",route="/charge"}[1m])))' \
| jq -r '.data.result[0].value[1]'
./prof-top.sh '{service_name="payments"}' 1m
curl -sG localhost:3200/api/search --data-urlencode 'q={ span.fault.fraud_rounds > 0 }' --data-urlencode limit=3 \
| jq -r '.traces[].traceID'Open one of those trace ids in Grafana (Explore, Tempo data source, paste the id). Click payments’ POST /charge span and expand it.
/charge is up from about 0.01 s to somewhere between 0.1 and 0.5 s: each charge burns CPU and every other charge queues behind it on the event loop. The profile now has one frame for fraud_score with 60 to 90% total time, most of it self time in the sha256 call line, and the tick count has jumped. In the trace, POST /charge is long and its Redis GET and SET children are a millisecond each: the trace shows a gap with no explanation. The span details show the attribute pyroscope.profile.id, a “Profiles for this span” button, and an embedded flame graph that is almost entirely fraud_score. That is the link: from a slow span to the line of code that ran during it, with no extra spans added.7. Prove the profile is blind to waiting.
FAULT_FRAUD_ROUNDS=0 FAULT_SLOW_PAYMENTS_PCT=30 docker compose --profile telemetry up -d payments
sleep 120
./prof-top.sh '{service_name="payments"}' 1m
curl -sG localhost:3200/api/search --data-urlencode 'q={ span.fault.slow_delay_s > 0 }' --data-urlencode limit=3 \
| jq -r '.traces[].traceID'POST /charge takes 1.5 to 3 s. The profile looks like step 5’s baseline, with no new function, and the span’s embedded flame graph is empty or a handful of framework frames. The 2 s were spent in asyncio.sleep, during which the coroutine was not on any stack and the event loop was idle in select(), which oncpu=True excludes. This is the Predict at the top of the chapter. When latency is up and CPU is not, stop looking at profiles and read the trace.8. Measure the profiler’s overhead. Hold the load steady and compare payments’ CPU with the profiler on and off. Take five readings in each state:
FAULT_SLOW_PAYMENTS_PCT=0 docker compose --profile telemetry up -d payments
sleep 30
for i in 1 2 3 4 5; do docker stats --no-stream --format '{{.Name}} {{.CPUPerc}}' atlas-observability-payments-1; done
PYROSCOPE_SERVER_ADDRESS= docker compose --profile telemetry up -d payments
sleep 30
for i in 1 2 3 4 5; do docker stats --no-stream --format '{{.Name}} {{.CPUPerc}}' atlas-observability-payments-1; donedocker compose --profile telemetry up -d payments (the .env value comes back).fraud_score(req.order_id, rounds) to await asyncio.to_thread(fraud_score, req.order_id, rounds), rebuild payments (docker compose --profile telemetry up -d --build payments) and run step 6 again with FAULT_FRAUD_ROUNDS=100000. The service-wide profile still shows fraud_score: it still costs the same CPU. But open a slow trace and the span’s embedded flame graph is now nearly empty. The span processor tagged the event loop thread; the work ran on a worker thread with no tags. Span profiles in Python follow threads, not requests, and any hand-off to a thread pool cuts the link. Put the call back, and leave FAULT_FRAUD_ROUNDS=0 in .env when you finish.You run platform for 40 services on Kubernetes: 25 in Go, 10 in Python, 5 on the JVM. The cloud bill for compute rose 30% over two quarters and nobody can say which code is responsible. The payments team also wants to jump from slow traces to profiles. You have one quarter and one engineer. How do you roll out profiling?
- PAPER Google-Wide Profiling: A Continuous Profiling Infrastructure for Data Centers Gang Ren, Eric Tune, Tipp Moseley, Yixin Shi, Silvius Rus, Robert Hundt, 2010
The paper that defined continuous profiling: sample machines and events, symbolise offline, store profiles as queryable data. Every modern tool is a descendant of these three decisions. Read: the Infrastructure section (two-dimensional sampling, symbolisation, storage) and Reliability analysis; skim the platform-affinity applications.
- POST Flame Graphs Brendan Gregg
The inventor's own page: what the axes mean, how to read width and plateaus, and the variants (differential, off-CPU, memory). Read the first section and the differential flame graphs part; skip the per-language recipes unless you need one.
- POST Off-CPU Analysis Brendan Gregg
Explains the time on-CPU profiles cannot see, how to capture it with scheduler events, and how to read an off-CPU flame graph. The answer to every 'the profile looks normal but it is slow' moment.
- DOC Pyroscope: span profiles for Python
The official setup for pyroscope-otel and the Tempo data source link used in the lab. Short; pair it with the Python SDK page for the configure() options.
- CODE py-spy Ben Frederickson
The README explains how a Python profiler reads interpreter memory from outside the process without slowing it down, and its record and top modes are what you reach for on a box with no continuous profiler.
- DOC Parca documentation: overview
The open-source eBPF alternative to an SDK: a whole-node agent, pprof-compatible storage and the symbolisation design. Read it to understand the agent option in the Decide above.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.