Skip to content

How to read a flame graph: profiling a slow Node.js report from CPU profile to fix

What a flame graph's width and height really mean, why time can land on the wrong function, and how we cut a 1.2 second Node.js report to 30 ms.

· 7 min read

  • Performance
  • Profiling
  • Node.js

A flame graph is the quickest way to see where a program spends its CPU time. It is also easy to misread. People look for the tallest tower, optimise it, and find the program is barely faster.

This article profiles a small, deliberately slow Node.js report generator and uses the result to explain what the axes mean, where time gets attributed to the wrong function, and why you often fix two things, not one. Everything here was run on Node 22; the numbers are from one ordinary Linux container, so treat them as relative, not absolute.

The program

It builds a CSV from 40,000 orders, removing duplicate order IDs and formatting the total as pounds:

function dedupe(orders) {
  const seen = [];
  const result = [];
  for (const o of orders) {
    if (!seen.includes(o.id)) {
      seen.push(o.id);
      result.push(o);
    }
  }
  return result;
}

function formatMoney(x) {
  return x.toLocaleString("en-GB", { style: "currency", currency: "GBP" });
}

function toRow(o) {
  return [o.id, o.customer, formatMoney(o.total)].join(",");
}

function buildReport(orders) {
  const unique = dedupe(orders);
  return unique.map(toRow).join("\n");
}

makeOrders(40000) generates the input: 40,000 orders, of which 4,000 repeat an earlier ID. The report takes about 1.2 seconds. (The join(",") CSV is naive and would break on a value like £1,234.00. Totals here stay below £1,000, so it works. Use a real CSV writer in production.) Nothing in it looks outrageous, which is the point: this is how slow code usually looks.

Take a profile

Node can write a V8 CPU profile with one flag:

node --cpu-prof --cpu-prof-dir=prof app.js

That produces a .cpuprofile file. Open it in the Performance panel of Chrome DevTools, or in a viewer such as speedscope, and you get a flame graph. The default sampling interval is 1 ms (--cpu-prof-interval changes it): V8 pauses, records the call stack, and carries on. Our run recorded about 1,150 samples. Counts vary by a few per cent from run to run, so the figures below are typical, not exact.

That is the whole mechanism. A profile is a pile of stack snapshots. A flame graph is those snapshots merged. (DevTools calls its time-ordered view a flame chart. The ideas below apply to both.)

What the axes mean

  • Width is the share of samples. A frame that is 50% wide was on the stack in half the samples. It is the only measurement on the chart.
  • Height is call depth. A tall tower means a deep call chain, not a slow one. Tall and narrow is usually fine.
  • Left to right is not time. In the classic flame graph, frames are sorted alphabetically so identical stacks merge. A frame on the left did not run before one on the right. Timeline views, like the DevTools one, do use the x-axis for time; know which one you are looking at.
  • Colour usually means nothing. It is there to separate neighbouring frames.

The useful question for any frame is: how much is on top of it? The part of a frame’s width that no child covers is its self time: samples where that function itself was the one running. Wide frames with a thick bare top are where the work happens. Wide frames completely covered by children are just routes to it.

You can compute this yourself, which is a good way to trust the picture. This script folds a profile into the one-line-per-stack format that many flame graph tools accept:

import { readFileSync } from "node:fs";

const profile = JSON.parse(readFileSync(process.argv[2], "utf8"));
const nodes = new Map(profile.nodes.map((n) => [n.id, n]));
const parent = new Map();
for (const n of profile.nodes) for (const c of n.children ?? []) parent.set(c, n.id);

const counts = new Map();
for (const id of profile.samples) counts.set(id, (counts.get(id) ?? 0) + 1);

const folded = new Map();
for (const [id, count] of counts) {
  const stack = [];
  for (let cur = id; cur !== undefined; cur = parent.get(cur)) {
    const name = nodes.get(cur).callFrame.functionName;
    if (name !== "(root)") stack.push(name || "(anonymous)");
  }
  const key = stack.reverse().join(";");
  folded.set(key, (folded.get(key) ?? 0) + count);
}
for (const [k, v] of [...folded].sort((a, b) => b[1] - a[1])) console.log(k, v);

