01 / 09

Node js is single-threaded or multithreaded?

Node.js is single-threaded for the execution of your JavaScript code, but it is multi-threaded at the system and runtime level.

The Single-Threaded Aspect
  1. 1

    All your application's JavaScript code runs on a single main thread called the Event Loop.

  2. 2

    Non-Blocking: Because it is single-threaded, Node.js uses asynchronous, non-blocking I/O to handle thousands of concurrent connections without the overhead of creating a new thread for every request

The Multi-Threaded Aspect: While your code runs on one thread, the Node.js runtime environment uses multiple threads 'under the hood' to handle heavy tasks:
  1. 1

    Libuv Thread Pool: Node.js uses a C++ library called libuv, which maintains a default pool of 4 background threads (configurable via UV_THREADPOOL_SIZE).

  2. 2

    Internal Tasks: These background threads handle intensive operations that would otherwise block the main thread, such as File System (I/O) operations, Cryptographic functions (e.g., hashing), Compression (Zlib), DNS lookups.

  3. 3

    V8 Engine Threads: The V8 engine itself uses separate threads for tasks like garbage collection.