CodePark/ questions / Performance & memory leaks
START PRACTICINGPRACTICE
Backend question · Node.js › Performance & memory leaks

What is event loop lag (delay), why does it matter, and how can you measure it?

const { monitorEventLoopDelay } = require("node:perf_hooks");
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => {
  console.log("p99 ms", h.percentile(99) / 1e6);
  h.reset();
}, 10_000);

Event loop lag is how long a callback waits after the time it should have run. It waits because the loop was busy with other synchronous work. Example: a timer is set for 10 ms but fires after 200 ms. So the loop was blocked for about 190 ms, and every request in that time waited too.

It is one of the best health signals for a Node service. High CPU with low lag is fine. But rising lag means users see slow responses, even when the database is fast.

How to measure it:

  • perf_hooks.monitorEventLoopDelay() returns a histogram with mean, max and percentile() values. Send the p99 (the 99th percentile: the delay that only 1% of samples exceed) to your metrics.
  • performance.eventLoopUtilization() shows how much of the time the loop was busy.
  • Event loop lag is the delay between when a callback should run and when it actually runs.
  • Synchronous work that blocks the loop causes it.
  • Lag adds directly to the response time of every request.
  • Measure it with the monitorEventLoopDelay histogram and track the p99.
  • Use eventLoopUtilization to see how much of the time the loop is busy.