Node.js 采用了单线程模型,且拥有基于事件驱动的异步非阻塞 I/O 特性,可高效利用 CPU 资源,但并不能说明 Node.js 只能运行在单核 CPU 下。事实上,Node,js 原生已支持集群特性,我们只需要将程序稍作调整,就能充分利用多核 CPU 带来的价值。
一个简单的 Hello Word!程序,我们将该应用程序部署在单台服务器的多核 CPU 上,从而搭建集群环境。也就是说,每个 CPU 内核都会运行一个 Node.js 进程,但需要注意的是,这样的集群只能在单台服务器上运行,而不能跨多台服务器。改造的程序如下:
var http = require('http');var cluster = require('cluster');var os = require('os');var PORT = 1234;var CPUS = os.cpus().length; // 获取 CPU 内核数if (cluster.isMaster) {// 当前进程为主进程for (let i = 0; i < CPUS; i++) {cluster.fork()}} else {var app = http.createServer((req, res) => {console.log(req.url, process.pid)res.writeHead(200, { 'Content-Type': 'text/html' });res.write('<h1>Hello World!</h1>');res.end()})app.listen(PORT, () => {console.log(`server is running at ${PORT}`)})}
我们首先加载了 Node.js 内置的 Cluster 模块与 OS 模块,通过 OS 模块获取 CPU 内核数,随后分两种情况进行处理,若当前进程为主线程(Master Process),则根据 CPU 内核数去创建子进程(Child Process) ,只有在子进程中才能执行相关的程序代码。实际上,在内部就是通过主进程去调度各个子进程的。可见,CPU 核心数越多,单台服务器上可创建的子进程就越多,支持的并发量就越大,从而整个应用程序的吞吐率就越高。
实际项目中,我们启动代码一般都已经封装在了 app.js 中,要把整块启动逻辑嵌在上面的 if else 中实在不优雅,所以可以这样:
var cluster = require('cluster');var numCPUs = require('os').cpus().length;if (cluster.isMaster) {for (var i = 0; i < numCPUs; i++) {cluster.fork();}// 其它代码} else {require("./app.js");}
To see the advantages that clustering offers, we’ll start with a sample Node.js app that doesn’t use clusters and compare it with one that uses clusters:
const express = require('express');const app = express();const port = 3000;app.get('/', (req, res) => {res.send('Hello World!');})app.get('/api/:n', function (req, res) {let n = parseInt(req.params.n);let count = 0;if (n > 5000000000) n = 5000000000;for(let i = 0; i <= n; i++){count += i;}res.send(`Final count is ${count}`);})app.listen(port, () => {console.log(`App listening on port ${port}`);})
It’s a bit contrived and not something you would find a real-world situation, but it will suit our needs. The app contains two routes - a root route that returns the string “Hello World” and another route that takes a route parameter n and adds numbers up to n to a variable count before returning a string containing the final count.
The operation is an 0(n) operation so it offers us an easy way to simulate long-running operation on the server - if we feed it a large enough value for n . We cap n off at 5,000,000,000 - let’s spare our computer from having to run so many operations.
If you run the app with node app.js and pass it a decently small value for n (e.g. http://localhost:3000/api/50 ), it will execute quickly and return a response almost immediately. The root route( http://localhost:3000 ) also returns a response quickly.
When you pass it a large n , you will start seeing the problem that running the app on a single thread offers. Try passing it 5,000,000,000 (via https://localhost:3000/api/5000000000).
The app will take a few seconds to complete the request. If you open another browser tab and try to send request to the server (to either / or /api/:n route), the request will take a few seconds to complete as the single thread will be busy processing the other long-running operation. The single CPU core has to complete the first request before it can handle another.
Now, let’s use the cluster module in the app to spawn some child processes and see how that impove things.
Below is the modified app:
const express = require('express');const port = 3000;const cluster = require('cluster');const totalCPUs = require('os').cpus().length;if (cluster.isMaster) {console.log(`Number of CPUs is ${totalCPUs}`);console.log(`Master ${process.pid} is running`);// Fork workers.for (let i = 0; i < totalCPUs; i++) {cluster.fork();}cluster.on('exit', (worker, code, signal) => {console.log(`worker ${worker.process.pid} died`);console.log("Let's fork another worker!");cluster.fork();});} else {const app = express();console.log(`Worker ${process.pid} started`);app.get('/', (req, res) => {res.send('Hello World!');})app.get('/api/:n', function (req, res) {let n = parseInt(req.params.n);let count = 0;if (n > 5000000000) n = 5000000000;for(let i = 0; i <= n; i++){count += i;}res.send(`Final count is ${count}`);})app.listen(port, () => {console.log(`App listening on port ${port}`);})}
The app does th same thing as before, but this time, we are spawning up several child processes that will all share port 3000 and that will be able to handle requests sent to this port. The worker processes are spawning using the child_process.fork() method. The method returns a ChildProcess object that has a built-in communication channel that allows messages to be passed back and forth between the child and its parent.
We create as many child processes as there are CPU cores on the machine the app is running. When the app first runs, we check to see if it’s a master process with isMaster. This is determined by the process.env.NODE_UNIQUE_ID variable. If process.env.NODE_UNIQUE_ID is undefined, then isMaster will be true
If the process is a master, we then call cluster.fork() to spawn several prcesses. We log the master and worker process IDs. Below, you can see the ouput from running the app on a four-core system. When a child process, we spawn a new one to keep utilizing the available CPU cores.
Number of CPUs is 4Master 67967 is runningWorker 67981 startedApp listening on port 3000Worker 67988 startedApp listening on port 3000Worker 67982 startedWorker 67975 startedApp listening on port 3000App listening on port 3000
To see the improvement clustering offers, run the same experiment as before: first make a request to the server with a large value for n and quickly run another request in another browser tab. The second request will complete while the first is still running - it doesn’t have to wait for the other request to complete. With multiple workers available to take requests, both server availability and thoughput are improved.
Running a request in one browser tab and quickly running another one in a second tab might work to show us the improvement offered by clustering for our example, but it’s hardly a proper or reliable way to determine performance improvements. Let’s take a look at some benchmarks that will better demonstrate how much clustering has improved our app.
Performance Metrics
Let’s run a load test on our apps to see how each handles a large number of incoming connections. We’ll use the loadtest package for this.
The loadtest package allow you to simulate a large number of concurrent connections to your API so that you can measure its performance.
To use loadtest ,first install it globally:
npm install -g loadtest
Then run the app that you want to test with node app.js. We will start by testing the version that doesn’t use clustering.
With the app running, open another Terminal and run the following load test:
loadtest http://localhost:3000/api/500000 -n 1000 -c 100
The above command will send 1000 requests to the given URL, of which 100 are concurrent. The following is the output from the above command:
Requests: 0 (0%), requests per second: 0, mean latency: 0 msTarget URL: http://localhost:3000/api/500000Max requests: 1000Concurrency level: 100Agent: noneCompleted requests: 1000Total errors: 0Total time: 1.268364041 sRequests per second: 788Mean latency: 119.4 msPercentage of the requests served within a certain time50% 121 ms90% 132 ms95% 135 ms99% 141 ms100% 142 ms (longest request)
With a request where n = 500000 the server was able to handle 114 requests per second with a mean latency if 828.9 milliseconds.
Let’s compare this result with that of the app that use clusters.
Stop the non-cluster app, run the clustered one and, finally, run the same load tests.
Below are the results for testing for http://localhost:3000/api/500000 :
Requests: 0 (0%), requests per second: 0, mean latency: 0 msTarget URL: http://localhost:3000/api/500000Max requests: 1000Concurrency level: 100Agent: noneCompleted requests: 1000Total errors: 0Total time: 0.701446328 sRequests per second: 1426Mean latency: 65 msPercentage of the requests served within a certain time50% 61 ms90% 81 ms95% 90 ms99% 106 ms100% 112 ms (longest request)
Tested with the same requests(when n = 500000 ), the app that uses clustering was able ti handle 1426 requests per second - a significant increase, compared to the 788 requests per second of the app with no clusters. The mean latency of the clustered app is 65 milliseconds, compared to 119.4 of the app with no clusters. You can clearly see the improvement that clustering added to the app.
And below are the results for testing for http://localhost:3000/api/5000000 :
Requests: 0 (0%), requests per second: 0, mean latency: 0 msTarget URL: http://localhost:3000/api/5000000Max requests: 1000Concurrency level: 100Agent: noneCompleted requests: 1000Total errors: 0Total time: 2.43770738 sRequests per second: 410Mean latency: 229.9 msPercentage of the requests served within a certain time50% 235 ms90% 253 ms95% 259 ms99% 355 ms100% 421 ms (longest request)
Here (when n = 5000000), the app was able to run 410 requests per second, compared to 114 of the app with no clusters, with a latency of 229.9 ,compared with 828.9 of the other app.
Before moving on to the next section, let’s take a look at a scenario where clustering may not offer much performance improvement.
We’ll run two more rests for each of our apps. Well test requests that aren’t CPU-intensive and that run fairly quickly without overloading the Event Loop.
With the no-cluster app running, execute the following test:
loadtest http://localhost:3000/api/50 -n 1000 -c 100
The following represents the summarized results:
Total time: 0.531421648 sRequests per second: 1882Mean latency: 50 ms
With the same no-cluster app still runnig, execute the following test:
loadtest http://localhost:3000/api/5000 -n 1000 -c 100
Here are the summarized results:
23Total time: 0.50637567 sRequests per second: 1975Mean latency: 47.6 ms
Now, stop the app and run the clustered one once more.
With the clustering app running, execute the following test:
loadtest http://localhost:3000/api/50 -n 1000 -c 100
The summarized results:
Total time: 0.598028941 sRequests per second: 1672Mean latency: 56.6 ms
The clustered app ran 1672 requests per second compared to 1882 of the no-cluster one and had a mean latency of 56.6 milliseconds compared to 50 of the no-cluster one.
Let’s run the other test. With the same cluster app still running, execute the test below:
loadtest http://localhost:3000/api/5000 -n 1000 -c 100
The summarized results:
Total time: 0.5703417869999999 sRequests per second: 1753Mean latency: 53.7 ms
Here, the clustered ran 1753 requests per second compared to 1975 of the no-cluster one and a mean latency of 53.7 milliseconds compared to 47.6 of the no-cluster one.
Based on those tests, you can see the clustering didn’t offer much improvement to the app’s performance. In fact, the clustered app performed a bit worse compared to the one that doesn’t use clusters. How come?
In the tests above, we call our API with a fairly small value for n, which means that the number of times the loop in our code will run is considerably small. The operation won’t be that CPU-intensive. Clustering shines when it comes to CPU-intensive tasks. When your app is likely to sun such tasks, then clustering will offer an advantage in terms of the number of such tasks it can run at a time.
Howhover, if your app isn’t running a lot of CPU-intensive tasks, then it might not be worth the overhead to spawn up so many workers. Remember, each process you create has its own memory and V8 instance. Because if the additional resource allocations, spawning a large number of child Node.js processes is not always recommanded.
In our example, the clustered app performs a bit worse than the no-cluster app because we are paying the overhead for creating several child processes that don’t offer much advantage. In a real-world situation, you can use this to determine which apps in your microserive architecture could benefit from clustering - run tests to check if the benefits for the extra complexity are worth it.
Using PM2 to Manage a Node.js Cluster
In our app, we are using the Node.js cluster module to manually create and manage worker processes. We first determine the number of number if workers to spawn (using the number of CPU cores), then manually spawn the workers, and finally, listen for any dead workers so we can spawn new ones. In our very simple app, we’ve had to write a decent amount id code just to handle clustering. In a production app, you can expect to write even more.
There id a tool that help manage the process a bit better - the PM2 process manager. PM2 is a Production Process Manage for Node,js applications with a built-in Load Balancer. When properly configured, PM2 will automatically run your app in cluster mode, spawn workers for you, and take care of spawning new workers when a worker dies. PM2 make it easy to stop, delete, and start processes and it also has some monitoring tools that can help you to moniter and tweak your app’s performance.
To use PM2, first install it globally:
npm install pm2 -g
We use it to run our first unmodified app:
const express = require('express');const app = express();const port = 3000;app.get('/', (req, res) => {res.send('Hello World!');})app.get('/api/:n', function (req, res) {let n = parseInt(req.params.n);let count = 0;if (n > 5000000000) n = 5000000000;for(let i = 0; i <= n; i++){count += i;}res.send(`Final count is ${count}`);})app.listen(port, () => {console.log(`App listening on port ${port}`);})
Run the app with:
pm2 start app.js -i 0
-i <number of workers> will tell PM2 to launch the app in cluster_mode (as opposed to fork_mode). If <number if workers> is set to 0, PM2 will automatically spawn as many workers as there are CPU cores.
And just like that, your app is running in cluster mode - no need for code changes. You can now run the same tests of the previous sections after which can expect the same results of the app that used clusters. Behind the scenes, PM2 also uses the Node.js cluster module as well as other tools that make process management easier.
In the Terminal, you’ll get a table displaying some details of the spawned processes:

You can stop the app with the following command:
pm2 stop app.js
The app will go offline and the Terminal output will show all processes with a stopped status.

Rather than always passing in configuraions when you run the app with pm2 start app.js -i 0, you can save them to a separate configuration file - called Ecosytem File. The file also allows you to set up specific configurations for different applications, which can be particularly useful for micro-service apps, for example.
You can generate an Ecosystem File with the following command:
pm2 ecosystem
It will generate a file named ecosystem.config.js. As for our app, we need to modify it as a shown below:
module.exports = {apps : [{name: "app",script: "app.js",instances : 0,exec_mode : "cluster"}]}
By setting exex_mode with the cluster value, you instruct PM2 to load balance between each instance. The instance are set to 0 just as before, which will spawn as many workers as there are CPU cores.
The -i or instances option can be set to:
0ormax(deprecated) to spread the app across all CPUs-1to spread the app across all CPUs -1numberto spread the app across anumberof CPUs
You can now run app with:
pm2 start ecosystem.config.js
The app will run in cluster mode, just as before.
You can start, restart, reload, stop and delete an app with the following commands, respectively:
$ pm2 start app_name$ pm2 restart app_name$ pm2 reload app_name$ pm2 stop app_name$ pm2 delete app_name# When using an Ecosystem file:$ pm2 [start|restart|reload|stop|delete] ecosystem.config.js
The restart command immediately kills and restarts the processes while the reload commmand achieves a 0-second-downtime reload where workers are restarted one by one, waiting for a new worker to spawn before killing the old one.
You can alse check the status, logs, and metrics of running applications.
The following lists the status of all application managed by PM2:
$ pm2 ls
The following displays logs in realtime:
$ pm2 logs
The following displays a realtime dashboard in your Terminal:
$ pm2 monit
For more on PM2 and its cluster mode, check the documention.
Conclusion
Clustering offers a way of improving your Node.js app performance by making use of system resources in a more effcient way, We saw noticeable improvements in throughput when an app was modified to use clusters. We then took a brief look at tool that can help you make the process of managing clusters a bit easier. I hope this article was useful to you. For more on clustering, check the cluster module documentation and PM2 decumentation. You can also check out this tutorial.
