Node.js Cluster Module
Node.js's cluster module allows you to easily create child processes (worker processes) that share the same server port. Since Node.js is single-threaded,cluster the module can help us fully utilize the performance of multi-core CPU systems.
Simply put,cluster The module is like a restaurant manager that creates multiple waiters (workers) to handle customers (requests), rather than having one waiter handle all customers.
Why do we need the Cluster module?
-
Improves performance: modern CPUs usually have multiple cores, but Node.js uses only one core by default.
clusterThe module lets you utilize all available CPU cores. -
Improve reliability: if one worker crashes, other workers can continue handling requests, and the master process can restart the crashed worker.
-
Zero downtime: workers can be restarted one by one to implement code updates without interrupting service.
Basic Usage of the Cluster Module
Example
const
cluster
=
require
(
'cluster'
)
;
const
http
=
require
(
'http'
)
;
const
numCPUs
=
require
(
'os'
)
.
cpus
(
)
.
length
;
if
(
cluster.
isMaster
)
{
console.
log
(
`Master process $
{
process.
pid
}
running`
)
;
// Fork worker processes
for
(
let i
=
0
;
i
<
numCPUs
;
i
++
)
{
cluster.
fork
(
)
;
}
cluster.
on
(
'exit'
,
(
worker
,
code
,
signal
)
=>
{
console.
log
(
`worker $
{
worker.
process
.
pid
}
exited`
)
;
}
)
;
}
else
{
// Workers can share the same TCP connection
// Here is an HTTP server
http.
createServer
(
(
req
,
res
)
=>
{
res.
writeHead
(
200
)
;
res.
end
(
'Hello World\n'
)
;
}
)
.
listen
(
8000
)
;
console.
log
(
`Worker $
{
process.
pid
}
started`
)
;
}
Core Concept Analysis
Master Process
- Responsible for managing all worker processes
- Usually does not handle actual requests
- Can listen for various worker events
Worker Processes
- Child processes that actually handle requests
- Each worker is an independent Node.js process
- Share the same server port
Common APIs of the Cluster Module
cluster.fork()
Creates a new worker process. Calling this method returns a worker object.
cluster.isMaster
if it is the master process, true。
cluster.isWorker
if it is a worker process, true。
cluster.workers
a hash table containing all active worker objects, keyed by worker.id as the key.
Practical Application Scenarios
1. Load balancing
Example
// In the master process
const
cluster
=
require
(
'cluster'
)
;
const
numCPUs
=
require
(
'os'
)
.
cpus
(
)
.
length
;
if
(
cluster.
isMaster
)
{
for
(
let i
=
0
;
i
<
numCPUs
;
i
++
)
{
cluster.
fork
(
)
;
}
}
else
{
require
(
'./app'
)
;
// Your application entry file
}
2. Graceful restart
Example
cluster.
on
(
'exit'
,
(
worker
,
code
,
signal
)
=>
{
console.
log
(
`Worker $
{
worker.
process
.
pid
}
exited`
)
;
// You can fork a new worker here
cluster.
fork
(
)
;
}
)
;
3. Inter-process communication
Example
// The master process sends a message
worker.
send
(
'Hello worker!'
)
;
// The worker receives the message
process.
on
(
'message'
,
(
msg
)
=>
{
console.
log
(
`Worker $
{
process.
pid
}
Message received
:
$
{
msg
}
`
)
;
}
)
;
Performance optimization tips
-
Create workers based on the number of CPU cores: it is usually recommended that the number of workers equal the number of CPU cores.
-
Shared port: all workers share the same port, and the operating system automatically distributes requests to different workers.
-
Shared connections: for long-lived connections (such as WebSocket), you need to consider how connections are distributed to different workers.
-
Shared state: workers do not share memory, so you need to use external storage such as Redis to share state.
Common Problems and Solutions
1. Memory leaks
Each worker is an independent process, so a memory leak in one worker will not affect the others, but you need to monitor and restart abnormal workers.
2. Session persistence
If you need session persistence, you can use sticky sessions or store session data externally (such as in Redis).
3. File descriptor limits
A large number of workers may exhaust file descriptors, so you need to adjust system limits:
Example
ulimit
-n
10000
Set the file descriptor limit
Alternatives to the Cluster Module
Although cluster The module is powerful, but there are other options:
- PM2: a process manager with built-in load balancing and monitoring
- Nginx: a reverse proxy that can load balance across multiple Node.js instances
- Kubernete: a container orchestration system that can automatically scale Node.js services
Summary
Node.js's cluster The module is an important tool for building high-performance, highly available network services. By creating multiple worker processes, we can:
- fully utilize the performance of multi-core CPUs
- improve application reliability
- achieve zero-downtime deployment
Although setting up and managing multi-process applications is more complex than single-process ones, for Node.js applications in production environments, using the cluster module or a similar solution is almost essential.
I hope this guide helps you understand and use Node.js's cluster module!
Node.js Built-in Modules