Home > OS >  Improve NodeJS performance running on PM2 clusters
Improve NodeJS performance running on PM2 clusters

Time:09-17

I'm running a clustered nodejs production API using PM2 and I have concerns about performance. I've read through the PM2 docs but I'm not seeing much about performance optimization.

Do either PM2 or Node have default limitations? If so, what can I do to ensure that my API is running at its fullest potential?

My web server has 4 Processors, 12 GB of RAM, and exists solely for this API.

PM2 script

module.exports = {
    apps: [{
        name: "myAppsName",
        script: "src/server.js",
        exec_mode: "cluster",
        instances: "max",
        autorestart: true,
        watch: false
      }]
};

CodePudding user response:

You are probably in good shape performance-wise. You didn't say anything about your performance concerns, so here's a general answer.

You have set up your pm2 cluster mode configuration with instances: "max". That means pm2 will figure out the number of processor cores on your machine and create an appropriate number of clustered nodejs processes for you. So it's making good use of your four core machine. And, if you need to scale it up, you can move it to a machine with more cores.

You didn't describe your web service, so it's hard to guess how much RAM each process in your cluster will need. Unless your nodejs program uses enormous in-memory data structures, you probably can use the nodejs default heap size. It's around 1.5GiB per process, so a total of 2GiB of physical RAM for each process is plenty. You have 12GiB and you need 8GiB.

In the extrememly unlikely situation where you need more RAM in each nodejs process, you can increase it. Look up --max_old_space_size to learn how to do that.

The more files you can serve with express.static(), the better your overall web app performance will be.

If you reverse-proxy your nodejs cluster through nginx, you'll offload the handling of https to the nginx process, freeing up compute cycles for your web server application.

You may have a performance bottleneck somewhere in a database server. It's a fairly common problem in web applications as they scale up. You'll have to figure that out.

If your nodejs app does compute-intensive work, you should investigate using worker threads to do those computations. In that case you should reduce instances: to half the number of cores on your machine, to leave cores for the worker threads to use.

  • Related