Node.js

Most of us think that node.js is single-threaded is that true ? Let's find out

28 NOV 2022

as we know node.js is a single-threaded application, but it is not fully true. Node.js uses a single threaded model with event looping. Event looping is an algorithm that uses an event queue and an event loop. The event loop looks at the event queue and processes the pending callbacks. The event loop is a part of the browser JavaScript runtime. It is responsible for executing the callback functions after the call stack is empty. BUT there's some exceptions to this rule. some of Node.js frameworks and standard/core libraries are not fully single-threaded. Let's take a look at some of them.

Let's do some benchmarks and discover in code what'll happen!

We are going to use crypto standard module, which is a part of the core Node.js. DON'T WORRY, We just care about the time and order the results printed out in the console.

Code snippet:

Console result:

Looks normal? ok let's see another one

Code snippet:

Console result:


Here we should pause and think about what's happening. As you may noticed that the 2 functions executed at the same time. But why? that's because the crypto module is not fully single-threaded. It uses a thread pool to handle the heavy work. So, the 2 functions executed at the same time. But what about the 3rd, 4th, and 5th function? Let's see what'll happen.

Code snippet:

Console result:

Result analysis:


It's clear that the 1st, 2nd, 3rd, and 4th function executed at the same time. That's because the thread pool has a limited number of threads. So, the 5rd function will be executed after the 1st, 2nd, 3rd, and 4th functions finished. But what about the 6th function? Let's see what'll happen I think you guess is right.

Console result:


As you may noticed that the 6th function executed at the same time as the 5th function. That's because the thread pool has a limited number of threads in this case 4.

Conclusion:

Node.js isn't fully single-threaded but it uses a thread pool to handle the heavy work. So, some of Node.js frameworks and standard/core libraries are not fully single-threaded.

Thanks for your time really appriciated 👏

Leave a Reply