Course contents · Lesson 20 of 21

Continuous Profiling with Grafana Pyroscope, Hands-On

Putting It Together · Lesson 20 of 21 · 11 min Hands-on

A teammate ran a batch of sales reports at 14:05, and for a minute the shop felt sluggish. Now the CPU is calm, and lesson 19's trace only says that GET /report spent its time in one span with no children. Which function burned the CPU? This lesson adds Grafana Pyroscope to the lab: you profile shop-demo all day, find the hot function in a flame graph and compare the slow minute with a normal one.

The kitchen camera: how Pyroscope collects profiles

As Continuous Profiling explained, a continuous profiler samples call stacks all day at a low rate. A profile records where CPU time went, function by function. Pyroscope is the server that stores each profile with its time and labels, and answers a question like "shop-demo, CPU, 14:04 to 14:06" with one merged flame graph.

Profiles reach the server in one of two ways. In push mode, a Pyroscope SDK, a library inside your program, samples the program's own stacks and uploads them. In pull mode, Grafana Alloy, Grafana's open-source collector agent, fetches profiles from the app, for example from the /debug/pprof endpoints a Go program serves, and writes them to the server.

This lab pushes. The Python SDK, pyroscope-io, copies the running Python thread's stack 100 times a second and uploads what it collected every 10 seconds. The server keeps the uploads and serves a web UI and an HTTP API on port 4040. In the flowchart, notice that you choose the time window only at step 3, long after the samples were taken.

Flowchart. 1: shop-demo with the Pyroscope SDK, pyroscope-io, copies the running stack 100 times a second and pushes a profile every 10 seconds to http://pyroscope:4040. 2: the Pyroscope server on port 4040 stores each profile with its time and labels. Dashed alternative: Grafana Alloy pulls, scraping Go apps' /debug/pprof, then writes to the server. 3: choose what to see, a service and time range such as shop-demo and process_cpu, in the UI on port 4040 or in Grafana. 4: the server merges that window's profiles into a flame graph: total, request frames, build_report, and compute_report as the widest box at the bottom.
Samples are taken all day and the window is picked only when you ask, which is what lets you replay a slow minute.

Add the Pyroscope SDK to shop-demo

The new lab, course-labs/open-source-observability-stack/07-pyroscope, runs four services: shop-demo, loadgen, pyroscope (Grafana Pyroscope 2.4.4) and grafana (Grafana 13.3.2, for the diff later). The shop is lesson 2's code, mounted unchanged. Its image adds one package, pyroscope-io==1.4.0, and a start script, shop-demo/profiled.py, turns profiling on before the shop starts (comments shortened):

import os

import pyroscope

import app as shop  # 01-lab-setup's app.py

def start_profiling():
    pyroscope.configure(
        application_name="shop-demo",
        server_address=os.environ.get("PYROSCOPE_SERVER_ADDRESS", "http://pyroscope:4040"),
        sample_rate=int(os.environ.get("PYROSCOPE_SAMPLE_RATE", "100")),
        tags={"version": shop.VERSION},
    )

if __name__ == "__main__":
    start_profiling()
    shop.main()

application_name becomes the service_name label, the name you pick in the UI. server_address uses the service name pyroscope, because the shop reaches the server inside the lab network. sample_rate is samples per second, 100 by default, and tags adds labels to every profile, here version="1.0.0". The compose file publishes the shop on port 8001 and sets SKIP_PATHS=/report on loadgen, so every report in the profiles is one you sent.

Stop the other labs, start this one, then ask Pyroscope whether it is ready and request one report:

$ cd course-labs/open-source-observability-stack/07-pyroscope
$ docker compose up -d
$ curl -s localhost:4040/ready
ready
$ curl -s localhost:8001/report
{"report": "sales", "days": 30, "total": 86399041}

The first start builds the shop's image and downloads Pyroscope, Grafana and a Grafana plugin, so allow a few minutes. In the first seconds, /ready may answer with a "not ready" message: wait and repeat. A report takes a tenth of a second or more, depending on your CPU.

Find the wide function in the flame graph

Send a few reports with the try-it's loop below, wait 10 to 20 seconds for the next upload, and open http://localhost:4040. Choose the Service shop-demo and its CPU Profile Type, whose name starts with process_cpu; the service pyroscope is the server profiling itself. The timeline above the flame graph stays near zero, because the other routes mostly sleep, except for a bump where your reports ran.

