Node.js runtime internals
Node.js internals: event loop phases, nextTick vs microtasks, the thread pool, blocking, streams, scaling, memory, graceful shutdown and module systems.
9 lessons
The event loop
- 1Event loop phases (libuv): timers, poll, check, closeThe loop is a fixed round of phases; what runs next depends on which phase you are in now, not on a delay of 0.
- 2process.nextTick vs promise microtasks, and starvationnextTick is not the next loop turn: Node empties the tick queue, then the promise queue, again and again, before the loop moves on.
- 3The libuv thread pool: fs, dns.lookup, crypto, zlibThe pool is a short crew behind one long queue, and a host name is a ticket in that queue.
- 4Blocking the event loop: CPU work, sync APIs, ReDoS, and measuring itWhile one callback computes, the whole process waits: nothing is refused, nothing runs, and everything arrives late.
Data flow
Scaling and process lifecycle
- 6Worker threads vs cluster vs horizontal scalingProcesses share only the port, threads share only what you hand them, and the libuv pool is one fixed crew per process.
- 7Memory: the V8 heap, garbage collection, and leaksA server leaks what it stores per visit and forgets per ending; snapshots over time show it.
- 8Graceful shutdown on SIGTERMserver.close() only stops new connections; a graceful shutdown drains everything else before SIGKILL does.