Is Node.js Single or Multi-Threaded? A Clear Explanation

Tanay BanerjeeTanay Banerjee
2 min read

Table of contents

I often get asked Is Node.js single or multi-threaded? The answer is “it depends”.

For synchronous operations, Node.js is single-threaded because the V8 engine inside Node.js executes all the synchronous operations. And since the V8 engine lives on the main thread, in this case, only one thread is being used.

But the V8 engine can execute only synchronous operations. It offloads all the asynchronous tasks to the libuv (do not worry, we will dive deep into what exactly is libuv later).

There’s a concept of a Thread pool inside libuv. When an async task is offloaded to libuv, it finds a thread from the thread pool and occupies it. When an async operation is being processed, it completely occupies the thread, and the thread cannot do anything else.

The size of the threads is 4 by default.

So what happens when 5 async operations are offloaded?

  1. The first 4 operations occupy one thread each.

  2. The remaining 1 operation will have to wait for one of the operations to finish so that the thread gets free and the operation can use the thread.

The thread pool is used for some specific asynchronous operations and not all.

  • For the fs module operations.

  • For the lookup function of the DNS module.

  • For crypto methods.

  • Sometimes, there is some user-specified input or some C++ code that needs to be run.

Note that we can change the size of the thread pool from 4 to any number lower than or greater than 4.

Key takeaways:

  • For synchronous tasks, Node.js is single-threaded, since each and every sync task is executed by the V8 engine.

  • For asynchronous tasks, and that too among some of the above-specified operations, Node.js becomes multi-threaded, and it can use the UV Thread pool.

That's it. I hope it was worth your time and helped you in some way. Can you please share it with the community? Would appreciate it. Please provide your feedback in the comments. Thanks for reading.

0
Subscribe to my newsletter

Read articles from Tanay Banerjee directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tanay Banerjee
Tanay Banerjee

Hi 👋, I am Tanay. I am from Kolkata, West Bengal. I am a Flutter Developer with 2 years of working experience.