0

Currently, running my prod apps in cluster mode with pm2 to create multiple instances. But over time, I can see increase in memory usage. How to solve it as for ow I need to restart the app manually?

pm2 start app.js -i 0 -o "/dev/null"
devil
  • 19
  • 4

2 Answers2

0

You can either:

  • figure out where the memory leak in your app is and fix that, or
  • set the --max-memory-restart option to have pm2 restart instances of your app when they leak too much
AKX
  • 152,115
  • 15
  • 115
  • 172
0

I was facing the same issue. It's because pm2 has an issue with the memory leak.

Instead use nodejs cluster module.

const cluster = require('cluster')

require('events').EventEmitter.defaultMaxListeners = Infinity;
const OS = require('os');
process.env.UV_THREADPOOL_SIZE = OS.cpus().length


let app = express();


const numCPUs = parseInt(process.env.NO_OF_CPU || 1)

if(cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  // start server on port
  let appServer = app.listen(process.env.OUTBOUND_PORT, () => {
    console.log(`server listening on ${process.env.OUTBOUND_PORT} `);
  });
}
Ravi Ranjan
  • 84
  • 1
  • 3
  • @AKX the problem with --max-memory-restart is that the app will get restarted and you may lose the requests in the meantime your app gets started and accepting the requests again. And, in production, you can't risk starting your app frequently without saving the current image of the app – Ravi Ranjan Aug 17 '21 at 15:00
  • OP says they're using cluster mode. I'd imagine pm2 only kills the one process that's leaky in that case, and the rest can continue serving requests. On the second point, if your app really relies on process-local state, it's not production-worthy, IMO. – AKX Aug 17 '21 at 15:57