Shortly, How Node.js works on a single thread?

There is a common misconception when it comes to node.js. People start tell how a single threading model going to work well or scale much.

Let’s first agree on the fact that you don’t know your scalability issues from the start, you don’t know what is your feature set when you start out and you won’t know how your scaling problems will be. wait until your site grows to learn where your scaling problem are going to be.

Node.js was built upon an experiment in asynchronous processing, and was said that doing an asynchronous processing on a single thread could provide more performance and scalabilty than typical thread based implementation.

The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn’t continue processing the event loop until the code after an async function has executed.

Event-loop is the heart of each node.js process and it keeps pumping as long as the process is alive. It’s responsible for handling async operations, that means any request for I/O will queued to the event loop waiting to be executed on the next free I/O, on execution completion the event loop will got notified to trigger a callback to the main function.

During this process, your main thread isn’t blocked and your code would continually execute peacefully. While the intensive CPU scenario may not be the best choice here, there’re some workarounds to get your job done.

When people say “Node.js runs on a single thread” they are really saying “the callbacks of Node.js run on a single thread”, all other threads that actually handling your I/O operations are handled by a C level thread pool.

It’s always dependent on what you’re doing. If you are not familiar with your application’s nature, node.js may be a free receipt to the hell.

If you need more details, there’e are some good references here :
1- What the heck is the event loop anyway?
2- Understanding the Node.js Event Loop — Node.js at Scale

Show your support

Clapping shows how much you appreciated Amr Ragaey’s story.