NodeJS - Print stack trace when stuck/frozen

Viewed 505

Is it possible to print the stack trace of a nodejs app when it is becoming very slow or froze to get information about performance spikes?

This would be incredibly helpful in instances where the reproduction for the issue is unknown.

In Java this saved hundreds of hours and was straight forward:

  1. spawn a new "watchdog" thread
  2. send a heartbeat every 50ms from the main thread to the watchdog
  3. if the "watchdog" doesn't receive a heartbeat for +200ms, log the main threads stacktrace

Is something like this possible with nodejs?

FI: the nodejs diagnostics report doesn't contain any javascript stack trace when initiated from a sig kill event.

1 Answers

You are looking for checking if event loop is blocked or slow. There is a npm package https://www.npmjs.com/package/blocked-at that detects slow synchronous execution and report where it started.

Usage:

const blocked = require('blocked-at');

blocked((time, stack) => {
  console.log(`Blocked for ${time}ms, operation started here:`, stack)
});

from scratch you can implement yourself a check in this way:

var interval = 500;
var interval = setInterval(function() {
    var last = process.hrtime();       
    setImmediate(function() {
        var delta = process.hrtime(last);
        if (delta > blockDelta) {
            console.log("node.eventloop_blocked", delta);
        }
    });
}, interval);

The idea is: if the timer doesn't fire after the expected time, this mean that event loop was blocked in some operation.

This snippet check if event loop is blocked for more than 500 ms. Isn't perfect, I'm suggest to use blocked-at for more robust control.

Related