Profiling and finding bottlenecks

Advanced · 20 min

Finding where a Node service spends its time, using event-loop delay and utilization, --cpu-prof CPU profiles, flame graphs and the older --prof tick profiler.

Before thisThe event loop phasesBlocking vs non-blocking I/O

nodeconfeu · 20 min

Profiling and finding bottlenecks

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by nodeconfeuReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Measure first. A Node service is slow for one of two reasons: JavaScript is hogging the single thread, or it is waiting on I/O. The tools for each are different, and guessing wastes days.
  • Event-loop delay (`perf_hooks.monitorEventLoopDelay`) and event-loop utilization (`performance.eventLoopUtilization()`) tell you whether the thread is saturated. High delay with high utilization means CPU-bound JavaScript is blocking the loop.
  • `node --cpu-prof app.js` writes a `.cpuprofile` file on exit that DevTools, speedscope and other viewers open. It samples the call stack and shows where CPU time went.
  • In a flame graph the width of a box is time, and the stack below it shows who called it. Look for wide boxes near the top, which have high self time, and read down for the caller.
  • `node --prof` plus `node --prof-process` is the older, text-based V8 tick profiler. It still works, but its native symbol names can be misleading and the output is harder to read.
  • A CPU profile cannot show time spent waiting. A slow database call or an awaited fetch looks like an idle process, so use logs, tracing and metrics for I/O-bound slowness.

Measure before you optimize

“The service is slow” is not a diagnosis. Node runs your JavaScript on one thread, as covered in the event loop phases, so slowness has two very different causes:

  1. JavaScript is hogging the thread. A heavy loop, a huge JSON.parse, a synchronous call or a bad regex stops everything else. The cure is to find that code and fix or offload it.
  2. The process is waiting. It is idle while a database, an API or a lock responds. The thread is free, and the cure lives elsewhere.

A profile of running JavaScript helps with the first and is blind to the second. So the first measurement is which one you have. For the general metrics side of this, see metrics and instrumentation in application code.

Is the event loop saturated

Node exposes two cheap signals through perf_hooks:

import { monitorEventLoopDelay, performance } from 'node:perf_hooks';

const h = monitorEventLoopDelay({ resolution: 10 });
h.enable();
const before = performance.eventLoopUtilization();

// ... serve traffic ...

h.disable();
console.log('loop delay p50/p99/max ms:',
  (h.percentile(50) / 1e6).toFixed(1),
  (h.percentile(99) / 1e6).toFixed(1),
  (h.max / 1e6).toFixed(1));
console.log('ELU', performance.eventLoopUtilization(before).utilization.toFixed(2));

monitorEventLoopDelay is a histogram of how late timers fire. On an idle loop it sits near the resolution you chose. eventLoopUtilization() reports the fraction of time the loop was busy, from 0 to 1.

I tested this with a tiny HTTP server where one route computed fib(37) synchronously. After two requests to it, the delay histogram showed p50 of about 127 ms and a max of 130 ms, and utilization read 1.00. A route that normally answers in a millisecond was stuck behind 250 ms of someone else’s CPU work. That pattern, high delay plus high utilization, is the signature of blocking JavaScript. If delay is low but requests are slow, the problem is I/O, and you should look at downstream timings instead. Export both numbers as metrics and alert on them. Blocking vs non-blocking I/O is the concept behind them.

Taking a CPU profile

Once you know JavaScript is the culprit, find which function. The built-in way:

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

On exit Node writes a .cpuprofile file, a JSON record of sampled call stacks. Open it in Chrome DevTools (Performance panel, Load profile) or in a viewer like speedscope to get a flame graph. You can also read it with a short script. Summing sample time by function for my test run:

250ms fib slow.mjs:5
 21ms Hash node:internal/crypto/hash
 19ms digest
  9ms update

That is the answer in four lines: fib accounts for most of the time. In a real service you will have a long tail, and a graph is easier than a list.

Two practical notes. The profile is written when the process exits normally, so a server you kill with SIGKILL produces nothing. Handle SIGINT or SIGTERM and exit cleanly, as in deploying Node applications. And you can attach to a running process through the inspector (see debugging with the inspector) and record a profile from DevTools without restarting.

