Node.js & Libuv Architecture Concepts
20 in-depth architectural topics from the 6-phase Libuv event loop to streams backpressure and V8 memory slabs.
Node.js Architecture: V8 Engine, C++ Bindings & Libuv
Node.js combines Google V8 (compiles JS to machine code) with Libuv (C library providing the cross-platform asynchronous event loop and thread pool).
The 6-Phase Libuv Event Loop (Timers, Poll, Check)
Each tick of the Libuv Event Loop processes 6 distinct phases: Timers -> Pending Callbacks -> Idle/Prepare -> Poll -> Check -> Close Callbacks.
Microtasks: process.nextTick vs Promise.then
Microtask queues are NOT part of Libuv; they are managed directly by Node.js. process.nextTick has higher priority than Promise microtasks, and both drain completely between every single event loop phase.
Libuv Thread Pool & UV_THREADPOOL_SIZE
Node.js is single-threaded for JS execution, but Libuv maintains a background C thread pool (default 4 threads) to handle synchronous OS tasks: file system (fs), cryptography (crypto), compression (zlib), and DNS lookups.
Streams & Backpressure with highWaterMark
Streams process data piece-by-piece in chunks without loading entire files into RAM. Backpressure occurs when a readable stream produces data faster than a writable stream can consume it.
Buffers, Binary Memory & The 8KB Slab Allocator
Buffers represent raw binary memory allocated outside the V8 JavaScript heap (using C++ malloc). Node.js uses an 8KB Slab Allocator to pre-allocate contiguous chunks for small buffer slices.
EventEmitter Internals & MaxListenersExceeded Warnings
EventEmitter is the cornerstone of Node.js networking and streams. Registering listeners without cleanup leads to silent memory leaks when objects retain closure references.
Clustering (Multi-Process) vs Worker Threads
Clustering creates multiple isolated OS processes sharing the same server port (multi-core horizontal scaling). Worker Threads run multiple V8 instances sharing the same process memory (via SharedArrayBuffer).
AsyncLocalStorage & Distributed Tracing Context
AsyncLocalStorage provides thread-local storage semantics across asynchronous execution chains, allowing correlation IDs and user contexts to propagate automatically without prop-drilling.
V8 Garbage Collection: Scavenger Minor GC & Mark-Sweep Major GC
V8 manages RAM via Generational Garbage Collection: Young Generation (Eden + Semi-Spaces From/To for fast Minor GC) and Old Generation (Mark-Sweep-Compact for long-lived objects).
ESM vs CommonJS Dual Package Hazard & Top-Level Await
Node.js supports both CommonJS (require/module.exports - synchronous) and ECMAScript Modules (import/export - asynchronous with static analysis and Top-Level Await).
Process Signals & Zero-Downtime Graceful Shutdown
Graceful shutdown intercepts OS termination signals (SIGINT, SIGTERM) to stop accepting new requests, close database pools, finish in-flight HTTP requests, and exit cleanly with code 0.