aarosil
aarosil

Reputation: 4898

How to find source of memory leak in Node.JS App

I have a memory leak in Node.js/Express app. The app dies after 3-5 days with the following log message:

FATAL ERROR: JS Allocation failed - process out of memory

I setup a server without users connecting, and it still crashes, so I know leak is originating in the following code which runs in the background to sync api changes to the db.

poll(config.refreshInterval)

function poll(refreshRate) {
    return apiSync.syncDatabase()
        .then(function(){
            return wait(refreshRate)
        })
        .then(function(){
            return poll(refreshRate)
        })          
}

var wait = function wait(time) {
    return new Promise(function(resolve){
        applog.info('waiting for %s ms..', time)
        setTimeout(function(){
            resolve(true)
        },time)
    })
}

What techniques are available for profiling the heap to find the source object(s) of what is taking all the memory?

This takes awhile to crash, so I would need something that logs and I can come back later and analyze.

Is there any option like Java's JVM flag -XX:HeapDumpOnOutOfMemoryError ?

Upvotes: 2

Views: 264

Answers (1)

celeritas
celeritas

Reputation: 2281

Check out node-memwatch.

It provides a heap diff class:

var hd = new memwatch.HeapDiff();
// your code here ...
var diff = hd.end();

It also has event emitters for leaks:

memwatch.on('leak', function(info) {
// look at info to find out about what might be leaking
});

Upvotes: 1

Related Questions