Beginner Node.js Interview QuestionsBeginnerConcept
Node.js · Question 3
Why is Node.js single-threaded?
Direct answer
JavaScript on the main thread is single-threaded by design — one call stack avoids locks and race conditions in user code; Node achieves concurrency via non-blocking I/O and libuv's thread pool, not one thread per request.
"Single-threaded" refers to your JavaScript, not the entire Node process — libuv uses a small worker thread pool (default 4) for file compression, crypto, and some DNS work behind the scenes.
| Main JS thread | libuv thread pool | |
|---|---|---|
| Runs | Your callbacks, Express handlers | Selected blocking OS tasks |
| Count | One for JavaScript | Default 4 (UV_THREADPOOL_SIZE) |
| You manage | Avoid long sync loops | Rarely — automatic for fs/crypto |
- Why one JS thread — simpler mental model; no mutexes in typical app code; great for thousands of idle connections.
- Cost of one thread — CPU-heavy JSON parse or bcrypt in a route blocks all clients until done (Q74).
- Scaling CPUs — cluster module (one process per core) or worker_threads for parallel JS (Q68–69).
blocking-trap.js
// BAD — blocks entire server for ~2 seconds
app.get("/hash", (req, res) => {
const start = Date.now();
while (Date.now() - start < 2000) {} // sync CPU loop
res.send("done");
});
// GOOD — offload or use async crypto
import { hash } from "node:crypto";
hash("sha256", data, () => res.send("hashed")); // uses thread pool