Get your own Node server
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isPrimary) {
  console.log(`Primary ${process.pid} is running`);

  // Fork initial workers
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  // Store worker refs
  let workers = Object.values(cluster.workers);

  // Restart one worker at a time
  function restartWorker(workerIndex) {
    const worker = workers[workerIndex];
    console.log(`Restarting worker #${worker.id}`);

    // Create a new worker
    const newWorker = cluster.fork();
    
    // Add the new worker to our array
    workers.push(newWorker);
    
    // When the new worker is online, disconnect the old worker
    newWorker.on('online', () => {
      if (worker) {
        console.log(`New worker #${newWorker.id} is online, disconnecting old worker #${worker.id}`);
        worker.disconnect();
      }
    });

    // When the old worker is disconnected, remove it from the array
    worker.on('disconnect', () => {
      console.log(`Worker #${worker.id} disconnected`);
      workers = workers.filter(w => w.id !== worker.id);
    });

    // Continue the process if there are more workers to restart
    if (workerIndex + 1 < workers.length) {
      setTimeout(() => {
        restartWorker(workerIndex + 1);
      }, 5000);
    }
  }

  // Example: trigger a rolling restart after 15 seconds
  setTimeout(() => {
    console.log('Starting rolling restart of workers...');
    restartWorker(0);
  }, 15000);

  // Additional event handlers
  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} exited with code ${code}`);
  });

} else {
  // Worker process
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Hello from worker ${process.pid}, started at ${new Date().toISOString()}\n`);
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}

              
Primary 17720 is running
Worker 2612 started
Worker 22888 started
Worker 23344 started
Worker 31488 started
Worker 16528 started
Worker 28832 started
Worker 6716 started
Worker 24340 started
Worker 27560 started
Worker 32164 started
Worker 16208 started
Worker 11104 started
Worker 21324 started
Worker 24512 started
Worker 18420 started
Worker 23512 started
Starting rolling restart of workers...
Restarting worker #1
New worker #17 is online, disconnecting old worker #1
Worker #1 disconnected
Worker 18412 started
Worker 22888 exited with code 0
Restarting worker #3
New worker #18 is online, disconnecting old worker #3
Worker #3 disconnected
Worker 32756 started
Worker 2612 exited with code 0
Restarting worker #5
New worker #19 is online, disconnecting old worker #5
Worker #5 disconnected
Worker 31488 exited with code 0
Worker 4116 started