Run on our profile, and trimmed to the frames from buildReport down, the top of the output is:

buildReport;toRow;formatMoney 612
buildReport 465
buildReport;dedupe 29
(garbage collector) 19
buildReport;toRow 9

Each line is a stack, and the number is its self time in samples. So formatMoney accounts for 612 of 1,149 samples, 53% of the run. buildReport accounts for another 465, 40%.

Where the time lands

formatMoney makes sense. It calls toLocaleString, which is built into the engine, so here there is no child frame and the time shows as self time of the JavaScript function that called it.

buildReport is the surprise. It does almost nothing itself: it calls dedupe, then map, then join. Yet dedupe, the function with the accidental O(n²) includes scan, has only 29 samples.

The cause is on-stack replacement (OSR). dedupe is called once and spends its whole life in one long loop, so V8 swaps in optimised code while the loop is running. In this profile, the time in that optimised code is attributed to the caller. We confirmed the switch by turning OSR off:

node --no-use-osr --cpu-prof --cpu-prof-dir=prof app.js

Now the output was (trimmed as before):

buildReport;toRow;formatMoney 597
buildReport;dedupe 481

The 465 samples moved from buildReport to dedupe. --no-opt gives the same result; --no-maglev alone does not. We found the flag by experiment and have not traced the exact mechanism inside V8, so treat the explanation as “OSR is what triggers it”. Changing engine flags distorts timing, so use this to understand the picture, not to measure performance. (Inlining of small functions can cause a similar merge into the caller, but it was not the cause here: --no-turbo-inlining changed nothing.)

The practical rule is that a fat self-time block in a function with a tiny body means optimised code was attributed to the caller, or the callee is native. Read the function’s source and look at what it calls.

Fix the widest thing, then look again

The two fixes are well known. Array.prototype.includes is a linear scan, so dedupe does about n²/2 comparisons; use a Set. And toLocaleString with options does locale setup work on each call; build one Intl.NumberFormat and reuse it.

const fmt = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" });
const formatMoney = (x) => fmt.format(x);

// in dedupe
const seen = new Set();
// ...
if (!seen.has(o.id)) { seen.add(o.id); result.push(o); }

Three runs of each variant gave:

Variant Time
Original about 1.2 s
Reused Intl.NumberFormat only about 0.55 s
Set only about 0.65 s
Both about 0.03 s

The CSV output was byte-identical in the original and fully fixed versions.

Look at the middle rows. The formatter was 53% of the samples, and removing it left about 47% of the time (0.55 of 1.2 s), so the profile predicted the result. Each fix on its own removed only its own share, and the other bottleneck stayed. That is the usual shape: a profile is a ranked list, and the second item becomes the first once you fix it. Profile again after every fix. The new profile of the final version has only about 60 samples in total, spread across the formatter, GC and row building, which is what a finished profile looks like: no wide plateau left to chase.

Mistakes to avoid

  • Profiling a cold, tiny run. Short runs are mostly startup, module loading and JIT warm-up. Use realistic input and enough of it to collect at least a few hundred samples. Our own profile contained a few samples of Node internals loading stdout.
  • Reading width as wall-clock time. A CPU profile counts samples where the thread was running. It says little about time spent waiting on a database, a socket or a lock; those show as (idle) or (program), or not at all. For a slow request, use tracing or timing around the I/O instead.
  • Optimising from one run. Profile two or three times and check the same frames are wide.
  • Chasing the tallest tower. Depth is not cost. Hunt for wide frames with bare tops.
  • Trusting the profile over a benchmark. Profiling distorts timing a little. Confirm the fix with a plain before-and-after timing, as in the table above.

A flame graph tells you where to look. It does not say why the code is slow, and the fixes above came from reading the code it pointed at. Used that way it is quick: one profile here replaced an afternoon of guessing.

Slow reports, exports and API endpoints are a common reason people come to us. Finding the real bottleneck, in code or in the database, is part of how we build and maintain backend systems. Related reading: keyset pagination in Postgres versus OFFSET for a slow-query version of the same story, and git bisect run for finding when a slowdown arrived.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open