Course contentsShow
← Node.js
Lesson 601 of 1,9806. Networking and HTTP FundamentalsFree lesson

Event Loop Monitoring and Alerting

Set up probes that trigger alerts when the event loop is blocked for longer than a threshold duration.

In this lesson, you will learn how to detect when your Node.js event loop is stalled, preventing your application from becoming unresponsive under heavy load.

The Problem: Event Loop Blockage

Node.js relies on a single-threaded event loop to process tasks. When you execute heavy synchronous code—like parsing a massive JSON object or running complex calculations—the event loop stops processing new incoming network requests. This creates "lag," where your HTTP server stops responding to clients entirely. Monitoring this is critical because, unlike CPU usage, a high event loop delay isn't always visible in standard system metrics.

Probing the Latency

To detect these stalls, we can use a "heartbeat" probe. We set a setInterval that fires frequently (e.g., every 100ms) to record the current time. If the loop is healthy, the interval callback should execute exactly as scheduled. If the loop is blocked, the callback will be delayed. By comparing the expected execution time to the actual execution time, we can calculate the "lag."

Here is a simplified way to implement a watchdog probe:

const THRESHOLD_MS = 200;
let lastTime = Date.now();

setInterval(() => {
  const now = Date.now();
  const delay = now - lastTime - 100; // 100 is our interval duration

  if (delay > THRESHOLD_MS) {
    console.error(`Alert: Event loop blocked for ${delay}ms!`);
    // Trigger your alerting system here (e.g., PagerDuty, email)
  }

  lastTime = now;
}, 100);

Setting Alerts

When the delay exceeds your THRESHOLD_MS, you are experiencing a blocking event. In a production environment, you shouldn't just log this to the console. Instead, you should integrate this with a monitoring tool. By firing an alert when this threshold is crossed, you gain visibility into code paths (like expensive regex operations or synchronous file system calls) that are degrading your server's performance. By tracking these spikes, you can pinpoint exactly which part of your network stack is causing latency issues before your users start seeing timeouts.

Key Takeaway: By measuring the delta between the expected and actual execution time of a periodic timer, you can proactively detect and alert on event loop starvation before it results in dropped network connections.