How to detect and measure event loop blocking in node.js?

Fabian Jakobs picture Fabian Jakobs · Feb 17, 2015 · Viewed 11.2k times · Source

I'd like to monitor how long each run of the event loop in node.js takes. However I'm uncertain about the best way to measure this. The best way I could come up with looks like this:

var interval = 500;
var interval = setInterval(function() {
    var last = Date.now();        
    setImmediate(function() {
        var delta = Date.now() - last;
        if (delta > blockDelta) {
            report("node.eventloop_blocked", delta);
        }
    });
}, interval);

I basically infer the event loop run time by looking at the delay of a setInterval. I've seen the same approach in the blocked node module but it feels inaccurate and heavy. Is there a better way to get to this information?

Update: Changed the code to use setImmediate as done by hapi.js.

Answer

YoungJohn picture YoungJohn · Apr 7, 2016

"Is there a better way to get this information?" I don't have a better way to test the eventloop than checking the time delay of SetImmediate, but you can get better precision using node's high resolution timer instead of Date.now()

var interval = 500;
var interval = setInterval(function() {
    var last = process.hrtime();          // replace Date.now()        
    setImmediate(function() {
        var delta = process.hrtime(last); // with process.hrtime()
        if (delta > blockDelta) {
            report("node.eventloop_blocked", delta);
        }
    });
}, interval);

NOTE: delta will be a tuple Array [seconds, nanoseconds].

For more details on process.hrtime(): https://nodejs.org/api/all.html#all_process_hrtime

"The primary use is for measuring performance between intervals."