Tag Archives: performance

Nodejs memory leak detector

Just wrote a simple module to tracking down memory leaks.

Create a standalone module

cat menoryUsageInfo.js

/**
 * Memoryusage info detections.
 * @author Allex Wang (allex.wxn@gmail.com)
 */
module.exports = function() {
  // output memory usage info every 2 minutes
  var min = 0, last = 0, interval = 2 * 1000
  var pid = process.pid
  process.nextTick(function f() {
    var o = process.memoryUsage()
    var percent = ~~((o.heapUsed / o.heapTotal) * 100) + '%'
    if (!min || o.heapUsed < last) {
      min = o.heapUsed
      console.warn([pid, (min / 1048576) + 'M' + '/' + (o.heapTotal / 1048576) + 'M', percent])
    }
    last = o.heapUsed
    setTimeout(f, interval)
  })
}

Create a simple web server for memory leak detections

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(7070, '127.0.0.1');

console.log('Server running at http://127.0.0.1:7070/. Process PID: ', process.pid);

require('./menoryUsageInfo')();

If we hit this continuously with

while true; do curl -s http://127.0.0.1:7070/; done

in one shell, and in another shell view our process: top -pid <process pid> we will see very high and erratic memory usage for this node process.

For more details about memory detections there are two awesome node modules – memwatch and heapdump.

Reference Urls