Course contentsShow
← Node.js
Lesson 1686 of 1,98015. Logging, Observability, and MetricsFree lesson

Tracking Event Loop Delay

Use metrics to quantify the impact of CPU-intensive tasks on the responsiveness of the event loop.

In this lesson, you will learn how to measure event loop delay to quantify how much your CPU-intensive tasks are degrading the responsiveness of your Node.js application.

The Problem: Event Loop Blockage

Because Node.js runs on a single thread, the event loop must process all incoming I/O, timers, and callbacks. If you perform a heavy computation—such as parsing a massive JSON object or encrypting a large file—the event loop is "blocked." During this time, the process cannot handle new requests or trigger setTimeout callbacks. This latency, known as event loop delay, is a critical indicator of your server’s actual health under load.

Measuring Latency

To quantify this, we look at the difference between the time a timer was scheduled to run and the time it actually executed. If a timer is set for 10ms but executes at 50ms, you have an event loop delay of 40ms.

We can track this using the built-in perf_hooks module, which provides a high-resolution observer for event loop utilization.

const { monitorEventLoopDelay } = require('perf_hooks');

// Initialize the monitor with a 100ms resolution
const h = monitorEventLoopDelay({ resolution: 100 });
h.enable();

// Periodically check the delay
setInterval(() => {
  console.log(`Mean delay: ${h.mean / 1e6}ms`);
  console.log(`Max delay: ${h.max / 1e6}ms`);
  
  // Reset the histogram for the next interval
  h.reset();
}, 5000);

Why This Matters

When you monitor logs or centralized error reports, you might see "request timeouts" without knowing the root cause. By tracking event loop delay, you can correlate spikes in latency with specific CPU-heavy operations. If your max delay regularly exceeds 100ms, your users will experience perceptible sluggishness, regardless of how fast your database queries are. This metric provides the "ground truth" of your process performance, allowing you to proactively offload heavy tasks to worker threads before they impact your service availability.

Key Takeaway: Event loop delay is the most accurate barometer of your application’s responsiveness, revealing exactly how much your synchronous work is starving the event loop of the time it needs to serve your users.