As we all know, Node
.js is essentially JavaScript running outside the browser. It operates on a single thread, meaning it can only utilise one thread/core on any machine. This single-threaded nature presents a challenge:
When we want more users to use our backend service, Node.js won't be able to handle an overwhelming quantity of requests efficiently. To address this, we typically try to scale our application.
In other programming languages, we can use multiple threads or cores of the CPU, effectively utilising all the CPU power. This makes it possible to scale vertically by adding more CPU, memory, and RAM to the machine. However, because Node.js is single-threaded, no matter what, it will only use one core of your machine, leaving all other cores idle.
Node
.js?You might ask, "Why don't we make Node
.js use multiple cores?" Well, the answer is, you can, but it's really hard and counterintuitive. The complexity of managing multiple threads in Node
.js often outweighs the benefits.
The first solution that might come to your mind is if the machine has 8 cores then just run 8 different Node applications simultaneously:
node index1.js
node index2.js
node index3.js
.
.
.
node index8.js
This, of course, has a lot of problems: