Chapter 7 — The Node Event Loop, libuv & the Async Model Truly Explained
Part II · The Node.js Runtime | Prerequisites: Ch 4 | Builds: the precise mechanics of how Node runs your async code
Earlier you saw the general shape of concurrency: the difference between readiness and completion models, why blocking on I/O wastes a thread, and how a single thread can shepherd thousands of connections by never sitting idle on a slow syscall. That treatment was deliberately runtime-agnostic — it gave you the theory of the event loop as a pattern, the same pattern that powers Nginx, Redis, Netty, and Go's network poller. This chapter takes that pattern and makes it Node-specific and concrete: the exact threads your code runs on, the exact order in which your callbacks fire, the exact reason one bad handler can take an entire process to its knees. By the end you will be able to read a snippet mixing setTimeout, setImmediate, Promise.then, and process.nextTick and predict its output line by line — and, far more importantly, you'll be able to look at a production latency graph and say "that's loop lag, not CPU, not the database" and be right.
This is a mechanics chapter. There is more code here than usual, because the whole point is to kill the magic by showing the moving parts. But the goal is not trivia — every mechanism we open exists to answer two operational questions you will ask for the rest of your Node career: which thread is this running on? and is this yielding control, or hogging it?
1. The problem: why "non-blocking" is a half-truth
Let me start where you'll actually meet this: a 2 a.m. page.
Pulsely's /panel endpoint — the provider's patient panel, risk-stratified so the sickest patients float to the top — is normally a 40 ms call. Tonight, under nothing more than a modest bump — a new clinic onboarded that morning, a few thousand extra patients spread across the panels — its p99 climbs to 4 seconds. The dashboards are baffling. CPU on the box reads 100%… but only on one core. The other seven sit at near-zero, idle, bored. Memory is fine. The database is fast — its slow-query log is empty. And then the cruelest symptom of all: the orchestrator's health check, a trivial GET /healthz that does nothing but return { ok: true }, starts timing out. Kubernetes concludes the pod is dead and kills it. The replacement comes up, takes the same traffic, and dies the same way. You are now in a restart loop, shedding load, during your busiest clinic hours.
Two things about this incident should bother you, because they contradict the marketing.
First: every request slowed down at once. Not just /panel. The login endpoint, the eligibility poller, the do-nothing health check — all of them degraded in lockstep, as if they shared a single bottleneck. They do. Hold that thought.
Second: seven cores sat idle while one was pinned. Node was handed an eight-core machine and used one-eighth of it. That is not a bug in your code; it is the defining fact of the runtime. And nobody told you, because the brochure said "Node is non-blocking and fast."
Here is the correction that unlocks everything: "non-blocking" describes I/O, not computation. Node gives you concurrency for I/O for free — ten thousand idle sockets cost almost nothing because waiting on them happens in the kernel, not in your thread. But Node gives you zero concurrency for CPU work by default. Your JavaScript runs on exactly one thread. The instant a handler does real computation — risk-stratifying a panel, parsing a giant JSON body, hashing a password synchronously, running a pathological regex — that one thread is busy, and while it is busy it cannot run anyone else's callback, cannot accept a new connection, cannot answer the health check. One handler's CPU burst is everyone's outage — every clinic on that pod, mid-visit.
This is the trap that catches developers pivoting from a thread-per-request world. In classic Java/Spring, each request gets its own thread from a pool of two hundred; if one request spends a second doing math, it spins its own thread and the other 199 keep serving. In Go, a goroutine that computes hard is scheduled across all your cores. So when those developers arrive at Node and read await rankPanel(patients), the word await feels like "this runs elsewhere and I'll get the result back." It does not. await is not a thread switch. If rankPanel is synchronous CPU work, awaiting it changes nothing about where it runs — it runs on your one thread, and it blocks the loop exactly as if you'd never written await.
🧭 Mental model. Node hands you concurrency for waiting and charges you full price for thinking. Idle connections are nearly free; busy computation is strictly serial on one thread. Most of operating Node well is keeping the "thinking" short so the "waiting" can scale.
So the framing for the whole chapter: to operate Node you must always know which thread your code runs on and what yields control versus what hogs it. Everything that follows — the loop phases, the microtask queue, libuv's thread pool, the cardinal sin of blocking — is an answer to those two questions.
2. The mental model: one waiter, a kitchen, and two notebooks
Before any phases or queues, install the picture. Three pieces.
One thread runs your JavaScript. Call it the main thread, the loop thread, the JS thread — same thing. Every line of your application code, every callback, every .then, every await resumption, executes here, one at a time, in some order we'll make precise. There is no second thread running your JS in parallel. This is the source of both Node's greatest simplicity and its sharpest failure mode.
An event-driven loop feeds that thread work. The thread doesn't sit and poll. It runs whatever JS is ready, and when there's nothing ready to run, it sleeps — efficiently, in a single OS syscall — until the kernel says "a socket has data" or "a timer is due." Then it wakes, runs the callbacks that just became ready, and goes back to sleep. That wake-run-sleep cycle is the event loop.
A small pool of background threads does the blocking work the main thread can't. Some operations have no non-blocking kernel API — reading a file, hashing with pbkdf2, gzipping a buffer, certain DNS lookups. For these, Node keeps a handful of worker threads (four, by default) and offloads the blocking syscall to one of them, so the main thread never parks. This pool is part of libuv, the C library underneath Node, and we'll name exactly what uses it later.
Now the analogy — and I'll use it precisely, because a sloppy analogy here teaches the wrong instincts.
Picture a restaurant with one waiter (the main thread). The waiter takes orders, carries plates, runs the bill — all the customer-facing work. Crucially, the waiter never stands at a table waiting for the food to cook. He takes your order, fires it to the kitchen, and immediately serves the next table. When a dish is ready, the kitchen rings a bell; the waiter, between other tasks, grabs it and delivers it. This is how one waiter serves a packed dining room: he is never blocked waiting; he's only ever doing or briefly idle.
The kitchen is two things working together: the OS kernel (for network I/O — it'll ring the bell when a socket is readable) and the libuv worker pool (for the blocking jobs — reading a file off disk, hashing a password). The waiter delegates and moves on.
And here is the failure mode the analogy makes obvious: what happens if the waiter starts chopping vegetables himself? If a customer's order requires the waiter to personally stand at the counter and dice onions for thirty seconds — that's CPU work on the main thread — then every other table waits. The kitchen could be idle, other dishes ready and ringing, new customers at the door — none of it matters, because the one waiter is heads-down chopping. That is your /panel incident. The fix is never "make the waiter chop faster"; it's "get the chopping off the waiter."
Finally, two distinct queues you must keep separate in your head from the start — think of them as the waiter's two notebooks:
- A "do this later, when something is ready" notebook — timers that are due, I/O callbacks for sockets that got data. These are macrotasks, and the loop works through them phase by phase.
- A "do this the instant I finish what I'm holding" notebook — Promise reactions, things scheduled to run before the waiter so much as glances at the next table. These are microtasks, and they're drained completely between every other thing.
Confusing these two is the source of nearly every "why did my code run in that order?" surprise. We'll make the distinction exact in §3 and §4.
🧭 Mental model. Your code is a guest on the loop, and the rule of the house is: always give the loop its turn back. Nothing preempts you — no timer, no signal, no other callback interrupts a running function. You run to completion or to an
await, and only then does control return to the loop. Cooperative, not preemptive. The loop's health depends entirely on your good manners.
📎 Borrowed on credit: the event-loop pattern is universal. What you're learning is not a Node quirk. Multiplexing many connections over few threads by never blocking on I/O is the same engine inside Nginx, Redis, HAProxy, Netty, and Go's runtime. Node is one instance of a deep pattern, which is why the intuitions transfer. We name this here so you don't over-index on Node-specific syntax; the shape is the transferable asset. (Ch 4 developed the general theory and the C10k motivation — we won't re-derive it.)
3. Theory & invariants
A mental model tells you how to picture the loop. Invariants tell you what is guaranteed — the rules you can build predictions on. There are a handful, and they're worth memorizing because production debugging is mostly applying them in reverse.
🔑 The run-to-completion invariant. Once a JavaScript callback starts running, it runs uninterrupted until it returns or hits an
await. No other JavaScript executes concurrently in the same loop — not a timer, not an I/O callback, not another request's handler. Nothing.
This single guarantee is Node's defining tradeoff, and it cuts both ways. The upside is enormous: your in-process shared state is data-race-free by construction. Two requests incrementing a shared counter, mutating a shared cache, pushing to a shared array — none of them can interleave mid-statement, because only one runs at a time and it finishes before the next begins.
It's worth pausing on what this saves you from, because if you've only ever written React/TypeScript you've never had to live with it. In multi-threaded runtimes, two threads touching the same variable at the same moment can leave it half-updated — a torn read — or apply their changes in an order neither expected, which is why such code has to wrap shared data in locks. In Node, because only one piece of your code ever runs at a time, that entire class of bug simply cannot happen: you will never write a lock, a mutex, or a volatile for in-memory state, and you will never debug a torn read. (Optional aside for JVM refugees, skip if it's not your world: contrast this with the JVM, where every shared mutable field is a potential race and the Java Memory Model is required reading — Node hands you that safety for free.)
The downside is the mirror image: because a callback runs to completion with nothing able to interrupt it, a callback that never yields starves every other callback forever. The same property that frees you from locks is the property that lets one while(true) freeze the process. There is no preemptive scheduler to rescue you.
🔑 The microtask-drain invariant. The microtask queue is drained completely to empty before the loop does anything else — before it advances to the next loop phase, before it picks up the next I/O event, after every single macrotask callback. Promise reactions don't wait for "the next tick"; they run at the first available gap, which is immediately.
Concretely: when a callback finishes, the loop does not move on to the next timer or socket. It first asks "are there any microtasks?" and runs them all — and if those microtasks schedule more microtasks, it runs those too, and keeps going until the microtask queue is genuinely empty. Only then does the macrotask machinery advance. This is why Promise.resolve().then(...) always runs before a setTimeout(..., 0) you scheduled in the same breath: the promise reaction is a microtask, drained before the loop ever reaches the timers phase. And it's the seed of a real failure mode — a function that recursively schedules microtasks (Promise.resolve().then(loop) calling itself) can hold the loop hostage indefinitely, because the drain never completes and the loop never advances to run timers or I/O.
Now the vocabulary you must own, because senior conversations assume it:
- Macrotask (often just task): a unit the loop schedules in a phase — a due timer callback, an I/O completion callback, a
setImmediatecallback. The loop runs one macrotask, drains microtasks, runs the next macrotask, and so on. - Microtask: a Promise reaction (
.then/.catch/.finally, anasyncfunction's resumption afterawait) or aqueueMicrotaskcallback. Drained to empty between macrotasks. process.nextTick: Node's own special queue, which is not the Promise microtask queue and is not a macrotask. It has its own slot and — this is the gotcha — it drains before the Promise microtask queue. So within one "between-callbacks" gap, the order is: allnextTickcallbacks first, then all Promise microtasks, and only then back to the loop.
🔑 The phase-ordering guarantee (and its limits). Within one turn of the loop, phases run in a fixed order, and callbacks within a single phase run FIFO — first registered, first run. What you may not rely on is deterministic ordering across phases for things scheduled from the top level. The canonical trap involves
setTimeout(fn, 0)versussetImmediate(fn). Called from your main module, their relative order is non-deterministic: it's a coin flip that depends on whether the ~1 ms timer clamp has elapsed by the time the loop first checks its timers. But make the same two calls inside an I/O callback and the order becomes deterministic —setImmediatealways wins there. The reason: inside an I/O callback the loop is already past the timers stage for this lap, so the next stage it reaches ischeck, which is exactly wheresetImmediatelives. (We draw the full lap of stages in §4 — if that reasoning feels abstract now, it will click once you can see the wheel.) If your test's correctness depends on that ordering, your code has a latent bug.
🔑 Liveness, not fairness. The loop guarantees progress — it will keep doing work as long as work exists — but it does not guarantee fairness. A relentless stream of
process.nextTickor microtask scheduling can indefinitely defer timers and I/O callbacks, and the spec permits this. Starvation is a legal state. The loop isn't broken when it happens; you broke the contract by never yielding.
The vocabulary to walk away with and use without hesitation: tick (one iteration of the loop), phase (a stage within a tick), task vs. microtask (macro queue vs. drained-between queue), starvation (one queue indefinitely deferring another), loop lag / loop delay (how late a callback fires versus when it should have), blocking (occupying the main thread so it can't yield), yielding (returning control to the loop, via return or await or a deliberate setImmediate).
4. Under the hood: V8, the phases, and what actually runs where
Now we open the box. This is the longest beat, by design — it's where the magic dies.
V8 and the JIT, just enough
Node is V8 (Google's JavaScript engine, the part that runs your JS) plus libuv (the C library that provides the loop and the I/O, the part that does your waiting) plus the bindings that glue them. Start with V8.
V8 doesn't interpret your JavaScript line by line forever. It parses your source to bytecode and runs it on a fast interpreter called Ignition. Functions that get called a lot — "hot" functions — get promoted: an optimizing compiler called TurboFan compiles them to specialized machine code under a set of assumptions it observed (this variable is always a small integer, this object always has these fields in this order — its "hidden class"). As long as the assumptions hold, the function runs at near-native speed.
When the assumptions break — you suddenly pass a string where it always saw a number, you add a property that changes an object's hidden class — V8 deoptimizes: it throws away the optimized code and falls back to the interpreter, possibly re-optimizing later.
Two words carry this whole lesson, so let's ground them plainly before the payoff. A function is monomorphic when you always call it with the same shape of argument — always a number, or always an object with the same keys in the same order. It's polymorphic when you sometimes pass a number, sometimes a string, sometimes a differently-shaped object. (That "shape" V8 tracks internally is the hidden class — its fingerprint of an object's fields and their order.) The frontend analogy is close: think of a React component that re-renders fast when its props keep a stable shape and janks when the shape keeps churning. V8 optimizes hard for the stable shape and throws that optimization away — deoptimizes — the moment the shape varies.
Why should you, a backend engineer, care? Because a deopt in a hot handler silently raises CPU, and on Node, raised CPU on the main thread is loop lag, which is everyone's latency. A handler that was fast in your benchmark (monomorphic, well-optimized) can quietly get slower in production when real-world inputs make it polymorphic. You won't see an error; you'll see p99 creep. Keep hot paths type-stable.
And then there's garbage collection, which matters here for one reason that tutorials skip: V8's GC pauses run on the main thread, and they count as loop lag. When V8 stops the world to collect, your loop is not running callbacks — it's collecting garbage. A high allocation rate (allocating lots of short-lived objects per request) means frequent young-generation collections; a large live heap means longer, rarer old-generation pauses. Either way, GC shows up in your latency graph as a tail, not as a memory number. So "reduce per-request allocation" is a latency optimization in Node, not merely a memory one. (The heap layout, generational GC, and how to find the allocation pressure are Ch 8's territory — here we just nail down why GC is loop lag.)
The architecture stack
Here is the whole runtime in one picture. Memorize the routing — what bypasses the pool and what goes through it is the single most misunderstood thing about Node.
┌───────────────────────────────────────────────────────┐
│ YOUR JS APPLICATION │
└────────────────── ─────────────────────────────────────┘
│ runs on
▼
┌──────────────────────┐ ┌────────────────────────────────┐
│ V8 │ │ libuv │
│ (executes your JS, │◀────────▶│ • the event loop (phases) │
│ JIT, GC — ONE │ bindings │ • worker thread pool (def. 4) │
│ main thread) │ │ • cross-platform async I/O │
└──────────────────────┘ └───────────────┬────────────────┘
│
┌───────────────────────────────────┼───────────────────────────┐
│ │ │
NETWORK I/O (no pool!) FILESYSTEM / CPU-ish (everything
sockets: TCP/UDP/HTTP fs.*, dns.lookup, libuv can do
│ crypto, zlib async in-kernel
▼ ▼ goes left)
┌───────────────────┐ ┌───────────────────┐
│ OS multiplexer │ │ libuv 4-thread │
│ epoll/kqueue/IOCP │ │ WORKER POOL │
└───────────────────┘ └───────────────────┘
The headline: network I/O does not use the thread pool. Sockets are handled by the OS's event multiplexer — epoll on Linux, kqueue on BSD/macOS, IOCP on Windows — which the kernel makes genuinely non-blocking. Ten thousand concurrent connections cost you essentially no threads. The pool is for the other stuff, the operations the OS has no good async API for. Conflating these two is the most common Node misconception in interviews and incident reviews alike.
The six phases, walked
One turn of the loop — one tick — runs through a fixed sequence of phases. Each phase has its own queue of callbacks. Here's the wheel:
┌───────────────────────────────────────────────────────────────┐
│ ONE TICK OF THE LOOP │
│ │
│ ┌──────────┐ │
┌───▶│ TIMERS │ setTimeout / setInterval callbacks now due │
│ └────┬─────┘ │
│ │ ← drain nextTick queue, then microtask queue │
│ ┌────▼──────────────┐ │
│ │ PENDING CALLBACKS │ deferred system/TCP errors │
│ └────┬──────────────┘ │
│ │ ← drain nextTick, then microtasks │
│ ┌────▼─────────────┐ │
│ │ IDLE / PREPARE │ internal libuv bookkeeping (not yours) │
│ └────┬─────────────┘ │
│ ┌────▼─────┐ │
│ │ POLL │ THE HEART: wait for I/O, run I/O callbacks, │
│ └────┬─────┘ decide how long to block (until next timer / fd) │
│ │ ← drain nextTick, then microtasks │
│ ┌────▼─────┐ │
│ │ CHECK │ setImmediate callbacks │
│ └────┬─────┘ │
│ │ ← drain nextTick, then microtasks │
│ ┌────▼─────┐ │
│ │ CLOSE │ 'close' handlers (socket.destroy, etc.) │
│ └────┬─────┘ │
│ └──────────────── loop back to TIMERS ──────────────────────┘
└──── (if nothing left to do anywhere, the process exits)
Phase by phase:
- Timers. Runs the callbacks of any
setTimeout/setIntervalwhose delay has elapsed. "Elapsed" is checked against the clock when this phase runs — which is whysetTimeout(fn, 0)doesn't run immediately, it runs no earlier than the next time the loop reaches this phase, and the delay is clamped to a minimum (about 1 ms) by the runtime. - Pending callbacks. Runs certain deferred system-level callbacks — some TCP error callbacks, for instance — that the OS handed back for next-tick delivery. You rarely think about this phase directly.
- Idle / prepare. Internal libuv housekeeping. Not yours; named for completeness so the wheel has no mystery gaps.
- Poll — the heart. This is where the loop spends most of its life. Two jobs: run the callbacks for I/O that has completed (a socket got data, a file read finished and its result came back from the pool), and — when there's nothing immediately ready — block, efficiently, on the OS multiplexer until either a file descriptor becomes ready or the nearest timer is about to come due. This blocking is the good kind: the process is genuinely asleep, consuming no CPU, parked in a single
epoll_wait-style syscall. This is how an idle Node process serving ten thousand open-but-quiet connections uses ~0% CPU. The poll phase is also where the loop decides how long to sleep: just long enough that it wakes for the next due timer. - Check. Runs
setImmediatecallbacks. The whole reasonsetImmediateexists is to give you a "run right after poll, before the next round of timers" slot — useful for "yield to any pending I/O, then continue." - Close. Runs
'close'event handlers — cleanup when a socket or handle is destroyed.
Now the part the phase wheel by itself doesn't show, and the part that trips everyone up:
🔑 Microtasks (and
nextTick) drain between every callback — not just at phase boundaries. After each individual macrotask callback completes, the loop drains the entireprocess.nextTickqueue, then the entire Promise microtask queue, before running the next macrotask in that phase or advancing to the next phase. So microtasks are not "end of tick" — they're "after literally every callback." This is why a Promise chain can resolve fully before the next timer fires, even if the timer was due.
A worked trace — predict the output
Here is the snippet every Node interview eventually asks about. Read it, predict the exact output, then check yourself. This is the single best exercise for proving you understand the queues.
console.log('1: sync start');
setTimeout(() => console.log('2: setTimeout 0'), 0);
setImmediate(() => console.log('3: setImmediate'));
Promise.resolve().then(() => console.log('4: promise then'));
process.nextTick(() => console.log('5: nextTick'));
console.log('6: sync end');
The output:
1: sync start
6: sync end
5: nextTick
4: promise then
2: setTimeout 0 ⎫ order of these two from the MAIN MODULE
3: setImmediate ⎬ is NOT guaranteed — may swap run to run
Walk it, because every line has a reason:
1and6are synchronous — they run immediately, top to bottom, as the main module executes. Nothing async happens until the current run-to-completion finishes. So1then6, always.- The main module's synchronous run is now done. Before the loop advances to any phase, it drains its between-callback queues.
nextTickdrains first →5. Then the Promise microtask queue →4. (This ordering —nextTickbefore Promises — is a fixed Node rule.) - Now the loop enters its phases.
2(a duesetTimeout) is a timers-phase macrotask;3(setImmediate) is a check-phase macrotask. From the top-level module, which of these fires first is non-deterministic — it depends on whether ~1 ms of clamp has elapsed by the time the loop reaches the timers phase. Move these same two calls inside afs.readFilecallback and3would deterministically beat2, because you'd already be past timers and the very next phase is check.
If you can narrate that, you understand the loop better than most people shipping Node to production. The lesson isn't the exact output — it's the reasoning: sync first, then nextTick, then Promise microtasks, then macrotasks in phase order, with microtasks re-drained between each.
The desugaring ladder: callbacks → Promises → async/await
Async/await is not a new concurrency mechanism. It is syntax over Promises, which are objects over callbacks. Seeing the three as one thing — the same machine in three costumes — is what lets you reason about ordering. Here is one operation, reading a patient's chart from disk, rewritten up the ladder:
// Rung 1: error-first callback — the original Node convention.
// Note the (err, value) shape: errors are a first argument, not thrown.
fs.readFile('chart.json', (err, buf) => {
if (err) return handle(err);
use(buf);
});
// Rung 2: Promise — a state machine object (pending → fulfilled/rejected).
// .then schedules a MICROTASK that runs when the promise settles.
fs.promises.readFile('chart.json')
.then(buf => use(buf))
.catch(err => handle(err));
// Rung 3: async/await — pure syntactic sugar over Rung 2.
async function loadChart() {
try {
const buf = await fs.promises.readFile('chart.json');
use(buf);
} catch (err) {
handle(err);
}
}
Three facts about Rung 3 that you must hold as load-bearing, because they're the source of most async confusion:
- An
asyncfunction always returns a Promise. Evenasync function f() { return 1; }returns aPromise<number>, not anumber. Thereturnvalue becomes the fulfillment value. await xis a suspension point, not a thread switch. It pauses this function, lets the rest of the current synchronous code run to completion, and schedules the function's resumption as a microtask that fires whenxsettles. The thread does not change. Nothing runs in parallel.await≈ "register the rest of this function as a.thenand return control to the loop."awaiton a CPU-bound synchronous value buys you nothing.await rankPanel(patients)whererankPanelis a synchronous function still runsrankPanelsynchronously, on the main thread, blocking the loop.awaitonly yields when the thing you await is actually asynchronous (a real I/O Promise). Awaiting computation does not offload computation. This is the precise mechanism behind the §1 trap.
So when you write a tidy async/await handler, picture the desugared reality: a sequence of synchronous bursts separated by microtask-scheduled resumptions, all on one thread. The awaits are the only places control returns to the loop. Between two awaits, you own the thread completely — for better (no races) and worse (no yielding).
What's truly async vs. what uses the pool
Pin this down, because it determines where your work actually runs and which resource it can exhaust:
- Genuinely async at the kernel level — no pool, no threads: all network I/O. TCP, UDP, HTTP/HTTPS sockets, handled by
epoll/kqueue/IOCP. This is why Node scales to enormous connection counts: network waiting is free. The pool is not involved in network I/O. If you remember one sentence from this section, that's it. - Uses the libuv worker pool — because the OS has no good async API:
fs.*— most filesystem operations (read, write, stat, …).dns.lookup— uses the operating system's own name-resolution call (getaddrinfo— the same lookup path your OS uses for everything), and that call has no async version, so Node has to run it on a pool thread. Its siblingdns.resolve*skips the OS entirely and sends a DNS query over the network itself, which is ordinary non-blocking network I/O — so it never touches the pool. Same-looking API, opposite resource. This distinction bites people.crypto—pbkdf2,scrypt,randomBytes, and similar.zlib— gzip/deflate compression and decompression.
The pool's default size is 4 (UV_THREADPOOL_SIZE). That number is small, fixed, and process-wide, and it is the source of a whole class of confusing incidents we'll meet in §5: when you have more concurrent pool-bound operations than pool threads, they queue, and latency climbs even though CPU isn't maxed — because the work is waiting for a free pool thread, not for the CPU. An eight-core box with UV_THREADPOOL_SIZE=4 can serialize your crypto calls four at a time regardless of how many cores sit idle.
The JVM contrast, where it teaches
It's worth one paragraph to see the road not taken, because it sharpens why Node behaves as it does. (This is a skippable aside if the JVM isn't your world — the transferable payoff is the last sentence.)
Classic Java/Spring MVC is thread-per-request: a Tomcat connector pool of, say, 200 threads, each one handling a single request start to finish, and blocking I/O is fine — when a thread blocks on a JDBC query, the OS parks it and schedules another. The mental model is dead simple (write straight-line blocking code; the platform parallelizes by giving you more threads) and CPU work doesn't poison the world (one busy thread, 199 others still serving). The cost is the threads themselves: each platform thread carries ~1 MB of stack and real kernel scheduling overhead, so "a few thousand" is the practical ceiling, and at high concurrency you spend real money on context switches. Node made the opposite bet — one thread, never block it, multiplex everything — trading the simple blocking model for the ability to hold vastly more concurrent connections cheaply.
And the punchline that proves the event loop is a pattern, not a Node accident: the JVM is converging on the same idea. Netty runs an event loop exactly like Node's for high-concurrency network servers. Project Loom's virtual threads make blocking cheap — millions of user-mode threads multiplexed onto a few carriers, where a "blocking" call yields the carrier instead of parking an OS thread — which is the JVM importing the event loop's efficiency while keeping the synchronous programming model. Same destination (many connections, few OS threads), different road. You'll weigh that tradeoff explicitly in Chapter 9; here, just register that Node's model is one valid point on a spectrum, not a magic trick.
🛑 What we deliberately did not explain. How streams and backpressure ride on top of these I/O callbacks; how
worker_threadsandclusteractually parallelize across cores; how to read a flamegraph or driveclinic.jsto attribute a stall; how V8 lays out the heap and how you hunt a leak. Those are Chapter 8. We namedworker_threadsandclusteras escape hatches and will name them again in §5 and §7, but their machinery is the next chapter's job, not this one's.
5. In production: measuring the loop and tuning the pool
Theory predicts ordering. Production is about seeing the loop's health and acting before the pager does. The whole game reduces to one metric and a couple of knobs.
Measure loop lag — the earliest warning you'll ever get
The canonical signal that the loop is in trouble is event-loop delay (loop lag): how much later a scheduled callback actually fires than it was supposed to. At a healthy idle, this is sub-millisecond. When a handler hogs the thread, it spikes — and it spikes before CPU alarms and before user-visible latency alarms, because it's measuring the cause, not the symptom.
The real tool is perf_hooks.monitorEventLoopDelay(), which gives you a histogram (mean, percentiles, max) sampled by the runtime itself:
const { monitorEventLoopDelay } = require('node:perf_hooks');
const h = monitorEventLoopDelay({ resolution: 20 }); // sample every 20 ms
h.enable();
// expose on /metrics, scrape with Prometheus, alert on p99
function loopLagMillis() {
return {
mean: h.mean / 1e6, // histogram is in nanoseconds
p50: h.percentile(50) / 1e6,
p99: h.percentile(99) / 1e6,
max: h.max / 1e6,
};
}
There's a cheap homegrown version — schedule a setInterval(fn, 100) and measure how late each fire is versus the expected 100 ms — and it's fine for a quick smell test, but know that it under-reports: its own callback is a macrotask, so it can only observe lag at its sampling cadence and misses sub-interval stalls. Use monitorEventLoopDelay for anything you'll alert on; it samples at high resolution inside the runtime.
What "good" looks like, as operating thresholds:
- Mean loop delay sub-millisecond at idle. If your idle mean is already milliseconds, something is doing periodic work it shouldn't.
- p99 over ~50–100 ms = a handler is doing too much on the thread. That's your alert threshold for "someone is blocking the loop." Tune to your latency budget.
- Wire loop lag into the health check, not just CPU%. This is the subtle one. Your
/healthzand your real handlers share the same loop, so a saturated loop makes the health check itself slow — which, as in §1, gets your healthy process killed. Reporting loop lag as a metric (and optionally failing readiness above a threshold deliberately, with hysteresis) is far better than the orchestrator inferring death from a timed-out probe. CPU% lies here: it'll read 100% on one core and look "normal" on a multi-core average. Loop lag tells the truth.
Tune UV_THREADPOOL_SIZE — and know when it's the answer
The pool's default of 4 is conservative. Raise it when your service does heavy concurrent pool-bound work — lots of simultaneous fs operations, crypto hashing, zlib compression, or dns.lookup. Two rules and a gotcha:
- It must be set before the loop starts. It's read once at startup. Set it as an environment variable (
UV_THREADPOOL_SIZE=16 node server.js) or assignprocess.env.UV_THREADPOOL_SIZEat the very top of your entry file before anything touches the pool. Setting it late does nothing. - It's process-wide, not per-request or per-module. One number for the whole process.
- Size it to the nature of the work. For CPU-bound pool work (
crypto,zlib), more pool threads than CPU cores just oversubscribes the cores and adds context-switch cost — bound it near your core count. For I/O-bound pool work (fswaiting on a slow disk or network filesystem), you can go higher, because those threads spend their time blocked, not computing.
🏭 Diagnosing "which exhaustion?" Here's the tell that catches people: latency climbs, requests pile up, and CPU is not maxed. That is the signature of a saturated pool, not a CPU shortage. Your async
fs/cryptocalls are queueing for one of four pool threads while the cores sit idle. The fix is to raiseUV_THREADPOOL_SIZE(or reduce concurrent pool ops), not to add cores — adding cores does nothing for a 4-thread bottleneck. Contrast: if one core is pinned and loop lag is in seconds, that's the main thread blocked on CPU, and the fix is to get the work off the loop (next paragraph). Same "latency went up," opposite root cause, opposite fix. Distinguishing them is a senior skill.
Getting CPU work off the loop (named, deferred)
When the problem is genuinely main-thread CPU — the §1 /panel risk-stratification — you have a menu, which I'll name now and we'll build in depth in Chapter 8:
worker_threads— in-process parallelism on another thread. Best when you must keep the work in-process and share memory cheaply.- A separate process / service (
child_process, or a dedicated microservice) — isolation and independent scaling, at the cost of network/serialization overhead. - Chunking with
setImmediate— for work that can be broken into pieces, do a batch,setImmediateto yield to the loop, do the next batch. This keeps the loop breathing without leaving the process. It's the cheapest fix and often enough.
The decision criterion, stated now and justified later: chunk when the work is divisible and not enormous; reach for a worker or separate process when it's a big, indivisible CPU burst.
🏭 One loop = one core. A single Node process uses exactly one core for your JS, full stop. The loop does not auto-parallelize across cores. To use an eight-core box you run N processes —
cluster, or (more commonly today) N containers/replicas behind a load balancer, one Node per pod. This is the operational reality tutorials skip: scaling Node horizontally means more processes, not bigger machines. (Pool-sizing and full performance work belong to Chapter 30; the deep profiling toolchain —--cpu-profflamegraphs,clinic.js— is Chapter 8. We name them here; we don't open them.)
📎 Borrowed on credit: streams and backpressure. Everything in this chapter assumes work arrives in bounded chunks. The moment a response is large — a multi-gigabyte export of a payer's remittance file, say — you must stream it under backpressure or you'll OOM the process, and streaming is itself a discipline layered on these same I/O callbacks. That's Chapter 8. Flagged so you don't mistake "the loop handles I/O efficiently" for "you can buffer anything."
The Pulsely increment
Time to feel all of this rather than just read it. Rebuild Pulsely's clinical service directly on Node's http module — no Express yet (that's Chapter 13), because frameworks hide exactly the mechanics we're studying. Three endpoints, deliberately chosen to exercise the three behaviors:
const http = require('node:http');
const fs = require('node:fs/promises');
const { monitorEventLoopDelay } = require('node:perf_hooks');
const lag = monitorEventLoopDelay({ resolution: 20 });
lag.enable();
// CPU-bound stub: a synthetic risk-stratification burst. This BLOCKS the loop.
function rankPanel(patients) {
let score = 0;
for (let i = 0; i < 30_000_000; i++) score += Math.sqrt(i % 7); // pure CPU, no yield
return score;
}
const server = http.createServer(async (req, res) => {
if (req.url === '/panel') {
const score = rankPanel([]); // ← hogs the one thread for ~hundreds of ms
res.end(JSON.stringify({ score }));
} else if (req.url?.startsWith('/patient/')) {
const data = await fs.readFile('chart.json'); // ← real async I/O via the pool
res.end(data);
} else if (req.url === '/healthz') {
res.end('{"ok":true}'); // ← trivial; should always be instant
} else if (req.url === '/metrics') {
res.end(JSON.stringify({
loop_lag_p50_ms: lag.percentile(50) / 1e6,
loop_lag_p99_ms: lag.percentile(99) / 1e6,
loop_lag_max_ms: lag.max / 1e6,
}));
} else {
res.statusCode = 404; res.end();
}
});
server.listen(3000);
Now drive concurrent traffic at /panel (with autocannon or any load tool) and, at the same time, poll /healthz and /metrics. Chart what you observe. You will see — and this is the whole point — that /healthz latency and loop-lag p99 climb together, in lockstep, even though /healthz does nothing. The do-nothing endpoint is slow because the waiter is chopping vegetables for /panel. That is the single-thread blast radius made visible: one CPU-bound endpoint degrades everything on the process, including the probe that decides whether you live or die. In a multi-tenant HIPAA service that means every clinic on the pod stalls at once — a chart read, a login, an eligibility check — all frozen behind one risk-stratification burst. Prove it to yourself once and you'll never again be confused by an incident where "unrelated" endpoints slow down together.
Then fix it three ways and re-measure: (a) chunk rankPanel with setImmediate between batches and watch loop lag drop; (b) move it to a worker_threads pool; (c) extract it to a separate process. Compare loop lag and throughput across all three. (We build (b) and (c) properly in Chapter 8; (a) you can do right now with what you know.)
6. Common pitfalls
Each is signature → fix — the symptom you'll observe, then the principle that resolves it.
Blocking the loop with CPU work.
Signature: every endpoint slows together, one core pinned at 100% while others idle, loop-lag p99 in the hundreds of ms or seconds, health checks timing out, the process getting restart-looped.
Fix: get the hot function off the main thread — worker_threads, a separate service, or chunk it with setImmediate yields so the loop breathes between batches. Adding cores does nothing; the work has to move, not get more hardware around it.
A synchronous API in a hot path.
Signature: intermittent freezes that correlate with input size — fine on small payloads, ugly on big ones. Usual culprits: fs.readFileSync, crypto.*Sync, JSON.parse on a huge body, synchronous bcrypt, or a regex with catastrophic backtracking.
Fix: use the async variant (fs.promises, async crypto); bound input size before you process it; cap regex complexity or use a linear-time matcher. The Sync suffix in a request handler is a code smell — every one of them is a deliberate loop-block.
process.nextTick recursion / microtask starvation.
Signature: the process looks "alive" (not crashed, CPU maybe not even high) but timers and I/O never fire — the loop is stuck draining a queue that refills itself.
Fix: never recursively process.nextTick (or recursively schedule microtasks) for work that should yield to I/O. Use setImmediate for deferral that must let the loop advance a phase. nextTick means "before the loop moves at all"; that's almost never what you want for repeated work.
Unhandled rejection / a forgotten await.
Signature: work silently doesn't happen — "the claim sometimes doesn't submit," a request returns before its async side effect completes, an error vanishes with no stack trace.
Fix: await every Promise whose completion you depend on, or attach an explicit .catch. A handler that fires off submitClaim() without await returns immediately and the work races on alone. Run with --unhandled-rejections=strict so a dropped rejection crashes loudly instead of failing silently.
Assuming setTimeout(0) runs "immediately" or in a fixed order.
Signature: ordering bugs that pass in tests and fail in production (or flake run to run), built on the belief that setTimeout(fn, 0) fires right away or always beats/loses to setImmediate.
Fix: setTimeout(fn, 0) waits at minimum until the next timers phase and is clamped to ~1 ms; its order versus setImmediate from the top level is not deterministic. When you mean "as soon as the current code finishes," use queueMicrotask; when you mean "after pending I/O," use setImmediate. Pick the primitive whose guarantee matches your intent.
Pool exhaustion mistaken for a CPU shortage.
Signature: latency climbs under load, many concurrent fs/crypto/zlib calls, but CPU is not maxed — cores sit idle while requests queue.
Fix: it's the 4-thread pool, not the CPU. Raise UV_THREADPOOL_SIZE (set before startup, process-wide) or reduce concurrent pool operations. Throwing cores at a thread-pool bottleneck is wasted money.
Awaiting in a loop serially.
Signature: an endpoint that calls N independent downstreams takes N × latency instead of ~max-latency — five 100 ms calls take 500 ms when they could take ~100.
Fix: await inside a for loop serializes independent work needlessly. Use Promise.all (or Promise.allSettled) to fire independent calls concurrently and await them together. Keep the sequential for await only when each step truly depends on the previous one's result.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand.
Single-threaded simplicity ↔ zero free CPU parallelism. One thread buys you a programming model with no locks, no mutexes, no data races on in-process state, and trivially correct reasoning about shared memory — a genuine, underrated gift. It costs you any free parallelism for computation and a brutal blast radius: one poisoned handler stalls the whole process. You happily accept this trade for I/O-bound work (most web backends — chart reads, CRUD, worklists, proxying). You'd reverse it — reach for a different runtime, or offload aggressively from day one — when CPU dominates the workload: image/document processing, ML inference on device data, heavy cryptography. Don't fight the model; pick the model that fits the work.
nextTick ↔ setImmediate ↔ queueMicrotask.
Three "do it later" primitives with three different whens: process.nextTick runs before the loop advances at all (and before Promise microtasks); queueMicrotask runs after the current JS, with Promise reactions, before macrotasks; setImmediate runs after the poll phase, yielding to pending I/O first. Choosing wrong isn't a style nit — it's the difference between correctness, fairness, and starvation. "Defer but let I/O happen first" is setImmediate. "Run right after this synchronous burst" is queueMicrotask. "Run before anything else, even I/O" is nextTick — and that power is exactly what starves the loop when misused.
Raising UV_THREADPOOL_SIZE: more I/O concurrency ↔ more overhead.
A bigger pool lets more fs/crypto/zlib operations run at once, which helps when those threads spend their time blocked on I/O. But more threads means more context-switching and more memory, and for CPU-bound pool work (crypto, compression) a pool larger than your core count just oversubscribes the cores and gets slower. Raise it for I/O-bound pool work; don't raise it past core count for CPU-bound pool work. The right number depends on which kind you have — measure, don't guess.
worker_threads (embed) ↔ separate service (extract).
The classic embed-vs-extract decision, previewed here. worker_threads keep CPU work in-process with cheap, shared-memory data transfer (transferables, SharedArrayBuffer) — lower overhead, but a worker crash can still hurt the process and it shares the heap ceiling. A separate service gives you isolation, independent scaling, crash containment, even a different language — at the cost of network hops and serialization. Embed for tightly-coupled CPU offload at modest scale; extract when the work needs its own scaling story or its own failure domain. (Built in Chapter 8.)
Multi-process to use all cores ↔ one big process.
🚫 A framing this book rejects. "Just run one big Node process; it'll use the machine." It won't. One loop is one core, period — a single process leaves an eight-core box seven-eighths idle for your JS. The opposite over-correction — "threads everywhere, like Java" — is also wrong for Node: it forfeits the single-threaded, data-race-free model that is Node's main ergonomic advantage. The right answer is N processes (cluster or replicas) to span cores, each keeping the simple one-loop model internally. Span cores with processes; keep the simplicity within each process.
Async-everywhere ergonomics ↔ the hidden per-await cost.
async/await is beautiful and almost always correct. But it isn't free: every await is a microtask hop and a Promise allocation, and in ultra-hot paths (a function called millions of times a second) synchronous code can be legitimately faster and allocate less (which, recall, means less GC, which means less loop lag). This is a measure-first exception, not a license to write callback spaghetti — sugar by default, de-sugar a proven hot spot.
8. Security & scale notes
Security and scale aren't a separate topic in Node — they fall directly out of the single-thread model, and they're sharper here than in a thread-per-request runtime.
Blocking the loop is a denial-of-service vector. In a thread-per-request server, an attacker who makes one request do expensive work ties up one thread. In Node, an attacker who makes one request block the loop freezes every tenant on that process at once — in Pulsely's case, every clinic sharing that pod. The blast radius of a single-thread runtime is the whole instance. So any attacker-controllable input that can trigger heavy main-thread work is a DoS primitive:
- ReDoS — a catastrophic-backtracking regex fed a crafted string can spin the loop for seconds on a single request. Uniquely brutal on Node because there's no other thread to keep serving. Use linear-time regex engines or bound input length, and audit regexes on user input.
- Algorithmic-complexity attacks — an endpoint that's O(n²) in some input dimension, deeply nested JSON (a hostile FHIR bundle, say), hash-collision DoS — all become single-request freezes.
- Decompression / parse bombs — a tiny gzip that expands to gigabytes, or a giant
JSON.parse, blocks the loop (and blows the heap). Bound and validate input size before you do work on it.
The defense is one principle, stated once and forever: bound and validate input at the boundary, before the main thread touches it. Max body size, max array length, max nesting depth, max regex input — enforced before the expensive operation, not after. (This boundary discipline is developed for real in Chapter 9 and in the API-contract chapters.)
Pool exhaustion is a soft DoS. Flood a crypto-backed endpoint — say password hashing on login — and you drain the 4-thread pool. Now unrelated fs and dns.lookup operations across the whole process stall behind the hashing, even though those endpoints are innocent. An attacker hammering /login can degrade your chart-file reads and your DNS. Mitigate by rate-limiting expensive-by-design endpoints, sizing the pool deliberately, and considering isolating heavy crypto onto a worker or a separate service so it can't starve general I/O.
Behavior under load is a cliff, not a slope — and this is the scale lesson that surprises people. Node's throughput stays high and flat right up until the loop saturates, and then latency degrades non-linearly — it falls off a cliff. There's little gentle warning in the latency curve itself; the loop is fine, fine, fine, then suddenly everything queues behind a saturated thread. Worse, your liveness and readiness probes share that same loop, so a saturated process looks dead to the orchestrator — the health check times out — and gets restart-looped, which removes capacity during an overload and amplifies the outage into a death spiral. This is precisely the §1 incident, now explained: the cliff plus the shared-loop health check is what turns a CPU-heavy handler into a self-inflicted outage.
latency
│ ╱ ← non-linear cliff
│ ╱ (loop saturated)
│ ╱
│ ╱
│ flat, healthy, fast ╱ ◀── /healthz rides THE SAME curve:
│ ─────────────────────────╱ the probe times out, orchestrator
│ kills a "dead" (just busy) process
└──────────────────────────────────────────────▶ concurrent load
▲
the "looks dead" zone
The earliest warning you get — earlier than CPU, earlier than user-facing latency — is loop lag (§5). That's why it belongs in your alerts and your health logic: it's the leading indicator of the cliff.
🔑 Capacity is requests-per-loop-second-per-core, and you scale it with processes. A Node instance's ceiling is how much main-thread work it can do per second on its one core. You don't raise that ceiling by adding cores to the box (the loop won't use them) or threads to the pool (those are for I/O, not your JS) — you raise it by running more processes. Loop lag is your saturation gauge; process count is your scale lever. Internalize that and Node capacity planning stops being mysterious. (Full performance and tail-latency engineering: Chapter 30; reliability patterns like load-shedding and circuit-breaking under this kind of saturation: Chapter 33.)
9. Interview lens & exercises
Interview questions
Backend interviews probe whether you reason about the runtime or merely recite it. Same question, different level, in the quality of the narration.
"Walk me through the exact output of this snippet" (the setTimeout / setImmediate / Promise.then / process.nextTick mix).
- Junior answer: recites a memorized output, possibly correct, with no explanation — and gets stuck the moment the snippet is changed.
- Senior answer: names the queues and the rules — synchronous code first; then
nextTickdrains before the Promise microtask queue; then macrotasks in phase order with microtasks re-drained between each — and flags where ordering is not guaranteed (top-levelsetTimeout(0)vs.setImmediate), and how moving the calls inside an I/O callback makes it deterministic. Reasons, doesn't recite.
"Node is single-threaded — so how does it handle 10,000 concurrent connections?"
- Junior: "it's non-blocking," with no mechanism named.
- Senior: separates the two paths cleanly — network I/O is genuinely async in the kernel (
epoll/kqueue/IOCP, no threads, no pool), which is why idle connections are nearly free; the libuv pool (default 4) handlesfs/crypto/dns.lookup/zlibbecause those have no good async OS API; and CPU work still blocks the one thread regardless. Three distinct mechanisms, correctly assigned.
"A handler does crypto.pbkdf2 for auth and latency spikes under load, but CPU isn't maxed — diagnose it."
- Junior: "add more CPU."
- Senior: identifies pool exhaustion —
pbkdf2runs on the 4-thread libuv pool, so concurrent logins queue four at a time while cores sit idle (hence latency up, CPU not maxed). Fix: raiseUV_THREADPOOL_SIZE(set before startup) and/or isolate hashing; weighs the context-switch cost of oversubscribing cores with CPU-bound pool work. Names the right bottleneck.
"How do you detect that you're blocking the event loop in production?"
- Junior: "check CPU usage."
- Senior:
perf_hooks.monitorEventLoopDelay()histogram, alert on p99; flamegraphs (--cpu-prof,clinic) to find the wide synchronous frame; distinguishes GC pauses vs. user code vs. pool waiting. Notes that CPU% lies on a multi-core box (one pinned core averages out) and that loop lag leads the other signals.
"process.nextTick vs. a Promise microtask — what's the difference and when does it bite?"
- Junior: "they're basically the same."
- Senior: separate queues;
nextTickdrains first, before the Promise microtask queue, before the loop advances; recursivenextTick(or recursive microtask scheduling) starves timers and I/O because the drain never completes — a "looks alive but stuck" failure. PrefersetImmediatewhen deferral must yield to I/O.
Exercises & the Pulsely increment
Do these at the keyboard; predicting and then running is the whole point.
-
Predict-then-run the ordering snippet. Take the §4 trace, write the output you expect on paper first, then run it ten times. Watch the
setTimeout(0)/setImmediatepair swap order across runs from the top level. Then wrap both in afs.readFilecallback and watch the order become stable (immediate first). Explain why each result happens by phase and queue — if you can't, reread §4. -
Build the bare-
httpPulsely service (§5):/panel(CPU risk-stratification stub),/patient/:id(asyncfschart read),/healthz, and/metricsexposing loop-lag p50/p99/max frommonitorEventLoopDelay. No Express. -
Load-and-observe the blast radius. Drive concurrent traffic at
/panelwhile polling/healthzand/metrics. Chart/healthzlatency and loop-lag p99 on the same time axis. Prove to yourself that the do-nothing endpoint degrades in lockstep with the CPU endpoint — and connect that, explicitly, to the §1 incident where a health check timed out and the orchestrator killed a healthy-but-busy process. -
Fix it three ways. Mitigate the
/panelblock via (a)setImmediatechunking, (b)worker_threads, (c) a separate process. Measure loop lag and throughput for each; write one paragraph on which you'd ship for Pulsely and why. (You can do (a) now; (b) and (c) you'll do properly in Chapter 8.) -
Pool-tuning experiment. Hammer a
crypto.pbkdf2endpoint at concurrency 8 withUV_THREADPOOL_SIZE=4, then=8. Measure the latency change and explain it purely from pool mechanics — not from CPU. This is the §5 "which exhaustion?" diagnosis turned into a number you generated yourself.
Key takeaways
- Node runs all your JavaScript on one thread. "Non-blocking" is about I/O, not CPU — you get concurrency for waiting free, and zero concurrency for computation by default. One CPU-bound handler stalls the whole process, health check included.
- The runtime is V8 (runs JS, JITs, garbage-collects on the main thread) + libuv (the event loop, the cross-platform async I/O, and a 4-thread worker pool). GC pauses count as loop lag.
- Network I/O bypasses the pool (kernel
epoll/kqueue/IOCP — this is why idle connections are nearly free). The pool servesfs,dns.lookup,crypto, andzlib. Conflating these is the classic Node mistake. - Ordering is governed by invariants: run-to-completion (no JS preempts JS — hence no in-process data races, but also no rescue from a hogging callback); microtasks drain to empty between every callback;
nextTickdrains before Promise microtasks; phases run in fixed order but cross-phase top-level ordering is not guaranteed; the loop ensures liveness, not fairness (starvation is legal). async/awaitis sugar over Promises over callbacks:awaitis a microtask suspension point, not a thread switch — awaiting CPU work offloads nothing.- Loop lag (
monitorEventLoopDelay) is your earliest saturation signal — ahead of CPU and latency. Wire it into metrics and health logic, because the loop and your probes share a thread; a saturated process looks dead and gets restart-looped. - Under load Node degrades on a cliff, not a slope. You scale by adding processes, not cores or pool threads — one loop is one core. Blocking the loop is a DoS vector with the whole instance as blast radius; bound and validate input before the main thread touches it.
← Previous: Ch 6 — Networking II · Up: Part II overview · Master TOC · Next: Ch 8 — Node Deeper →