DEV Community

Cover image for Is Node.js really single-threaded?

Is Node.js really single-threaded?

Santhosh Reddy on July 26, 2020

Many developers wonder at some point in their Node.js programming journey that, is Node.js really single-threaded? If it is, how is it able to do a...
Collapse
 
merri profile image
Vesa Piittinen

I will do a joke. It will be very bad.

So Node.js is married-threaded.

Collapse
 
pankajtanwarbanna profile image
Pankaj Tanwar

It's been 6 hours. How to get this out of my head? It's very bad. 😣

Collapse
 
rsa profile image
Ranieri Althoff

Very bad indeed

Collapse
 
ben profile image
Ben Halpern

I concur

Collapse
 
aminmansuri profile image
hidden_dude

So does this mean that there's no advantage in running Node on a super beefy 16 core machine?

Collapse
 
dealloc profile image
Wannes Gennar

Honestly, if you're looking to make use of heavy multithreading; Javascript just isn't the language you should be looking at I'm fraid

Collapse
 
santhoshrt profile image
Santhosh Reddy

It's a practice to spawn multiple instances of the app with this type of setup.
Have a look at cluster module.

nodejs.org/api/cluster.html

Collapse
 
haseebsaeed profile image
haseebsaeed

To get started with multiple instances, have a look at pm2. You can spawn as many instances as your cpu cores.

pm2.keymetrics.io/

Collapse
 
okeeffed profile image
Dennis O'Keeffe

More an aside, but this was a great Node.js course on Frontend Masters that I did once. It touches on the usage of libuv under the hood for anyone who finds this discussion topic fascinating frontendmasters.com/courses/server...

 
dealloc profile image
Wannes Gennar • Edited

From what I can tell (correct me if I'm wrong), this uses service workers under the hood.
Those have the problem that you're not able to share memory, so if you want to pass large amounts of data around, you're effectively copying it every time it moves between threads.
While perhaps not problematic for some, I see this cause problems on large scale if you're not careful about what you're passing around; as well as the issue that suddenly you're not passing by reference whereas a regular function call would (for objects etc).

Collapse
 
rsa profile image
Ranieri Althoff

Asynchronous execution does not mean parallel execution. Node runs asynchronous tasks concurrently.

Collapse
 
santhoshrt profile image
Santhosh Reddy • Edited

True to some extent(per each worker). But, offloading multiple tasks to libuv thread pool essentially make it parallel.