301

In PHP (or Java/ASP.NET/Ruby) based webservers every client request is instantiated on a new thread. But in Node.js all the clients run on the same thread (they can even share the same variables!) I understand that I/O operations are event-based so they don't block the main thread loop.

What I don't understand is WHY the author of Node chose it to be single-threaded? It makes things difficult. For example, I can't run a CPU intensive function because it blocks the main thread (and new client requests are blocked) so I need to spawn a process (which means I need to create a separate JavaScript file and execute another node process on it). However, in PHP cpu intensive tasks do not block other clients because as I mentioned each client is on a different thread. What are its advantages compared to multi-threaded web servers?

Note: I've used clustering to get around this, but it's not pretty.

14
  • 16
    I recently watched a good video (29 mins) explaining some of the theory behind Node. I even think the guy talks about CPU intensive tasks and briefly how to handle them: youtube.com/watch?v=L0pjVcIsU6A
    – whirlwin
    Commented Jul 31, 2013 at 0:31
  • 34
    You may know this, but to be clear Node.js isn't single-threaded. Your JavaScript code runs single-threaded, but IO operations and other things that plugins can do run out of a thread pool. Node.js gives you much of the benefit of multithreading without having to deal with multithreaded code. Also, Node.js contributors didn't choose single-threaded nature of JavaScript, the authors of JavaScript did. I can't think of a way JS could work in a multithreaded context, but even if there were, V8 isn't written that way which is what Node.js uses as its JavaScript engine.
    – Brad
    Commented Jul 31, 2013 at 1:07
  • 9
    PHP is more single-threaded than JavaScript. You are probably thinking of server modules like FastCGI or mod_php. So you're in fact comparing Node.js with Apache, Nginx or IIS—not with PHP, Java or Ruby. Commented Feb 17, 2014 at 10:03
  • 56
    Node is not single-threaded. It's a popular misconception. Even simple node -e 'setTimeout(()=>{},1000);' & ps -T h $! | wc -l; kill $! displays five threads on my system. The main event loop is single-threaded (it wouldn't make much sense if it wasn't) but Node is heavily multi-threaded and you can write multi-threaded single-process applications if you want. I would love to write a comprehensive answer about it but some people decided to close your question so I can't. I'm voting to reopen it. If it gets more votes and gets reopened then please mention me in the comment.
    – rsp
    Commented Feb 3, 2016 at 14:49
  • 2
    @rsp thanks for your comment, but I meant in the main thread not i/o related. if you're doing something cpu related like a big for loop that does something then the server stops processing connections. meaning, the server is unusable at the time. so we're left using hacks like clusters just to do something so simple instead of it inherently threading every connection like most servers do. jxcore.com tried to address this but then it makes one use special/modified node plugins which essentially makes it unusable to me.
    – Shai UI
    Commented Feb 3, 2016 at 16:34

3 Answers 3

345

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

20
  • 29
    But web servers typically do ALOT of cpu intensive stuff it's not JUST database fetching. We need to process what we fetch, and do alot of business logic alot of the time before serving it up to the client.
    – Shai UI
    Commented Jul 31, 2013 at 0:40
  • 30
    So just spawn workers, well! That's the whole deal with Node.js. Heavy stuff can run in another process, and you process it's results in a lightweight callback.
    – MaiaVictor
    Commented Jul 31, 2013 at 0:44
  • 8
    The problem with that is that there's an os level process running per worker.. You'll see them using "ps" command. So that potentially means thousands of processes running on the machine at once - that's nuts!
    – Shai UI
    Commented Jul 31, 2013 at 0:50
  • 11
    @foreyez, You don't need a process per user. You have choice in how you split up the load. Also, not everyone is doing a ton of CPU intensive stuff. Node is a tool for a job... maybe not your job, but many kinds of jobs.
    – Brad
    Commented Jul 31, 2013 at 1:16
  • 26
    Actually, I'd like @foreyez to back up that statement that "web servers typically to ALOT(sic) of cpu intensive stuff". In my experience, they don't. Or maybe my definition of 'cpu intensive' differs from his. Converting product data into a UI is not CPU intensive, nor is calculating orders or the like. Most of the web is pretty transactional. CPU intensive stuff is things like converting videos, converting image formats, etc. Much of that is due to file i/o which, actually, node does pretty well. And makes it easy to offload to another process that's dedicated to the converting.
    – Paul
    Commented Jul 31, 2013 at 3:03
77

The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.

Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

5
  • 8
    Node.js is restricted to event-only processing due to the lack of v8 multithreading support. Well, javascript language itself lacks the needed features, so any implementatio will end up being tricky. That's the main culprit of Node.js, In my opinion. In other languages you can choose what you want. Or some hybrid of both models, like java NIO.
    – FrameGrace
    Commented Feb 17, 2014 at 21:08
  • 4
    @Kazaag, Modern web servers do maintain a threadpool. They don't just dumbly spawn a new thread per page load. Those are the older web servers.
    – Pacerier
    Commented Feb 19, 2017 at 18:50
  • 2
    @Pacerier I never said that a new thread is spawn, but each thread is allocated to one request until the request is finished.
    – Kazaag
    Commented Feb 23, 2017 at 12:35
  • 2
    @Kazaag It is definitely not a general rule that "each thread is allocated to one request until the request is finished". I.e. in .Net (including processing HTTP requests) one can and should use async (Task based) programming and this will release threads while waiting for I/O and other async operations to complete. This is applicable to high level programming as well, i.e. MVC/API controllers. So in practice there could be 20 HTTP requests pending but only one active thread. Commented Nov 7, 2018 at 0:07
  • "silver bullet in your foot" Opening my shoe: Python xD
    – france1
    Commented Jan 26, 2023 at 19:46
32

Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.

At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ

2
  • Do you have more information regarding this "isolate"?
    – Pacerier
    Commented Feb 19, 2017 at 18:51
  • V8 is not single-threaded
    – mercury
    Commented Nov 29, 2021 at 20:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.