NodeJS is a development platform based on JavaScript that allows developers to write server-side applications using JavaScript. One of NodeJS's key features is its single-threaded, event-driven model, enabling efficient handling of numerous concurrent requests without requiring multiple threads or processes.
However, the single-threaded nature of NodeJS has its limitations, such as:
To address these issues, NodeJS offers a Master-Worker Pattern, also known as the Cluster Mode. This distributed system design pattern comprises a master process and multiple worker processes. The master process manages and monitors the workers, while the workers handle specific business logic.
In NodeJS, the Master-Worker Pattern can be implemented using the cluster
module. This module allows developers to easily create multiple child processes and provides methods and events for control and communication. The basic steps to use the cluster
module are:
cluster
module and determine if the current process is the master or a worker.cluster.fork()
method to create multiple worker processes and bind events to monitor their state and messages.process.send()
.Here is a basic example of using the cluster
module:
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection.
// In this case, it is an HTTP server.
http
.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from Worker!');
})
.listen(8000);
console.log(`Worker ${process.pid} started`);
}
In this code, the master process first checks if it is the master (cluster.isMaster
). If true, it creates as many workers as the system's CPU core count. Each worker is an independent instance of the master process, with its own memory and V8 instance. The workers create an HTTP server using http.createServer
and begin listening for requests.
If a worker crashes or is killed, the exit
event triggers, allowing the master to restart the worker.
Use Nginx as a reverse proxy and load balancer. Nginx can distribute incoming requests across multiple Node.js processes.
Nginx configuration example:
http {
upstream node_cluster {
server 127.0.0.1:8000;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
# ... other Node.js processes
}
server {
listen 80;
location / {
proxy_pass http://node_cluster;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
}
In this configuration, Nginx distributes incoming requests evenly among the Node.js processes defined in node_cluster
.
In conclusion, Node.js's Master-Worker Pattern, implemented via the cluster
module, offers a simple yet powerful way to create multi-process applications, enhancing performance and reliability.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
Deploy unlimited projects for free
Unbeatable Cost Efficiency
Streamlined Developer Experience
Effortless Scalability and High Performance
Explore more in the Documentation!
Follow us on X: @LeapcellHQ