NodeJS is single thread, meaning a request must be completed before it can execute another request. This example demonstrates how inefficient in NodeJS: https://github.com/htsiah/node-performance-using-cluster/tree/main/blocking-the-event-loop
To improve the performance, we can implement cluster where you can fork as many as child processes. The rule of thumb is the child can not more than logical CPU. You can download the cluster implementation here. https://github.com/htsiah/node-performance-using-cluster/tree/main/cluster-in-action
This article explains the number of child process and thread vs the logical CPU: https://dev.to/johnjardincodes/increase-node-js-performance-with-libuv-thread-pool-5h10
PM2 is a NodeJS cluster package. This package used in many production environments. I recommend PM2 instead of reinventing the wheel. The above example is to let you understand how the cluster works.
First, you need to install PM in the global environment by using the command: npm install -g pm2
To start the application using pm2: pm2 start app.js -i -1 (-1 is maximum child process.)
To show all the process: pm2 list
To delete the process: pm2 delete app
More refer to https://www.npmjs.com/package/pm2
No comments:
Post a Comment