Finding Bottlenecks with Flamegraphs
local graph
Chapter 9 — Finding Bottlenecks with Flamegraphs
Section titled “Chapter 9 — Finding Bottlenecks with Flamegraphs”In Chapter 8, we learned how to align our telemetry with business outcomes. We transformed technical signals into verifiable Service Level Objectives (SLOs), measured the real financial cost of latency, and built the Grafana dashboards and burn-rate alerts necessary to catch revenue leaks before the VP of Sales notices them.
But while SLOs and dashboards are excellent at telling you when a system is failing and how much it costs, they often fall short of telling you why the code is slow. Even distributed tracing, which excels at showing us where the bottleneck is within our microservice architecture, only gives us a bounding box around the problem. When a single create_order span suddenly takes four seconds, and we can clearly see the delay is isolated to a specific Rust function call, what do we do next?
This is where tracing ends and profiling begins. Tracing gives you the coordinates of the fire, and profiling gives you the microscope to see what’s burning. In this chapter, we will bridge that final gap. We’ll learn how to use CPU flamegraphs and memory heap profilers to inspect exactly what the Rust runtime and the allocator are doing under the hood during those painfully slow spans.
What this chapter covers:
- Using
scripts/profile_checkout.shto generate load and exaggerate bottlenecks. - Interpreting CPU flamegraphs with
cargo‑flamegraphto find hot paths (e.g. expensive Regex compilation). - Performing heap profiling with
jemallocandjeprofto identify severe allocation overhead. - Fixing the identified Rust code issues and verifying the performance gains through the same observability tools.
Solving “The Mystery of the Slow Checkout”
Section titled “Solving “The Mystery of the Slow Checkout””Before we dive into the specific tools, let’s look at the high-level workflow to solve exactly the kind of incident we saw in Chapter 8. We’ll follow three steps: use traces to locate the problem, use profilers to diagnose the root cause, and then use traces again to confirm the fix. Each tool in our profiling sections maps directly to one of these steps.
Step 1: Trace Identifies the Slow Hop
Section titled “Step 1: Trace Identifies the Slow Hop”When the alert fires, the first tool you reach for is Jaeger. In this chapter’s scenario, start by filtering for high-latency POST /orders traces (for example, around the P99), since the primary symptom is slowness rather than failures. Use error=true as a secondary filter only if the same incident also includes failed requests.
A distributed trace gives us our starting point. In the scenario we’ll simulate in this chapter, looking at our slow create_order traces will expose two shockingly slow spans:
crm_client::fetch_user_loyalty_historypromotions_client::validate_item_discount
These spans show us exactly which functions are causing our latency. But looking at the Jaeger UI doesn’t explain why validating a discount takes 2 seconds, or why fetching a loyalty history overwhelms our allocator. We’ve found the bounding box, but we need to zoom in.
Step 2: Profile the Bottleneck
Section titled “Step 2: Profile the Bottleneck”This is where we shift our focus from distributed tracing to runtime profiling. We aren’t leaving observability behind; rather, we are zooming in. OpenTelemetry gave us the bounding box around the problem, and now Rust’s native profiling tools will let us inspect the exact instructions and allocations inside that box.
To observe CPU utilization, and identify exactly which instructions our processor is spending cycles on, we will build a Flamegraph (see Section: CPU Profiling with Flamegraphs). To observe Memory utilization and understand why our allocator is overwhelmed, we will generate a Heap Profile (Section: Memory Profiling).
Unlike traces, which sample requests in real time, traditional profiling adds significant overhead. In real-world production environments, teams use Continuous Profiling tools (like Parca or Pyroscope) that capture profiles at extremely low sampling rates to keep overhead under 1% while providing fleet-wide visibility.
However, we are intentionally using local, ad-hoc profiling tools rather than a continuous profiling platform. Learning to use cargo‑flamegraph and jemalloc teaches you the fundamentals of how stack traces and heap profiles are actually generated. Furthermore, platforms like Parca rely heavily on eBPF (Extended Berkeley Packet Filter), which requires privileged kernel access that is notoriously complex to configure consistently (and outside the scope of this book) across macOS, Windows, and Linux via Docker Desktop.
By using standard Rust native tools and our scripts/profile_checkout.sh a script to blast the orders service with an artificially high volume of targeted traffic, we can focus on the core profiling workflow without introducing a full continuous-profiling platform setup. The script amplifies the bottlenecks, making them scream out in the profiling tools.
CPU profiling with perf still depends on Linux kernel profiling support and container runtime permissions. In this chapter, the Docker setup is intended for the provided sandbox environment; on Docker Desktop (macOS/Windows) or restricted hosts, behavior can vary, and additional runtime configuration may be required.
Out-of-Stock Errors During Profiling**:** You might see some checkout traces failing with a 409 Conflict. Because our load hits the same product concurrently, the inventory service eventually runs out of stock and aborts the checkouts—proving our distributed transaction safety is working properly under extreme load.
Step 3: Fix and Verify with Traces
Section titled “Step 3: Fix and Verify with Traces”Once the profiler pinpoints the exact line of code (e.g., allocating too many String s or unnecessarily compiling a Regex in a hot loop), we rewrite the Rust logic to be more efficient.
However, the workflow doesn’t end with a code change. To close the loop, we restart our service, run the load generator again, and verify two things:
- The Profiler: The Flamegraph or Heap Profile should now be flat where a mountain used to be.
- The Trace: The span durations in Jaeger for those specific calls should drop back down to milliseconds, restoring our error budget.
Let’s start by simulating the CPU bottleneck and building our first flamegraph.
CPU Profiling with Flamegraphs
Section titled “CPU Profiling with Flamegraphs”This section corresponds to Step 2a of our workflow: profiling the CPU-bound bottleneck identified by tracing.
One of the bottlenecks our trace exposed was the promotions_client::validate_item_discount span, taking an unreasonable amount of time. Since we suspect this is a compute-heavy operation, we will perform CPU profiling.
What Is a Flamegraph?
Section titled “What Is a Flamegraph?”A Flamegraph is a visualization of profiled software, allowing you to quickly identify the most frequent code-paths. Originally created by Brendan Gregg at Netflix, flamegraph have become the standard way to visualize CPU profiles across virtually every language ecosystem.
To build one in Rust, we use the cargo‑flamegraph tool. It wraps standard system profilers (like perf on Linux or dtrace on macOS) and automatically handles the complex task of mapping those raw CPU samples back to your Rust source code and generating an interactive SVG.
The bottlenecks in this chapter are intentionally exaggerated to make profiling patterns visually unmistakable in a flamegraph. Recompiling a regex on every loop iteration and deserializing a massive array into memory produce dramatic, wide pillars that are impossible to miss. Real production bottlenecks are usually subtler: lock contention buried inside a connection pool, allocator fragmentation that accumulates over hours, async runtime starvation from a single blocking call on a Tokio worker thread, cache misses that add microseconds per request but compound under load, or inefficient serialization boundaries between services. These quieter problems produce thinner bands in a flamegraph and require more careful reading. Treat the following examples as a controlled learning environment where the signal is loud by design. The profiling workflow itself (trace to identify the slow hop, profile to find the expensive code, fix, re-profile to verify) applies identically to both the dramatic and the subtle cases.
Setting Up the Profiling Sandbox
Section titled “Setting Up the Profiling Sandbox”First, we need to ensure our Docker container has the OS-level permissions required to run hardware performance counters and has the necessary profiling tools installed. Production multi-stage Dockerfiles usually strip out the Rust toolchain (and debug symbols!) to save space. For our local observability sandbox, let’s create a special profiling‑sandbox stage at the end of orders/Dockerfile:
WARNING: We are intentionally enabling debug and OS-level profiling capabilities in this stage. This is not recommended for production environments.
# Stage 3: Profiling SandboxFROM rust:alpine AS profiling-sandboxRUN apk add --no-cache perf musl-dev jemalloc perl graphvizRUN cargo install flamegraphWORKDIR /appCOPY --from=builder /build/target/release/orders /app/ordersCOPY --from=builder /build/orders/config.docker.toml /app/config.tomlEXPOSE 3003CMD ["/app/orders"]Next, we update our docker‑compose.yml to target this profile stage and grant the necessary capabilities:
orders: build: context: . dockerfile: orders/Dockerfile target: profiling-sandbox # Use our new stage # ... # Grant the kernel capabilities perf needs to read hardware counters. # \`privileged: true\` is the simplest path for a local sandbox; for a # least-privilege setup, drop \`privileged\` and keep only \`cap_add\`. cap_add: - SYS_ADMIN - PERFMON privileged: trueFor this chapter’s quick sandbox setup, privileged: true is the simplest path. If you need more granular permissions, disable privileged: true and enable cap_add with only the capabilities required by your environment.
Finally, ensure the orders service is built with debug symbols enabled. In your workspace Cargo.toml, set debug = true and force‑frame‑pointers = true in the [profile.release] block (and make sure strip is not enabled there). Without debug symbols and frame pointers, stack unwinding can be incomplete, and the profiler may show raw memory addresses instead of clear Rust function names.
Generating the Flamegraph
Section titled “Generating the Flamegraph”With our permissions set and profiler baked in, we re-run docker compose up ‑d ‑‑build orders, apply our load, and attach the profiler:
# 1. Access the running orders containerdocker exec -it -u 0 orders-service sh# 2. In a separate terminal on your host, blast the API with traffic./scripts/profile_checkout.sh# 3. Back in the container terminal, attach the profiler to the running orders process (PID 1)flamegraph --pid 1 --freq 99# 4. When satisfied with the load, press Ctrl+C.# 5. Exit the container and copy the flamegraph to your hostdocker cp orders-service:/app/flamegraph.svg.Why PID 1? Because our Dockerfile uses exec form (CMD ["/app/orders"]), the orders binary is PID 1 inside the container. If you had used shell form (CMD /app/orders), PID 1 would be sh, and you’d need to find the actual process ID with ps aux.
Why ‑‑freq 99? We sample at 99 Hz rather than a round number like 100 to avoid lockstep sampling — a phenomenon where a round frequency can accidentally synchronize with periodic system timers, producing skewed results. 99 Hz gives us nearly the same resolution while avoiding that aliasing effect.
Reading Flamegraphs and Identifying Hot Paths
Section titled “Reading Flamegraphs and Identifying Hot Paths”When you stop the profiler (by pressing Ctrl+C), cargo‑flamegraph will output a file named flamegraph.svg. Open this file in any modern web browser.
Before interpreting the output, keep in mind that flamegraphs represent sampled observations, not exact execution accounting. The profiler interrupts the CPU at a fixed frequency (99 Hz in our setup) and records the stack frame that happens to be active at that instant. Functions that execute between two sample points may not appear at all. Short-lived bursts can be underrepresented or missed entirely. Inline functions may not appear as separate frames unless debug symbols preserve them, and blocking operations (waiting on I/O or locks) do not consume CPU and therefore do not appear in a CPU flamegraph, even though they contribute to wall-clock latency. A flamegraph tells you where the CPU is spending time, not where your request is spending time. For I/O-bound or lock-bound bottlenecks, the trace-based analysis from earlier chapters and the async profiling in Chapter 10 are the right tools.
Here is how you read a Flamegraph:
- The x-axis represents the population of samples. The wider a block is, the more frequently that function is observed running on the CPU. It does not represent a timeline from left to right.
- The y-axis represents the stack depth. The bottom of the graph is the entry point of your program (
main), and as you move up, you see the stack frames of the functions being called. - Colors are usually random variations of warm colors (red/orange/yellow) simply to separate the blocks visually. They carry no semantic meaning.
When you open the SVG generated from our orders service, you won’t see a flat, healthy plain. You will see a massive, undeniable pillar dominating the width of the graph.
Hovering or zooming into that wide pillar, you will see our function: promotions_client::validate_item_discount. But tracing already told us that. What tracing couldn’t tell us is the block sitting directly on top of it:
regex::Regex::new
The flamegraph reveals that the CPU isn’t struggling to execute the regex, but it’s struggling to compile it. By looking at the code in promotions_client.rs, we can see that the service was instantiating and compiling a brand-new Regex object inside a 5,000-iteration loop, simulating an overly complex “legacy rules” check for every single item in the cart.
Fixing the CPU Bottleneck
Section titled “Fixing the CPU Bottleneck”To fix this, we pull the compilation out of the loop and wrap it in a std::sync::OnceLock. This ensures the regex is compiled exactly once on the first request, and cached for all subsequent validations.
Our sample application includes a feature flag for this: setting the environment variable ENABLE_OPTIMIZATIONS=1 in docker‑compose.yml activates the optimized code path at runtime. The flag is read at startup in orders/src/main.rs and toggles between the naive loop-based Regex compilation and the OnceLock -cached version. This lets you switch between the broken and fixed behavior without changing any code, making it easy to compare flamegraphs before and after.
With the CPU bottleneck solved, let’s look at the remaining slow span.
Memory Profiling
Section titled “Memory Profiling”This section corresponds to Step 2b of our workflow: profiling the memory-bound bottleneck that tracing identified but CPU profiling cannot explain.
With the CPU bottleneck resolved, our create_order spans are faster, but crm_client::fetch_user_loyalty_history is still terribly slow. Looking at the code wouldn’t immediately reveal a CPU-heavy loop. What if the function isn’t burning CPU cycles, but is instead drowning in memory allocations? (Yes, “heaps” of them — pun very much intended.)
To find out, we need to inspect the allocator.
Allocator Instrumentation with jemalloc
Section titled “Allocator Instrumentation with jemalloc”Rust uses the system allocator by default, but it also allows us to swap in custom global allocators. jemalloc is a widely used, high-performance allocator that comes with incredibly powerful built-in memory profiling capabilities.
In our orders service, we have configured jemalloc as the global allocator. Many production systems use jemalloc successfully, but allocator choices should still be validated against your own workload. Its profiling feature should remain disabled by default and enabled only during targeted investigations.
In our Docker Compose environment, we have injected the MALLOC_CONF environment variable specifically for the orders service:
MALLOC_CONF: "prof:true,prof_prefix:/app/jeprof.out,lg_prof_interval:24"jemalloc reads this variable incredibly early during program startup. By placing it in docker‑compose.yml, we guarantee it is present before the Rust binary executes.
Heap Profiling
Section titled “Heap Profiling”Because our memory profile needs to write its output to disk (and these files can grow massive very quickly under load), we’ll first update our docker‑compose.yml to instruct jemalloc to flush to disk periodically, rather than waiting for a clean container shutdown, which can be tricky to guarantee:
orders: # ... environment: # ... - MALLOC_CONF=prof:true,prof_prefix:/app/jeprof.out,lg_prof_interval:24Before running this profile flow, ensure your orders crate enables features = ["profiling"] for tikv‑jemallocator in Cargo.toml, and that your orders/Dockerfile installs jemalloc, perl, and graphviz in the profiling‑sandbox stage.
lg_prof_interval:24 means jemalloc emits a heap profile dump roughly every bytes (about 16 MiB) of allocation activity. This gives you periodic snapshots during the process to exit.
Tuning tip: lower values generate more frequent dumps (more detail, more overhead), and higher values generate fewer dumps (less overhead, less granularity).
With the service running and jemalloc configured to profile, we generate our heavy load again:
# 1. In a separate terminal on your host, blast the API with traffic./scripts/profile_checkout.shAs the checkout script blasts the service, jemalloc will periodically flush.heap dump files to the /app directory.
To read these raw heap dumps, we use the jeprof tool, which we already built into our sandbox. We can instruct it to aggregate all the .heap dumps into a single visual SVG graph, and then copy it back to our host machine:
# 2. Extract the memory profile to an SVG inside the containerdocker exec -u 0 orders-service sh -c "jeprof --svg /app/orders /app/jeprof.out.*.heap > /app/memory_profile.svg"
# 3. Copy the profile back to the host machinedocker cp orders-service:/app/memory_profile.svg memory_profile.svgIdentifying Memory Hog
Section titled “Identifying Memory Hog”Opening memory_profile.svg in a browser reveals a graph where the size of the boxes represents the volume of memory allocated by that function.
Following the largest boxes down the tree leads us straight to crm_client::fetch_user_loyalty_history. Looking at the code, we see that this chapter intentionally simulates an unpaginated CRM history by allocating a very large in-memory dataset for each checkout attempt. In the naive path, the service constructs over 15,000 strings in a single Vec<String>, creating a clear allocation hotspot for profiling.
The exact moment this massive vector hits the allocator queue is when performance grinds to a halt.
Fixing the Memory Bottleneck
Section titled “Fixing the Memory Bottleneck”To fix this, we change the simulated CRM client toa request, using just a simple, static loyalty status flag instead of the entire transaction history array, completely eliminating heap allocations in the hot path.
Like the CPU fix, this optimization is controlled by the same ENABLE_OPTIMIZATIONS=1 environment variable. When the flag is set, the orders service calls a lightweight CRM endpoint that returns a single loyalty tier string instead of deserializing the full history. In the current sample setup, this single flag enables both optimizations, so you can compare baseline vs. optimized behavior directly.
Integrating Profiling with Observability
Section titled “Integrating Profiling with Observability”This section corresponds to Step 3 of our workflow: verifying the fix with the same tools that found the problem.
Now that we have removed the massive Regex compilation loop and the catastrophic memory allocation block, we run profile_checkout.sh one final time.
The CPU flamegraph is no longer dominated by Regex compilation in the hot path. The jeprof SVG shows near-zero allocations attributed to the CRM client. Most importantly, when we open Jaeger and review our traces under load, the 2-second P99 latencies on the POST /orders endpoint have vanished.
We successfully used traces to find the general area of the problem, profilers to identify the exact line of bad code, and traces once again to verify the fix restored our business’s error budget.
This is the complete observability-to-profiling loop: Alert → Trace → Profile → Fix → Trace → Confirm. Each tool plays a distinct role, and none of them replaces the others.
Looking Forward: Continuous Profiling
Section titled “Looking Forward: Continuous Profiling”While generating SVGs on your local terminal is phenomenal for ad-hoc debugging (“I have a bug right now and I want to fix it”), modern cloud-native teams take this a step further.
Tools like Parca and Pyroscope introduce the concept of Continuous Profiling. Using eBPF (Extended Berkeley Packet Filter), these platforms attach profiling programs to kernel events and collect stack samples from your production Kubernetes nodes. They sample the CPU and memory stacks of running containers 24/7 with low overhead, aggregating the data into a centralized cluster dashboard.
If a bug causes a massive surge in allocations at 3:00 AM on a Sunday, an on-call engineer doesn’t need to try to reproduce it with a script on Monday morning. They can simply log into the continuous profiling dashboard and view the exact flamegraph from Sunday night.
Even with low runtime overhead, deploying always-on profiling in production requires careful governance. Teams should evaluate kernel compatibility (eBPF support varies across kernel versions and cloud providers), security policies around attaching profilers to production processes, multi-tenant isolation concerns if profiling data from different services or customers is aggregated, symbol management (debug symbols must be available for meaningful stack frames without shipping them in production images), data retention costs for high-cardinality profile data, and organizational comfort with always-on runtime introspection. Start with a single non-critical service, validate the overhead and data pipeline, and expand incrementally.
Just as OpenTelemetry centralized our traces, metrics, and logs, Continuous Profiling is rapidly becoming the standard “fourth pillar” of observability.
Throughout this book, we started with a black-box system and progressively added layers of visibility: distributed traces to follow requests across services (Chapters 3–5), metrics to quantify patterns across millions of operations (Chapter 6), structured logs to capture rich debugging context (Chapter 7), SLOs to translate technical signals into business decisions (Chapter 8), and now runtime profiling to diagnose the exact line of code behind a bottleneck. Each layer answered a question that the previous layers couldn’t. Together, they form a complete observability practice, one that lets you move from “something is wrong” to “here’s the fix, and here’s the proof it worked” with confidence.
Summary
Section titled “Summary”In this chapter, we completed the full workflow: Alert - > Trace - > Profile - > Fix - > Trace - > Confirm. We used tracing to isolate the slow span, CPU and heap profiling to identify concrete code-level bottlenecks, and a final trace pass to verify the latency recovery under load.
Chapter 10 builds on this foundation by shifting from endpoint-level bottlenecks to async runtime behavior, where we will inspect scheduling, contention, and task-level latency patterns that are harder to spot with request traces alone.
References and Further Reading
Section titled “References and Further Reading”Flamegraph Resources
Section titled “Flamegraph Resources”- Brendan Gregg’s Flamegraph page: The canonical reference for flamegraph theory, interpretation, and history. Gregg invented the visualization while working at Netflix. https://www.brendangregg.com/flamegraphs.html
cargo‑flamegraphrepository: The Rust-specific flamegraph tool used in this chapter. Documentation covers platform-specific setup and advanced options. https://github.com/flamegraph-rs/flamegraph
Memory Profiling Resources
Section titled “Memory Profiling Resources”tikv‑jemallocatorcrate: The Rust crate that provides jemalloc as a global allocator with profiling support. https://docs.rs/tikv-jemallocator- jemalloc
MALLOC_CONFdocumentation: Full reference for all profiling options includingprof,lg_prof_interval,prof_prefix, and others. https://jemalloc.net/jemalloc.3.html
Continuous Profiling
Section titled “Continuous Profiling”- Parca: Open-source continuous profiling platform using eBPF. https://www.parca.dev/
- Pyroscope (Grafana): Continuous profiling integrated with the Grafana observability stack. https://grafana.com/oss/pyroscope/
- eBPF overview: For readers curious about the kernel technology underpinning continuous profilers.https://ebpf.io/