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
- All your application's JavaScript code runs on a single main thread called the Event Loop.
- 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:
- 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).
- 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.
- V8 Engine Threads: The V8 engine itself uses separate threads for tasks like garbage collection.