skip to content

In Node.js, what do perf_hooks.monitorEventLoopDelay() and performance.eventLoopUtilization() each measure, and how do you read them to spot a blocked loop?

level: middleimportance: should knowfreq 45%

answer

  1. late versus busy
  2. histogram in nanoseconds
  3. enable, export, reset
  4. time outside the event provider

basics

~20 s

monitorEventLoopDelay() records, in nanoseconds, how long the loop takes to reach a sampling timer, so a max or p99 spike exposes one long callback. eventLoopUtilization() reports the share of time the loop is busy rather than waiting for I/O.

solid answer

~40 s

`monitorEventLoopDelay({ resolution })` returns an `ELDHistogram` that, once `enable()`d, samples with a timer every `resolution` ms (10 by default) and records how late the loop gets to it, in **nanoseconds**. A spike in `max` or `percentile(99)` is the fingerprint of one long callback, because every request that arrived meanwhile waited that long. `performance.eventLoopUtilization()` returns `{ idle, active, utilization }`: the share of time the loop spent outside the event provider's wait, which is not CPU usage. Read together: spiky delay with modest utilization means an occasional blocking callback to find and fix; flat delay with utilization near 1 means many short callbacks, so add capacity. Export both per window, `reset()` the histogram after each export, and alert on per-instance p99 and max rather than averages.

code

javascript · 17 lines
javascript
import { monitorEventLoopDelay, performance } from 'node:perf_hooks';

const delay = monitorEventLoopDelay({ resolution: 20 });
delay.enable();
let previous = performance.eventLoopUtilization();

setInterval(() => {
  const current = performance.eventLoopUtilization();
  const elu = performance.eventLoopUtilization(current, previous);
  previous = current;
  console.log({
    p99Ms: delay.percentile(99) / 1e6,
    maxMs: delay.max / 1e6,
    utilization: Number(elu.utilization.toFixed(2)),
  });
  delay.reset();
}, 10_000).unref();

go deeper

for a junior

Recall that perf_hooks has one API for how late the loop is and one for how busy it is, and that the delay histogram reports nanoseconds.

for a middle

Explain how the histogram samples, why max and p99 matter more than the mean, and how utilization is defined relative to the event provider's wait.

for a senior

Show how you would export, reset and alert on both per instance, and how the pair separates a blocking bug from plain saturation during an incident.

for a principal

Decide which loop-health signals become fleet SLOs and alerts, and how they feed capacity and scaling decisions across services.

## Two questions, two instruments "Is the event loop blocked?" is really two questions. **How long does the loop take to come back** when something is waiting for it? And **how much of its time is the loop busy** at all? Node answers each with its own API in `node:perf_hooks`, and reading one as if it were the other is the usual mistake. ## `monitorEventLoopDelay()`: how late the loop is `perf_hooks.monitorEventLoopDelay([options])` returns an **`ELDHistogram`**. By default it samples with a timer every `resolution` milliseconds (default `10`) and records how long the loop took to get to it. When a callback holds the main thread for 300 ms, the sample taken across that stretch records a delay of roughly 300 ms. Key facts: - values are in **nanoseconds**, so divide by `1e6` for milliseconds; - nothing is recorded until you call **`histogram.enable()`**; `disable()` stops sampling; - the histogram exposes `min`, `max`, `mean`, `stddev`, `percentile(n)` and `percentiles`; - it **accumulates** from `enable()` on, so call **`reset()`** after each export or an old stall stays in `max` forever. Choosing `resolution` is a tradeoff: a smaller value samples more often and catches shorter stalls, at the cost of waking the loop more often; 10 to 20 ms suits most services. Loop delay is a **tail-latency** signal. Every request that arrived during a 300 ms block waited up to 300 ms before Node even looked at it, so a spike in `max` or `percentile(99)` is the direct fingerprint of one long callback. The mean is nearly useless here: one 2-second stall averaged with thousands of fast samples disappears. ## `eventLoopUtilization()`: how busy the loop is `performance.eventLoopUtilization()` returns `{ idle, active, utilization }`. `idle` and `active` are cumulative milliseconds; `utilization` is the ratio between 0 and 1. The docs define it as the share of time the loop has spent **outside the event provider** (for example `epoll_wait`), the point where it sleeps waiting for I/O. Pass a previous result to get the delta since then, or pass two results to get the delta between them. ELU is **not CPU usage**. The Node docs show a script that calls `child_process.spawnSync('sleep', ['5'])`: the CPU is idle, yet `utilization` is `1`, because the main thread is stuck in a synchronous call and never returns to waiting for events. That makes ELU the better saturation signal for a Node process than a CPU graph. ## Reading them together | Loop delay (p99/max) | ELU | What it usually means | |---|---|---| | low | low | healthy, spare capacity | | low | high | many short callbacks; busy but fair, so add capacity | | spiky | moderate | an occasional long callback; find and fix it | | high | near 1 | saturated and blocking; both problems at once | A spiky delay with modest ELU is the classic blocking bug: a large `JSON.parse`, a `*Sync` call or a backtracking regex on one route. High ELU with flat delay is plain load: each callback is short, the loop is just never idle, and the answer is more instances, not code surgery. Neither number says **which** code blocked. They tell you **that** the loop was held and **when**; a CPU profile or a request log lined up with the spike tells you **what**. ## Using them in production 1. Create one histogram at startup with a resolution like 10-20 ms, `enable()` it, and export `percentile(99)` and `max` per window, then `reset()`. 2. Export ELU as a delta per window by keeping the previous result. 3. Compare readings against a baseline from a healthy instance rather than against zero. 4. Alert on p99 and max delay per instance, not on fleet averages, because one blocked process hides inside a healthy average. 5. When a spike appears, correlate it with the route and payload size in your request logs, then confirm with a CPU profile (`node --cpu-prof`). Inside `worker_threads`, each worker has its own loop: from the parent, `worker.performance.eventLoopUtilization()` reports that worker's ELU, so you can see whether offloaded work is saturating a worker instead of the main thread.

  • Why reset the delay histogram after each export?
    The `ELDHistogram` accumulates from `enable()` onwards. Without `reset()`, a single 3-second stall from hours ago stays in `max` indefinitely, and long-run percentiles bury a fresh regression. Resetting per window turns it into per-interval p99 and max values you can graph and alert on.
  • Can event loop utilization be 1 while the CPU is idle?
    Yes. ELU counts time spent outside the event provider's wait, not CPU work. The Node docs show `child_process.spawnSync('sleep', ['5'])` producing a `utilization` of 1 while the CPU idles, because the main thread is stuck in a synchronous call. That is why ELU says more about a Node process's capacity than CPU percentage does.
  • How do you see whether a worker thread's own loop is saturated?
    From the parent, `worker.performance.eventLoopUtilization()` returns the same `{ idle, active, utilization }` object for that worker's loop. Each `worker_threads.Worker` has its own event loop, so a pool can be saturated while the main thread looks healthy.

  • Reads monitorEventLoopDelay values as milliseconds instead of nanoseconds.
  • Thinks the histogram records samples before enable() is called.
  • Treats event loop utilization as the same number as process CPU percentage.
  • Trusts a low mean loop delay as proof that no request was blocked.
  • Assumes high utilization always means a blocking bug rather than plain load.