Node.js runs on a single thread by default. Here's how to utilize all CPU cores with clustering.
Basic Cluster Setup#
Express with Clustering#
Graceful Shutdown#
Zero-Downtime Restart#
Shared State with IPC#
Sticky Sessions#
PM2 Alternative#
Load Testing#
Best Practices#
Scaling:
✓ Match workers to CPU cores
✓ Implement graceful shutdown
✓ Handle worker crashes
✓ Use zero-downtime restarts
State:
✓ Keep workers stateless
✓ Use external storage (Redis)
✓ IPC for coordination only
✓ Avoid shared mutable state
Monitoring:
✓ Track per-worker metrics
✓ Monitor memory usage
✓ Log worker lifecycle events
✓ Set up health checks
Production:
✓ Consider PM2 or similar
✓ Use process managers
✓ Configure restart limits
✓ Set memory limits
Conclusion#
Clustering scales Node.js across all CPU cores. Implement graceful shutdown for production reliability, use IPC sparingly for coordination, and keep workers stateless. For production, consider PM2 or Kubernetes for advanced orchestration. Always test with load to verify scaling benefits.