Clustering in Node.js is a technique used to create multiple instances of a Node.js application that can run on different CPU cores. This is important because Node.js runs in a single thread by default, meaning it can only utilize one CPU core—even on multi-core systems.
๐ง Why Clustering Is Used
-
To improve performance and scalability on multi-core machines.
-
To handle more concurrent requests by distributing load.
-
To provide basic fault tolerance—if one worker crashes, others continue running.
-
To avoid blocking the event loop with heavy traffic.
๐ง How It Works
-
Uses the built-in
cluster
module. -
The master process spawns worker processes (child processes).
-
Each worker runs its own event loop and can handle requests independently.
-
Workers can share server ports (e.g.,
http.createServer
) via the master process.
๐งช Example
⚠️ Notes
-
Workers do not share memory; they run in separate processes.
-
Use inter-process communication (IPC) or tools like Redis for shared data/state.