How to make NodeJs use More CPU Core or Multithreading Instead Single-thread How to make NodeJs use More CPU Core or Multithreading Instead Single-thread multithreading multithreading

How to make NodeJs use More CPU Core or Multithreading Instead Single-thread


Your question is perfectly valid.

A typical nodejs web server will use only 1 core of a CPU at any given moment.

Take a look at the cluster module


What you need to remember here is that multi-threaded code is not easy to write correctly, and handling concurrency in an application is something very few languages do well. The NodeJS team has chosen not to include a threading implementation probably because JavaScript itself is missing language features that would make this easy, and making NodeJS use a non-standard JavaScript is against the intentions of that project. It's possible that the emerging web workers standard will solve some of these problems.

That being said, from an operating system perspective the distinction between threads and processes is pretty minor. Each process is comprised of one or more threads, each of which compete with other threads on the system for resources according to their priority level.

If you build an application that's highly multi-threaded, or you build one that's multi-process, you will have the same concerns when it comes to running flat-out with any of your threads going to 100% utilization of a CPU core.

The solution in NodeJS is to break down your task into a series of smaller tasks that can be distributed amongst workers either in the same process, as you might with the stream interface, or between processes using some form of inter-process communication.

If you're worried about your server being swamped and grinding to a halt, what you need to do is some up with some sort of rate limiter that will regulate how much work is being done by your Node processes. A worker queue like RabbitMQ is one way to do this.

All this is talking about native NodeJS. If you're willing to mix in some modules, something that's pretty much essential with any serious work, you do have options like the webworker threads package from NPM that might do what you need.


Mike Gleason is correct with his answer on using the cluster module.

An easier way to "use" that is to use the PM2 app/module to manage your Node processes which manages the clustering for you and allows for graceful restarts etc.