Cluster

Node.js's Cluster API allows you improve the performance of your Node.js applications by distributing incoming requests across multiple processes.

import cluster from 'node:cluster'
import http from 'node:http'
import os from 'node:os'

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`)

  for (let i = 0; i < os.cpus().length; i++) {
    cluster.fork()
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`)
    cluster.fork()
  })
} else {
  http.createServer((req, res) => {
    res.writeHead(200)
    res.end(`hello from ${process.pid}`)
  }).listen(3000)
  console.log(`Worker ${process.pid} started`)
}
The child processes aren't really listening to the same port. Incoming socket
connections to the master process are being delegated to the child
processes.