Addresses Node.js’s single-process limitation in utilizing multi-core CPUs.
The master-worker (cluster) model enhances application robustness.
The Cluster module is built on the child_process module, supporting not only ordinary messages but also low-level objects like TCP and UDP.
When a TCP connection is sent from the master to a worker, the worker can reconstruct the TCP connection based on the message. The Cluster module can determine the appropriate number of worker processes based on hardware resources.
Threads
Single-Threading Issues
Inefficient CPU utilization.
An uncaught exception can cause the entire program to crash.
Node.js Threads
A Node.js process uses seven threads.
The core component is the V8 engine. When Node.js starts, it creates a V8 instance, which is multi-threaded:
Main Thread: Compiles and executes code.
Compile/Optimize Thread: Optimizes code while the main thread executes.
Profiler Thread: Tracks code execution time to provide data for Crankshaft optimization.
JavaScript execution in Node.js is single-threaded, but the host environment (Node.js or browsers) is multi-threaded.
Asynchronous I/O
Node.js uses a thread pool for certain I/O operations (e.g., DNS, FS) and CPU-intensive tasks (e.g., Zlib, Crypto).
The default thread pool size is 4, but it can be modified manually.
process.env.UV_THREADPOOL_SIZE=64;
Cluster Multi-Process Model
const cluster =require('cluster');const http =require('http');const numCPUs =require('os').cpus().length;if (cluster.isMaster) { console.log(`Master process ${process.pid} is running`);for (let i =0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker process ${worker.process.pid} exited`); });} else {// Workers can share any TCP connection.// In this example, they share an HTTP server. http.createServer((req, res) => { res.writeHead(200); res.end('Hello World'); }).listen(8000); console.log(`Worker process ${process.pid} started`);}
The example creates 9 processes: 1 master process and 8 worker processes (2 CPUs × 4 cores = 8 workers).
Both child_process and cluster use a multi-process model, not a multi-threaded model.
To address single-threading limitations, multi-process approaches are commonly used to simulate multi-threading.