How to use Node.js clustering for performance
· Category: Node.js
Short answer
The cluster module allows you to fork multiple worker processes that share the same server port, utilizing all CPU cores.
Steps
- Import cluster and os:
const cluster = require('cluster'); const os = require('os');. - In the master process, fork workers:
for (let i = 0; i < os.cpus().length; i++) cluster.fork();. - In the worker process, start your HTTP server normally.
- Handle worker crashes by forking a replacement in the master.
- Alternatively, use PM2 which handles clustering automatically.
Tips
- Worker processes do not share memory; use Redis or a database for session state.
- Zero-downtime deployments require orchestrating worker restarts gracefully.
Common issues
- Debugging clustered apps is harder because logs are interleaved from multiple processes.
- Improper signal handling during shutdown can leave connections dangling.