Backend
Node.js
Node.js and Threads

Node.js and Threads

One of the most misunderstood concepts in backend engineering is how Node.js actually handles threads. You will often hear that "Node.js is single-threaded," but this is only half the truth. Understanding the hidden multi-threaded architecture of Node.js is critical for system design.

The Single Main Thread

When you write JavaScript code in Node.js, your code executes on exactly one single main thread.

If 10,000 users hit your API at the same time, Node.js does not spawn 10,000 threads to handle them (unlike traditional servers like Java Tomcat). Instead, that single main thread handles all 10,000 users concurrently via the Event Loop.

Why is JavaScript Single-Threaded?

By forcing all JavaScript to run on a single thread, Node.js completely eliminates Race Conditions and Deadlocks. You never have to worry about two users accidentally modifying the same variable in memory at the exact same millisecond.

The Hidden Multi-Threading: libuv

If Node.js only has one thread, how does it handle heavy operations without freezing?

While your JavaScript code is strictly single-threaded, Node.js itself is written in C++ and relies on a powerful underlying library called libuv.

Libuv maintains a hidden Thread Pool (defaulting to 4 threads, which can be increased). Node.js uses this background thread pool to offload heavy, blocking tasks so the main JavaScript thread can stay fast and responsive.

What goes to the Thread Pool?

Node.js explicitly uses the libuv thread pool for three primary operations:

  1. File System (fs): Reading and writing large files to the hard drive (Storage I/O).
  2. DNS: Resolving domain names to IP addresses.
  3. Crypto: Heavy mathematical operations like hashing passwords (bcrypt or crypto.pbkdf2).

Worker Threads

If you write a massive for-loop that parses millions of JSON objects, it will block the main thread, and the libuv thread pool will not help you (because it is just standard JavaScript execution, not I/O or Crypto).

To solve this, modern Node.js provides the Worker Threads module. This allows you to manually spawn additional threads to execute heavy CPU-bound JavaScript in parallel, effectively giving you full multi-threading capabilities when you need them.