Skip to content

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

  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. 5Streams and backpressureEach stage buffers up to its own mark; pipe() leaves a failure half-open, pipeline() tears the whole chain down.

Scaling and process lifecycle

  1. 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.
  2. 7Memory: the V8 heap, garbage collection, and leaksA server leaks what it stores per visit and forgets per ending; snapshots over time show it.
  3. 8Graceful shutdown on SIGTERMserver.close() only stops new connections; a graceful shutdown drains everything else before SIGKILL does.

Module systems

  1. 9ES modules vs CommonJSrequire hands you a parcel packed once; import gives you a window onto the exporter's own shelf.