Course contentsShow
← Node.js
Lesson 75 of 1,9801. Node.js Foundations and Runtime InternalsFree lesson

System-Level Monitoring Metrics

Correlate Node.js event loop health with system-level metrics like CPU and memory usage.

In this lesson, you will learn how to connect the "health" of your Node.js event loop to the broader system-level metrics of the host machine.

The Pulse of Your Application

Think of your Node.js application as a restaurant kitchen. The event loop is the chef, and the system-level metrics (CPU usage and memory) are the environmental conditions of the kitchen. If the room temperature (CPU load) spikes or the workspace (RAM) becomes cluttered, the chef slows down, leading to "Event Loop Lag."

Correlating CPU and Loop Lag

The event loop is single-threaded. When the system CPU usage is pinned at 100%, the OS struggles to grant the Node.js process the time slices it needs. You can detect this by monitoring the delay between when a timer was scheduled and when it actually executed.

If you see CPU usage climbing while your event loop lag increases, your application is likely "CPU-bound." You aren't just waiting for I/O; you are literally starving the event loop of processing time.

const start = process.hrtime();

// If the event loop is healthy, this runs almost immediately.
// If CPU is saturated, this will be delayed.
setImmediate(() => {
  const delta = process.hrtime(start);
  const nanoseconds = delta[0] * 1e9 + delta[1];
  console.log(`Event loop lag: ${nanoseconds / 1e6}ms`);
});

Memory and Garbage Collection (GC)

System memory usage is another critical indicator. As your memory footprint grows, the V8 engine triggers the Garbage Collector more frequently. Frequent GC cycles "stop the world"—they pause your application code to reclaim memory.

If your system memory usage is consistently near your max-old-space-size limit, the event loop will stutter because the engine is constantly thrashing to find free memory. By tracking system RSS (Resident Set Size) alongside event loop lag, you can distinguish between a slow application due to heavy logic versus a slow application due to excessive object allocation causing constant GC pressure.

Key Takeaway: Monitoring event loop lag provides a window into your application’s performance, but correlating it with system CPU and memory metrics is the only way to determine if the bottleneck is your code's complexity or the host machine's capacity.