How-To Guide

How to Detect Event Loop Starvation

Measure event loop lag and per-phase time to find the synchronous code that starves I/O, and fix latency spikes that come from your own process.

On this page

  1. Introduction
  2. What Starvation Looks Like
  3. Measuring Event Loop Lag
  4. Finding the Blocking Code
  5. Common Causes
  6. Fixing and Preventing Starvation
  7. Distinguishing Loop Lag from Other Latency
  8. Common Pitfalls and Conclusion

Introduction

Latency that spikes without a slow dependency is usually your own event loop, blocked by a synchronous task that never yields. Because the loop runs one task at a time, a long JSON parse, a heavy regular expression, a large sort or a synchronous filesystem call freezes every timer, socket and promise until it returns. Detection is straightforward once you measure the right signal: event loop lag tells you when the loop is starved, and per-phase timings and profiling tell you which task is doing the starving.

What Starvation Looks Like

Under starvation, throughput may be fine on average while a fraction of requests see very high latency, because they happened to arrive while a long task held the loop. The distribution is bimodal: most requests fast, some extremely slow, with no corresponding downstream slow span. CPU may be high or only moderate, depending on whether the task is compute-bound or waiting.

The signature is that the slow requests do not share a slow dependency. If your traces show hundreds of requests waiting at the same instant and the waiting is before any downstream call, the loop was blocked at that instant, and you are looking for the task that ran then.

Measuring Event Loop Lag

Event loop lag is the delay between when a timer was scheduled to fire and when it actually fired. If the loop is free, a fifty-millisecond timer fires at fifty milliseconds; if a task blocked the loop for two hundred milliseconds, it fires two hundred milliseconds late. Sampling this delay gives a direct measure of starvation.

Export lag as a histogram and watch its high percentiles, not its average. A p99 of two hundred milliseconds means one percent of the time the loop is blocked for a fifth of a second, which is enough to break latency SLOs. Monitor p50, p99 and the maximum, because a rare very long block is worse than a common short one.

import { monitorEventLoopDelay } from 'node:perf_hooks';

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

setInterval(() => {
  const stats = {
    meanMs: (h.mean / 1e6).toFixed(1),
    p99Ms: (h.percentile(99) / 1e6).toFixed(1),
    maxMs: (h.max / 1e6).toFixed(1),
  };
  console.log('event_loop_lag', stats);
  h.reset();
}, 10_000);

Finding the Blocking Code

Once lag confirms starvation, you need to find the task. Per-phase timing, available in some diagnostics, shows whether time is spent in the timer phase, the poll phase or in user callbacks. A CPU profile taken during the spike shows which functions ran while the loop was blocked, because the profile samples the stack while the loop is stuck in that function.

A quick manual technique is to add a wrapper that times suspect synchronous functions and logs any that exceed a threshold. In a single-threaded runtime, the wall-clock duration of a synchronous function is exactly the time the loop is blocked, so a threshold-based timer on those calls catches the offenders directly.

function timeSync(name, fn) {
  const start = process.hrtime.bigint();
  try {
    return fn();
  } finally {
    const ms = Number(process.hrtime.bigint() - start) / 1e6;
    if (ms > 50) console.warn('blocked_loop', { fn: name, ms: ms.toFixed(1) });
  }
}

// wrap suspected offenders
const parsed = timeSync('parsePayload', () => JSON.parse(payload));
const matched = timeSync('regexScan', () => heavyRegex.test(text));

Common Causes

Large JSON.parse and JSON.stringify calls on megabyte payloads block the loop for tens of milliseconds each. Catastrophic backtracking regular expressions on user input can block for seconds. Synchronous filesystem calls such as readFileSync in a request path block for the duration of disk I/O. Sorting or filtering very large arrays blocks proportionally to their size.

Less obvious causes include synchronous crypto on large buffers, template engines rendering huge strings, deep recursion, and libraries that do work eagerly on import or on the first call. When lag spikes align with a particular endpoint or a particular job, the cause is usually in that path even if the library is third-party.

# frequent starvation sources
JSON.parse/stringify  on MB-scale payloads   -> stream or parse smaller
regex                 catastrophic backtrack  -> bound input; use RE2
fs.*Sync              in request paths        -> use async fs
Array.sort/filter     on very large arrays    -> chunk or offload
crypto                on large buffers        -> offload to worker
module init / imports eager work at startup   -> lazy load

Fixing and Preventing Starvation

For sliceable work, chunk it and yield with setImmediate between slices, as covered in cooperative scheduling. For atomic heavy work, offload it to a worker thread or a child process. For synchronous I/O, switch to the async API. For regex, bound the input length and prefer a linear-time engine. For large serialisation, stream it instead of building one giant string.

Prevent regressions by keeping lag on the dashboard and alerting on sustained p99 lag. Add a test that measures lag while exercising heavy endpoints, so a new synchronous dependency or an accidentally quadratic loop is caught before deploy. The metric and the test together keep the loop honest.

# mitigation by cause
sliceable sync work   -> chunk + await setImmediate()
atomic sync work      -> move to worker_threads / child_process
fs in request path    -> use async fs promises
unbounded regex       -> cap input length; linear-time engine
huge serialisation    -> stream encode instead of one big string
# guardrail: keep event loop lag p99 on the dashboard + a lag test in CI

Distinguishing Loop Lag from Other Latency

Before you blame the loop, rule out the alternatives. A slow dependency shows as a slow downstream span; loop starvation shows as waiting before any downstream call. CPU saturation from too many concurrent requests shows as uniformly high CPU and moderate lag; a single blocking task shows as spiky lag and CPU that is not necessarily saturated.

Per-request traces are the discriminator: if the queueing delay is inside your process before the first child span, it is loop lag. If it is inside a child span, it is that dependency. Measure both, so you always know which one you are looking at and do not chase the wrong layer.

# triage
gap before first child span, all requests at once  -> event loop blocked
one child span much longer than others             -> that dependency slow
lag high AND cpu ~ 100% everywhere                 -> overload, shed load
lag spiky, cpu moderate                            -> single blocking task

Common Pitfalls and Conclusion

Do not measure lag with a single setInterval that itself may be delayed and then treat that as the measurement; use the built-in monitor that samples the loop’s own delay. Do not watch only the average, which hides the p99 spikes that break SLOs. Do not assume a third-party library is async just because it returns a promise; it may do synchronous work before resolving. And do not offload everything to workers reflexively; offload only the atomic heavy work.

Event loop starvation is a self-inflicted latency source that is invisible in dependency metrics and obvious in loop lag. Measure lag as a histogram, find the blocking task with a profile or a timing wrapper, fix it by chunking, offloading, or switching to async I/O, and guard against regressions with alerting and a lag test. Then the loop stops being the silent cause of your p99 spikes.

Sources: Node.js: monitorEventLoopDelay, Node.js: Don’t block the event loop, Node.js: Diagnostics and flame graphs.

FAQ

What is event loop lag in one sentence?
It is the delay between when a timer was scheduled to fire and when it actually fired, which directly measures how long a synchronous task has blocked the loop.
How do I tell loop lag apart from a slow dependency?
Look at the trace: if every slow request shows queueing before the first child span, the loop was blocked. If the time is inside a child span, that dependency is slow. Measuring the gap before the first span is the discriminator.

Related Examples