Pyroscope draws the root, total, at the top, with each box's callees below it: the icicle form that How to Read a Flame Graph described. So the top of the call stack, the code that was running, is at the bottom edge of the picture. Look for the widest box with nothing below it.

Icicle flame graph of GET /report with the root on top. total 100%; two dimmed full-width rows of thread, http.server and shop Handler frames; build_report 88%, a caller covered by its child, beside a narrow box for other work; compute_report 87% with nothing below it, so its whole width is self time. A top table lists compute_report self 87% total 87% and build_report self 1% total 88%. Notes: width is the share of samples in the window, the running code sits at the bottom, left to right is not time. Widths illustrative.
compute_report is the hot spot: as wide as its caller, with nothing below it.

build_report is wide but covered by its only child, so it is a caller. compute_report, the loop in the shop's app.py, has nothing below it: its width is self time, CPU spent in the function itself. The panel's Top Table view lists each function's self and total share.

Compare a slow minute with a normal one

A flame graph merged over an hour dilutes a one-minute problem. Time range selection fixes that: drag across the bump on the timeline and the flame graph redraws from that window's profiles only.

To see what changed, you compare two windows. Pyroscope's own UI has no comparison view, so the lab adds Grafana with Profiles Drilldown, a Grafana app for browsing Pyroscope data without writing queries. Grafana downloads it on first start, pinned to version 3.2.0, and reads the Pyroscope data source from a provisioning file, as in lesson 9.

Make a slow minute: run the report loop with seq 100, which keeps the CPU busy for 10 to 30 seconds, then wait two minutes. Open http://localhost:3000 (admin / admin), then Drilldown > Profiles, or /a/grafana-pyroscope-app/explore on the same port. All services lists shop-demo; select it, and its Flame graph tab shows the same graph as port 4040. No Profiles entry means the plugin download failed: see the lab's README.

The Diff flame graph tab has two charts, Baseline and Comparison. Drag across a quiet minute on the first and across the bump on the second. The diff compares each function's share of the total, so busier traffic does not paint everything red. In the diagram, notice where green appears.

Two CPU charts of shop-demo with one bump where reports ran. Baseline: a quiet minute selected before the bump. Comparison: the bump selected. Below, the diff flame graph: total and request frames grey, about the same; build_report 0% to 88% and compute_report 0% to 87% in red, new in the slow minute; other work such as parsing, JSON and logs, 100% to 12%, in green. Legend: red share grew, green share shrank, grey about the same; green is not faster. Numbers illustrative.
Red marks the code that took over the slow minute; green only means the rest got a smaller slice.

The report functions are red because they never ran in the quiet minute; the frames that parse requests and write replies are green only because reports took most of the samples.

Overhead, labels and the link to traces

Overhead. The SDK's cost grows with the sampling rate. At 100 samples a second each sample stands for 10 ms of CPU; PYROSCOPE_SAMPLE_RATE lowers it, but then a window needs longer to collect as many samples. Measure on one instance first, comparing its CPU and latency with one that has profiling off.

Labels. tags puts fixed labels on every profile, such as version, so you can compare versions after a deploy. pyroscope.tag_wrapper({...}) labels only the samples taken inside a block of code. Keep both low-cardinality, as Metric Labels and Cardinality explained: never a user or order ID.

Safety. Profiles reveal function names, file paths and labels. The lab's server asks for no login, so it publishes port 4040 on 127.0.0.1 only. The SDK is not fork-safe after configure(): in a server that forks workers, such as Gunicorn, call it in each worker.

Traces to profiles. With span profiles, the SDK labels each CPU sample with the ID of the request's local root span, its first span in that process, and gives the span a pyroscope.profile.id attribute. Grafana uses it in the data source for Tempo, Grafana's own trace store, to open one request's flame graph from its trace; in Python, the pyroscope-otel package's PyroscopeSpanProcessor does the labelling. This course stores traces in Jaeger, so the lab leaves it out.

Check yourself

Reports slowed the shop for one minute, but in the flame graph of the last 6 hours compute_report looks modest. What do you change?

The time range: drag across that minute on the timeline. Six hours of merged profiles bury one minute of work under the normal traffic.

After a change, the frames that write JSON replies turn green in the diff. Did JSON get faster?

Not necessarily: the diff compares shares, so JSON turns green whenever another function takes a bigger share, even at the same speed.

build_report is 88% wide and its only child, compute_report, is 87%. Which one do you optimise?

compute_report. Its child covers almost all of build_report, whose self time is about 1%, so the CPU goes into compute_report's loop.