Course contentsShow
← Node.js
Lesson 1452 of 1,98013. Error Handling and Resilient SystemsFree lesson

Monitoring Event Loop Lag

You will track event loop delay and alert when the application can no longer process its queue in a timely manner.

In this lesson, you will learn how to monitor the Node.js event loop to detect when your application becomes "blocked" and unable to process incoming requests efficiently.

The Event Loop as a Bottleneck

In Node.js, the event loop handles all your I/O operations and callback execution. If a piece of code takes too long to run—like a heavy calculation or synchronous data processing—the loop cannot move to the next task. This delay is known as "Event Loop Lag." If your lag exceeds a few hundred milliseconds, your service will struggle to respond to health checks or handle incoming traffic, eventually leading to timeouts.

Implementing a Monitor

To detect this, we use the perf_hooks module. We set up a timer that checks the difference between when a task was scheduled to run and when it actually executed.

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

// Create a histogram with a 100ms resolution
const h = monitorEventLoopDelay({ resolution: 100 });
h.enable();

setInterval(() => {
  // Check the 99th percentile of lag in milliseconds
  const p99 = h.percentile(99) / 1000000; // Convert nanoseconds to ms
  
  if (p99 > 500) {
    console.error(`Alert: Event loop lag high: ${p99.toFixed(2)}ms`);
    // Here, you might trigger your "Graceful Degradation" strategy 
    // to stop accepting new work or shed load.
  }
  
  h.reset(); // Clear stats for the next interval
}, 5000);

Why This Matters for Resiliency

Monitoring lag is critical because it acts as an early warning system. By detecting high lag, you can proactively trigger Graceful Degradation or signal your Circuit Breakers to stop calling downstream services. If the event loop is already struggling, continuing to accept new requests will only exacerbate the issue, potentially crashing the process. Instead, an overloaded instance should signal that it is "unhealthy" to your load balancer so traffic can be diverted to healthier nodes.

Key Takeaway: Event Loop Lag is a leading indicator of system exhaustion; tracking it allows you to shed load before your service becomes completely unresponsive.