
Is Node.js Single-Threaded?
โก๏ธ Yes AND No.
- JS execution: Single-threaded (via V8 Engine + Call Stack)
- Background tasks like
fs, crypto, dns: handled via libuv Thread Pool
libuv Thread Pool โ What & Why?
Libuv is C-based library in Node.js that manages:
- ๐ Event Loop
- ๐งต Thread Pool (Default size = 4 threads)
- ๐๏ธ I/O Operations like:
fs (file system)
crypto (e.g., password hashing)
dns.lookup
- Custom async operations
# You can customize thread pool size
process.env.UV_THREADPOOL_SIZE = 8;
Diagram Breakdown (from your image):
- V8 JS Engine
- Executes JS (Single-threaded)
- Manages call stack + memory heap
- libuv handles:
- Event loop
- Callback queue
- Thread pool (multi-threaded)
- Thread Pool
- Handles expensive I/O without blocking JS
- Each task goes to 1 of the 4 threads
- Once done โ pushes callback to queue โ JS thread picks it
๐งช Real Example: crypto.pbkdf2 using Thread Pool
const crypto = require("crypto");
console.time("hash");
for (let i = 0; i < 5; i++) {
crypto.pbkdf2("password", "salt", 100000, 64, "sha512", () => {
console.timeEnd("hash");
});
}