Reading a flame graph

A flame graph stacks functions by call depth. The bottom is the entry point, and each box above it is something it called. A box’s width is how many samples included that function, so wider means more time. Two ideas are enough to start:

  • Self time is time spent in the function’s own code. The widest boxes at the top edge of the graph are where the CPU really was, and they are the first suspects.
  • Total time includes callees. A wide box low in the stack is just a function that called something slow, so read upward to find what.

Look for the unexpected: a JSON.stringify taking 30 percent, a regex running on every request, a synchronous fs call, a serializer that runs on a hot path. Optimize the widest box first, then measure again. Changes that do not move the wide boxes do not matter.

The older tick profiler

Before --cpu-prof, the standard was V8’s tick profiler:

node --prof app.js
node --prof-process isolate-*.log

The first writes an isolate-*.log, and the second turns it into a text report. On my machine it did identify fib, at about 70 percent of ticks. It also listed a native entry that was clearly mislabeled, Http2Session::AddSettings for a block of C++ ticks, because resolving native symbols from the raw log is unreliable on macOS. That is a good reason to prefer --cpu-prof and a graphical viewer. Use --prof when you need low-level detail, and treat native names with suspicion.

Tools such as Clinic.js and 0x wrap these profilers and generate flame graphs for you. They are conveniences over the same sampling idea, and I did not run them for this lesson, so check their current maintenance status before adopting one.

What a CPU profile cannot show

If most of a request’s time is an awaited database query, the CPU is idle during it, and the profile shows nothing wide. For that case you need timing at the I/O boundary: log how long each outbound call takes, trace requests across services, and watch the database’s own slow-query data. Logging with Pino with a responseTime field is the cheapest start. Also remember that a Node process can be CPU-bound on native work that the JavaScript profile attributes to the calling function, such as hashing or compression.

What the video covers

The embedded talk is Matteo Collina’s “Next-Gen Flame Graphs: Making Node.js Performance Profiling Actually Work”, an October 2026 upload from the NodeConf EU channel. From its abstract, it argues that flame graph generation used to need kernel-level tools and awkward scripts, shows a zero-config flame run server.js workflow, and uses a service at 96 percent event-loop utilization as the motivating symptom. Collina chairs the Node.js Technical Steering Committee and works at Platformatic, which makes that tool, so it is partly a product talk. It does not walk through --cpu-prof, --prof or perf_hooks, which this lesson covers and which I ran on Node 26. The conference channel has 142 subscribers, and a transcript was not available, so I’m describing the talk from its abstract.

Where this fits

Profiling finds slow code. The other production failure with a measuring tool of its own is a process that grows until it dies, which is memory leaks and heap snapshots.

Check yourself

  1. 01Requests are slow but CPU use on the host is low. Which tool do you reach for, a CPU profile or something else?

    Something else. If the process is mostly idle, the time is spent waiting on a database, another service or a lock, and a CPU profile only samples running JavaScript, so it will show nothing useful. Check event-loop utilization to confirm the loop is idle, then use request timings, tracing and database metrics to find the slow dependency.

  2. 02What does it mean when `monitorEventLoopDelay` reports a p99 of 130 ms on a server you expect to answer in 5 ms?

    Something is running synchronously for over 100 ms, so every other request waits behind it. The loop cannot service timers or I/O callbacks while JavaScript is executing. Take a CPU profile and look for the wide function, such as a big JSON parse, a loop, a synchronous crypto or file call, or a catastrophic regex.

  3. 03How do you read a flame graph?

    Each box is a function, its width is the share of samples where it was on the stack, and boxes below it are its callers. The wide boxes at the top edge, where the CPU actually was, have the highest self time and are the first suspects. The stack beneath tells you which request path led to them.

  4. 04Why take profiles in production-like conditions rather than on an idle laptop?

    Hot paths depend on real data sizes, concurrency and warmed-up code. A function that is trivial on a ten-row fixture can dominate with ten thousand rows. Profile under a realistic load, such as a load test, or a short sampling window on a live instance, so the numbers reflect the traffic that matters.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark