Node.js Internals
How Node.js works — V8 plus libuv, the non-blocking I/O model, the thread pool, event loop phases, streams and backpressure, buffers, worker threads, clustering, and diagnosing a blocked event loop.
Node.js is a JavaScript runtime for servers and tooling, built from V8 (executes JS) and libuv (a C library for asynchronous I/O and the event loop), plus core modules (fs, net, http, crypto…) that bind JavaScript to them. Its design bet: one thread running JavaScript, with all I/O non-blocking, can serve many thousands of concurrent connections efficiently.
Architecture
Non-blocking I/O
When you call fs.readFile or make an HTTP request, Node doesn't wait. It hands the operation to libuv and continues running JavaScript. When the result is ready, a callback is queued on the event loop.
How libuv achieves that depends on the operation:
| Operation | Mechanism |
|---|---|
| Network sockets (TCP, UDP, HTTP) | OS non-blocking APIs — epoll/kqueue/IOCP — monitored by the event loop itself. Thousands of sockets, no extra threads |
| File system | The libuv thread pool (OS file APIs are blocking on most platforms) |
DNS lookup (dns.lookup, used by http) | Thread pool (getaddrinfo is blocking) |
Crypto (pbkdf2, scrypt, randomBytes), zlib | Thread pool |
| Timers | Min-heap of timers checked by the loop |
The thread pool has 4 threads by default (UV_THREADPOOL_SIZE, up to 1024). If you start 100 concurrent scrypt hashes, only 4 run at a time — and file reads queue behind them.
The event loop phases
Each iteration ("tick") of libuv's loop runs these phases in order (The event loop):
- timers — expired
setTimeout/setIntervalcallbacks - pending callbacks — some deferred system callbacks
- idle, prepare — internal
- poll — wait for and run I/O callbacks (blocks here when there's nothing else to do)
- check —
setImmediatecallbacks - close callbacks —
'close'events
Between every callback, Node drains process.nextTick callbacks, then promise microtasks. The process exits when there's nothing left to wait for (no pending timers, sockets or handles).
Never block the event loop
Everything shares one JavaScript thread, so any slow synchronous work delays every request:
app.get("/report", (req, res) => {
const data = fs.readFileSync("big.json"); // blocks all requests during the read
const parsed = JSON.parse(data); // big JSON parse: blocks
const result = heavyComputation(parsed); // CPU-bound loop: blocks
res.json(result);
});Common culprits: *Sync APIs on request paths, huge JSON.parse/stringify, catastrophic-backtracking regular expressions (ReDoS), synchronous crypto, big loops over arrays.
Fixes: async APIs, streaming parsers, chunking work with setImmediate, moving CPU work to worker threads, or to another service.
Diagnose with perf_hooks.monitorEventLoopDelay(), node --cpu-prof, Clinic.js, or the --inspect DevTools profiler.
Streams and backpressure
Streams process data piece by piece instead of loading it all into memory. Four types: Readable, Writable, Duplex (both, like a socket), Transform (modify data passing through, like gzip).
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";
import { pipeline } from "node:stream/promises";
// Compress a 10 GB file with constant memory usage
await pipeline(
createReadStream("access.log"),
createGzip(),
createWriteStream("access.log.gz"),
);Backpressure: if the writable side is slower than the readable side, data would pile up in memory. write() returns false when the writable's internal buffer exceeds its highWaterMark; a well-behaved producer pauses until the 'drain' event. pipeline() (and pipe()) handle this automatically — and pipeline also propagates errors and destroys all streams on failure, so prefer it.
// Manual backpressure, for illustration
function writeMany(stream, lines) {
let i = 0;
(function writeMore() {
while (i < lines.length) {
if (!stream.write(lines[i++] + "\n")) {
stream.once("drain", writeMore); // wait until the buffer empties
return;
}
}
stream.end();
})();
}Streams are async iterables: for await (const chunk of readable) { ... }. Node also supports web-standard ReadableStream/WritableStream.
Buffers
Buffer is Node's fixed-size byte array (a Uint8Array subclass), allocated outside the V8 heap for binary data: files, network packets, crypto.
const buf = Buffer.from("héllo", "utf8"); // 6 bytes (é is 2 bytes in UTF-8)
buf.toString("base64"); // "aMOpbGxv"
Buffer.alloc(16); // zero-filled
Buffer.allocUnsafe(16); // faster, may contain old memory: overwrite before use!
Buffer.concat([a, b]);Using multiple cores
One Node process runs JavaScript on one core. Options to use more:
| Approach | What | Use for |
|---|---|---|
Worker threads (node:worker_threads) | Separate V8 isolates and event loops in the same process; communicate via messages, can share SharedArrayBuffer | CPU-heavy tasks: image processing, parsing, hashing |
Cluster (node:cluster) | Fork N processes that share a listening port | Scale an HTTP server across cores |
| Multiple processes behind a load balancer | PM2, containers, Kubernetes replicas | The usual production approach |
Child processes (node:child_process) | Run other programs | Shelling out to ffmpeg, git… |
// main.js
import { Worker } from "node:worker_threads";
const runHash = (input) => new Promise((resolve, reject) => {
const w = new Worker(new URL("./hash-worker.js", import.meta.url), { workerData: input });
w.once("message", resolve);
w.once("error", reject);
});
// hash-worker.js
import { parentPort, workerData } from "node:worker_threads";
parentPort.postMessage(expensiveHash(workerData));In production, use a worker pool (Piscina) rather than a new worker per task.
Other internals worth knowing
- Module loading: CJS
requireis synchronous and cached; ESM loads asynchronously (Modules). - EventEmitter: the observer implementation behind streams, servers and sockets. Emitting is synchronous. An
'error'event with no listener crashes the process. - Error handling: uncaught exceptions and unhandled promise rejections terminate the process by default. Log, then let a supervisor restart it — don't keep running in an unknown state.
- Memory: V8 heap limits apply (
--max-old-space-size); Buffers and native addons use memory outside the heap (process.memoryUsage()showsexternalandarrayBuffers). - Graceful shutdown: on SIGTERM, stop accepting connections (
server.close()), finish in-flight requests, close DB pools, then exit.
- Node = V8 + libuv + core modules; JavaScript runs on one thread.
- Network I/O uses OS readiness APIs; file system, DNS lookup, crypto and zlib use a 4-thread pool.
- Event loop phases: timers → poll → check → close, with nextTick and microtasks between callbacks.
- Never block the loop: avoid Sync APIs, giant parses and CPU loops on request paths.
- Streams process data incrementally; pipeline() handles backpressure and errors.
- Scale across cores with worker threads (CPU work) and multiple processes (servers).
QNode.js is single-threaded — how does it handle many concurrent requests?medium
Only JavaScript execution is single-threaded. I/O is non-blocking: network sockets are monitored by the OS's event notification APIs through libuv, and blocking operations like file access and some crypto run on libuv's thread pool. While waiting, the main thread processes other events. Because typical web requests spend most of their time waiting on I/O, one thread can interleave thousands of them — as long as no callback does heavy synchronous work.
QWhat is backpressure in streams?medium
When a producer writes data faster than a consumer can process it, buffered data grows without bound. Node signals backpressure when write() returns false because the writable's buffer exceeds its highWaterMark; the producer should pause until the 'drain' event. pipe() and stream.pipeline() implement this automatically by pausing and resuming the readable.