express: Memory Leak

We’ve been experiencing a memory leak in our node servers. Over the course of a day or so the memory in our servers started to fill until we got an alert and had to restart the app. We added new relic to check the node VM memory:

image

Upon debugging and testing we’ve come to the conclusion that the leak could be in express. We did some test on a clean express server, printing the heap before and after a lot of request and we see the memory increasing but never going back to the initial value.

We tested on various versions of Node and two versions of express (4.16.2 and 4.14.1) and we had the same results.

I’ll add the last test setup so you can reproduce it.

Tested on OSX 10.12.6 Node 7.6.0 Express 4.16.1

Code

var express = require('express');

var app = express();

app.get('/', function(req, res) {
  res.status(200).send('asdf');
  res.end();
});

function generateHeapDumpAndStats() {
  //1. Force garbage collection every time this function is called
  try {
    global.gc();
  } catch (e) {
    console.log("You must run program with 'node --expose-gc'");
    process.exit();
  }

  //2. Output Heap stats
  var heapUsed = process.memoryUsage().heapUsed;
  console.log('Program is using ' + heapUsed + ' bytes of Heap.');
}

const PORT = process.env.PORT || 9000;

app.listen(PORT, function() {
  console.log(`App listening on port ${PORT}!`);
});

setInterval(generateHeapDumpAndStats, 3000);

run with node --expose-gc server.js

autocannon command autocannon -a100000 -c5 http://localhost:9000/

Results:

screen shot 2018-02-05 at 17 54 44

This is just one of the many test we made, all with similar results

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 59 (25 by maintainers)

Most upvoted comments

@nickydonna I am very curious what the end of the story was? Were you able to fix it? It’s two years later but I am also seeing a similar thing in one production app…