Node.js › Event Loop & Non-blocking IO
How would you measure how 'busy' the event loop is in a running Node.js process using a simple technique?
IntermediateAnswer
A basic technique schedules a callback with a known delay (like setImmediate or a short setTimeout) and measures the actual elapsed time versus the expected delay -- if the event loop is busy processing other work, the callback fires later than scheduled, and that measured difference (the 'lag') serves as a rough real-time indicator of how backed up or blocked the event loop currently is, forming the basis of tools like the 'toobusy' or 'blocked-at' packages.
function measureLoopLag(callback) {
const start = process.hrtime.bigint();
setImmediate(() => {
const lagNs = process.hrtime.bigint() - start;
callback(Number(lagNs) / 1e6); // lag in milliseconds
});
}
measureLoopLag((lagMs) => console.log('Event loop lag:', lagMs, 'ms'));Real-world example A health-check endpoint includes a quick event-loop-lag measurement, returning an unhealthy status if the lag exceeds a threshold, letting a load balancer or orchestrator temporarily route traffic away from an instance that's become overloaded and unresponsive.