Cluster Module in Node.js

From the Node.js Core Modules cheat sheet ยท Utilities & Advanced ยท verified Jul 2026

Cluster Module

Scale Node.js apps across multiple CPU cores

javascript
const cluster = require('cluster')
const http = require('http')
const os = require('os')

if (cluster.isMaster) {
  const cpuCount = os.cpus().length
  
  console.log(\`Master \${process.pid} spawning \${cpuCount} workers\`)
  
  // Fork workers
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork()
  }
  
  cluster.on('exit', (worker, code, signal) => {
    console.log(\`Worker \${worker.process.pid} died\`)
    console.log('Starting new worker...')
    cluster.fork()
  })
} else {
  // Workers share server port
  http.createServer((req, res) => {
    res.writeHead(200)
    res.end(\`Worker \${process.pid} responded\\n\`)
  }).listen(8000)
  
  console.log(\`Worker \${process.pid} started\`)
}
๐ŸŸข Essential for production Node.js servers
๐Ÿ’ก Workers share server ports automatically
โšก Scales to all CPU cores for better performance
๐Ÿ“Œ Master process manages workers
โš ๏ธ Workers die independently, implement restart logic
๐Ÿ”— Related: pm2 for production process management
scalingperformance

Continue with Node.js Core Modules

Save the full cheat sheet or work through every related task.

More Node.js tasks

Back to the full Node.js Core Modules cheat sheet