Interview frequency: …
Short answer
Create child processes (Workers) that share the same server port and distribute incoming requests with Round-Robin scheduling.
Explanation
Because Node.js is single-threaded, a server with 16 cores uses only one core and wastes the other 15 unless multiple processes are started. The node:cluster module lets the primary process create child processes with cluster.fork(), pass the server socket to them, and balance the load across them. It can also restart a child process immediately if it crashes.
Code example
import cluster from "node:cluster";
import os from "node:os";
if (cluster.isPrimary) {
const cpus = os.cpus().length;
for (let i = 0; i < cpus; i++) cluster.fork();
} else {
// Ordinary server code
}Common mistakes
- Sharing memory directly between Worker processes without a distributed intermediary such as Redis or IPC messages.