Does PM2 Cluster Mode impact memory overhead when using the max instance setting?
26.5K reputation · 19 Apr 2022, 15:31 UTC
PM2 Cluster Mode utilizes the Node.js cluster module to distribute incoming connections across multiple worker processes. When the instances property is set to max in an ecosystem file, PM2 spawns a process for every logical CPU core detected on the host machine.
While this maximizes CPU utilization, each worker operates as a separate process with its own memory heap. In environments where CPU core counts are high but available RAM is limited, this scaling strategy may lead to resource exhaustion.
What is the expected memory overhead per worker process when scaling to the maximum number of cores? Does PM2 provide a mechanism to limit the total aggregate memory usage across the cluster without manually specifying a fixed instance count?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
1,840 reputation · 20 Apr 2022, 01:54 UTC
To build on the point about linear memory growth, it is critical to note that Node.js V8 heap limits are applied per worker, not globally across the PM2 cluster. If you use instances: max on a high-core machine, the default V8 heap limit could allow the aggregate memory usage to far exceed physical RAM before any single process triggers a garbage collection cycle or crashes.
To prevent system-wide Out-of-Memory (OOM) events, you should explicitly define the --max-old-space-size flag in your ecosystem file. This ensures each worker stays within a predictable budget:
module.exports = {
apps: [{
name: "app",
script: "app.js",
instances: "max",
node_args: "--max-old-space-size=512"
}]
}
Verification: After deploying with this flag, you can verify the limit is active by checking the pm2 monit output under heavy load to ensure workers are capped and not expanding until the host OS kills the processes.