Chapter 8 — Node Deeper: Streams, Backpressure, Memory/GC, Workers, Profiling, Graceful Shutdown
Part II · The Node.js Runtime | Prerequisites: Ch 7 | Builds: bounded-memory streaming, leak hunting, CPU offload, and graceful shutdown for Pulsely
Earlier you saw who runs your code: one thread draining an event loop, a libuv pool doing the blocking syscalls it can't, and a cooperative scheduler that never preempts you. That taught you to predict execution order and to feel the single-threaded reality. This chapter is about what happens when that runtime meets real load — the kind your laptop tutorial never produced. The event loop you can now reason about runs inside a process with a fixed-size heap, talking to clients over connections that can stall, dying on a schedule dictated by an orchestrator you don't control. Every constraint in this chapter was invisible on your machine and is load-bearing in production.
By the end you'll be able to stream a multi-gigabyte export through a process whose memory never moves; find a leak that creeps 40 MB an hour and hides behind restarts; move CPU work off the loop so one heavy request doesn't poison everyone; carry a request's identity down a deep async call tree without threading it through every function; read a flamegraph and a heap snapshot the way you read a stack trace; and shut a process down under live traffic without dropping a single in-flight request. These are the skills that separate "it works on my laptop" from "it survives a deploy at 3× traffic." We'll build all of them into Pulsely and write the policy down as an ADR.
1. The problem: the laptop lies, production tells the truth
Let me give you four pages from the same on-call notebook, because they're really one story told from four angles: Node's constraints are real, and your laptop hid every one of them.
Page one — the export that eats the pod. Pulsely added a CSV export so clinics could download their encounters for their own reporting. The handler is the obvious thing a frontend dev writes:
app.get('/exports/encounters', async (req, res) => {
const rows = await db.query('SELECT * FROM encounters WHERE provider_id = $1', [providerId]);
res.setHeader('Content-Type', 'text/csv');
res.send(toCsv(rows)); // build the whole CSV string, then send
});
It demos beautifully. It ships. Then a busy clinic with two years of charting hits GET /exports/encounters?range=2y, the query returns four million rows, db.query materializes every one of them into a JS array, toCsv builds a second multi-gigabyte string, and the pod dies with exit code 137 — OOMKilled. The orchestrator restarts it; the clinic retries; it dies again. One request, one user, the whole instance down. Nothing was buffered "wrong." The code simply assumed the response fits in memory, and at scale it doesn't.
Page two — the deploy that corrupts billing. A routine deploy rolls thirty pods. Kubernetes sends each one SIGTERM and the Node process, having no handler for it, exits immediately — the default disposition of SIGTERM is to terminate. Each pod had roughly two hundred requests in flight, many of them claim submissions to the clearinghouse. Those connections are cut mid-write: clients see 502s from the load balancer, some claims were half-submitted, and because the billing worker retries on failure, a few claims get submitted twice — a duplicate claim to the payer, which means a rejection, a rework queue, and a delayed payment. "It's just a restart" became a revenue-cycle incident and a payer reconciliation, and it happens on every deploy because nothing taught the process that "you're about to die" should mean "finish what you started first."
Page three — the leak that hides. Memory climbs about 40 MB an hour. Nobody notices, because the pod restarts on its own every eighteen hours — sometimes from a deploy, sometimes from hitting its limit — and each restart resets the graph to zero. The sawtooth looks like normal life. Then a flu-season surge doubles traffic, the leak now outruns the day, and pods start OOMKilling during peak instead of overnight. The bug was there for weeks; restarts were masking it. A leak you can't see is a leak you can't fix.
Page four — the CPU burst that poisons everyone. Pulsely's care-gap engine does a chunk of synchronous JSON crunching — scoring a provider's patient panel for open care gaps, sorting by risk, deduping overlapping recommendations. For a large panel it runs 800 ms on the main thread. While it runs, nothing else on that process moves: not /login, not /healthz, not the other ninety requests queued behind it — including a clinician trying to pull up a chart mid-visit. p99 latency on completely unrelated endpoints tanks in lockstep, because there is one loop, and a synchronous burst is everyone's burst. "Node is fast" is true right up until you do real CPU work on the loop, and then it's catastrophically, correlatedly false.
Strip the four pages to their cause and you get the reason this chapter exists. Node gives you exactly three things your laptop tutorial never stressed: one thread for your JavaScript, an OS-bounded heap (V8's default old-space cap is version- and RAM-dependent, commonly well under 2 GB and below your container's memory limit unless you raise it), and cooperative scheduling where nothing interrupts a running function. None of those mattered when you were one user hitting localhost. All of them are load-bearing the moment you have real traffic, real data sizes, and a platform that restarts you on a schedule. The rest of this chapter is the operating manual for those three constraints.
🧭 A useful distinction. Three of this chapter's four pages look like "memory problems," but they're three different problems that demand three different fixes. Page one is working-set too large — fixed by streaming, never by raising the limit. Page three is a leak — fixed by finding unintended reachability, never by streaming. Page four isn't memory at all; it's the loop — fixed by offloading CPU. Misdiagnosing which one you have is how teams "raise the heap" and OOMKill again next week. Naming the failure precisely is half the cure.
2. The mental model: a process is a pipe network with a fixed reservoir
Hold five pictures in your head for this chapter. They're the lenses you'll reach for at 3 a.m.
A process is a pipe network with a fixed-size reservoir. Data flows producer → transform → consumer: a DB cursor produces rows, a transform turns them into CSV, a socket consumes the bytes. The reservoir is the heap. If any stage produces faster than the next can consume, and nothing tells the producer to slow down, the reservoir fills and overflows — that overflow is OOM. Backpressure is the float valve: a signal that travels backward up the pipe — "stop pouring, I'm full" — so the producer pauses until the consumer catches up. A pipeline with working backpressure runs at the speed of its slowest stage with flat memory, no matter how much total data passes through. A pipeline without it runs until the reservoir bursts. Page one was a pipe network with the float valve removed.
The event loop is a single cashier. This is the cashier image again, sharpened for this chapter. The cashier rings up customers one at a time. I/O is "send this order to the kitchen and serve the next customer" — the cashier never stands idle. But a synchronous CPU burst is the cashier stopping to do long division by hand while the entire line waits. There is exactly one fix that keeps the till open: hand the long division to another cashier (a worker thread) or send it to another store (a separate process). You cannot make the one cashier do arithmetic and serve at the same time. Page four was the cashier doing long division.
Memory is two questions, never one. "How much is live right now?" is the working set — bounded by streaming, by pool sizes, by not buffering. "What should be dead but isn't?" is a leak — a reference graph that keeps growing because something still points at objects you've forgotten. The garbage collector reclaims everything unreachable; it is powerless against reachable-but-forgotten. Confuse these two and every fix is wrong: you'll stream to fix a leak, or hunt retainers to fix a working-set problem.
Shutdown is a state machine, not an event. A process doesn't "stop"; it transitions: RUNNING → DRAINING → CLOSED. In RUNNING it accepts and serves. The instant SIGTERM arrives it flips to DRAINING: refuse all new work, finish what's already in flight. When the last in-flight request completes — or a hard deadline fires — it moves to CLOSED and exits. The orchestrator and your process must agree on this contract, or one of them kills the other mid-sentence. Page two was a process with no state machine, jumping straight from RUNNING to dead.
Pooling is how you give backpressure somewhere to stop. A connection pool (a fixed, shared set of reusable DB connections the whole server borrows from), a worker pool, a file-handle limit — each is a deliberate ceiling on concurrency at a scarce resource. When the pool is exhausted, the next caller waits in a bounded queue with a timeout instead of opening connection number ten thousand. An unbounded pool doesn't remove the limit; it just moves the explosion downstream to whatever the pool talks to. A bound is where backpressure has a wall to push against.
🧭 Mental model. Every problem in this chapter is "something flows faster than something else can absorb it, and nothing pushed back." Rows outpace the socket → OOM. Allocations outpace death → leak (or GC pressure). One handler's CPU outpaces the loop's fairness → starvation. New requests outpace a dying process's ability to finish old ones → dropped work. The cure is always the same shape: put a bound somewhere and make the pressure travel backward to a producer that can pause. Streaming, pools, worker queues, and drain deadlines are four faces of one idea — bounded flow with backpressure.
3. Theory & invariants
The models tell you how to picture the process. Invariants tell you what must stay true while it runs under load. These are the load-bearing rules for everything that follows.
🔑 The backpressure invariant. A correct pipeline never buffers unboundedly; when the consumer is slow, the producer pauses. The protocol in Node is concrete: a
Writable'swrite()returnsfalsewhen its internal buffer is past itshighWaterMark, and the producer must stop and wait for the'drain'event before writing more.pipe()andpipeline()honor this automatically — they wire the pause/resume for you. A manualreadable.on('data', chunk => writable.write(chunk))loop does not: it keeps pulling data and shoving it at a sink that has already said "I'm full," and the unwritten chunks pile up in the heap. The rule to tattoo on your wrist: if you ignore the return value ofwrite(), you have no backpressure, and your memory is now a function of how slow your consumer is.
The stream types are a small, learnable taxonomy, and once you know their contracts the whole API stops feeling arbitrary:
- Readable — a source. Pulls or pushes data; its
highWaterMarkis the ceiling on how much it buffers internally before it stops reading from its underlying source. A DB cursor, a file read stream, an incoming HTTP request body. - Writable — a sink. You call
write(chunk); it returnsfalsewhen full; it emits'drain'when it has room again. A file write stream, an outgoing HTTP response, a TCP socket. - Duplex — both, on independent channels. A TCP socket is the canonical example: what you read and what you write are unrelated streams sharing one object.
- Transform — a Duplex where the output is a function of the input: gzip compression, CSV encoding, a JSON-to-NDJSON converter. You write rows in one end, encoded bytes come out the other.
One subtlety that bites everyone: object mode vs byte mode. In byte mode highWaterMark is measured in bytes (default 16 KB). In object mode — which a DB-row stream uses — it's measured in a count of objects (default 16). So "the buffer holds 16" means sixteen rows, not sixteen bytes, and a "small" buffer of sixteen rows can be huge if each row is a fat encounter with an embedded note. Know which mode you're in before you reason about memory.
🔑 The reachability invariant. The garbage collector reclaims by reachability from roots, not by "is this still needed." The roots are the call stack, the global object, and live closures. An object survives exactly as long as some chain of references leads to it from a root. Therefore every leak is unintended reachability — never a GC failure. The usual culprits are a short list you should be able to recite: a module-level
Mapor array used as a cache that only grows; anEventEmitterlistener added on every request and never removed; a closure that captures a large scope and is itself kept alive by a long-lived reference; asetIntervalwhose callback closes overthisand pins the whole object forever. The GC is doing its job perfectly. You are still pointing at the corpse.
🔑 The generational hypothesis. Most objects die young — a request's temporary variables are garbage milliseconds after the response is sent. V8 turns that bet into a memory layout. It keeps a small nursery it can sweep constantly and cheaply, because it assumes almost everything in there is already dead; only the rare survivors get moved into a big room that is slow and expensive to clean. Now the names for those pieces:
- the nursery is new space, and the cheap, frequent sweep that copies out its handful of survivors is a scavenge;
- the big room is old space, and the slow, rare walk of its whole live graph is a mark-sweep-compact;
- an object that survives two scavenges is promoted from new space to old space.
If you own React, this is the same instinct as keeping freshly-mounted throwaway components cheap to unmount and paying real reconciliation cost only on the long-lived ones. This is the why behind the GC pause patterns you'll read off a flamegraph: frequent tiny pauses are scavenges in new space; the occasional long freeze is a major collection in old space. Allocation-heavy hot paths push more objects into old space, which means longer major pauses — and on Node those pauses run on the main thread, so they are loop lag, not just a memory statistic.
🔑 The concurrency-isolation invariant. Node parallelizes I/O through libuv's worker pool (default four threads, for
fs,dns.lookup,crypto,zlib) but your JavaScript runs single-threaded per isolate. An isolate is a self-contained JS world — its own variables, its own heap — and a worker thread is a separate isolate. In plain terms: think of each worker like its own browser tab running your code, not another module sharing your variables. Real JS parallelism therefore requires more isolates —worker_threads(isolates inside one process) or separate processes. Because two isolates share nothing by default, anything you send from one to another gets deep-copied across; that copy has a name, a structured clone. The escapes arrive a beat later (and §4 builds them): you can move anArrayBufferacross with zero copy via a transfer list, or share one outright viaSharedArrayBuffer. This single fact decides every offload question below: "scale threads or scale processes?" is really "do I need shared memory, or independent throughput?"
The shutdown invariants are four rules that, together, define "graceful," and ADR-008 will pin them down for Pulsely:
- Once draining, zero new requests are accepted. No exceptions. A request let in after the drain decision is a request you may not finish.
- Every accepted request either completes or is bounded by a deadline. You promise to finish in-flight work or to give up at a known time — never to hang forever.
- Shutdown is idempotent. A second
SIGTERM(orchestrators sometimes send two) must not double-close pools or re-run cleanup. - The exit code reflects clean vs. forced.
exit(0)means "drained cleanly"; a non-zero forced exit means "the deadline fired and I killed in-flight work" — so your dashboards can tell the difference.
📎 Borrowed on credit: request context propagation. Several things — a correlation ID, the tenant, the acting user (for the HIPAA audit trail), a trace span — must follow an async call chain all the way down, into the logger and the DB call, without you threading a
ctxparameter through every function signature. A module-level "current request" variable cannot do this: under concurrency, many requests share the process, so a global is overwritten by whichever request ran most recently, and your logs scramble — one clinician's chart access attributed to another. The correct tool is continuation-local storage —AsyncLocalStorage, built onasync_hooks— which gives each async chain its own store. We name the invariant here (per-request context must live in async-local storage, never in a global) and build it concretely in §4. Why it matters now: it's the reason your request logs and audit records stay coherent under load instead of attributing one patient's query to another user's request.
4. Under the hood
Now we kill the magic, the way we did earlier for the loop. Four machines to open: streams and backpressure, the V8 heap, the offload primitives (workers, channels, async-local storage), and graceful shutdown.
Streams and backpressure, mechanically
A Readable has two modes. In paused mode it sits on its internal buffer and only yields data when you pull (.read() or for await). In flowing mode it pushes data at you via 'data' events as fast as it can read. The crucial, much-violated rule: don't mix .pipe() (or pipeline()) with manual .on('data') on the same stream. pipe puts the stream in flowing mode and manages backpressure for you by toggling the source between flowing and paused as the sink fills and drains. Add a .on('data') listener and you've started pulling data out from under pipe, corrupting the very mechanism that keeps memory bounded.
Use stream.pipeline(), not bare .pipe(), in any request handler. The difference is not stylistic; it's a correctness and resource bug:
import { pipeline } from 'node:stream/promises';
// CORRECT: errors propagate, every stream is destroyed on failure.
await pipeline(cursorStream, csvTransform, gzip, res);
If a downstream stream errors, pipeline destroys every stream in the chain and rejects — so the DB cursor is closed, the gzip stream is torn down, nothing leaks. Bare .pipe() does the opposite: on a downstream error it leaves the source reading happily into a sink that's gone, leaking the cursor and the connection it holds. stream.finished(stream) is the lower-level primitive for "tell me when this stream is truly done (or errored)," and for await (const chunk of readable) is the modern, backpressure-respecting way to consume a readable in a loop — each iteration awaits, so the source naturally pauses while you process a chunk.
The Pulsely export path, concretely
Here is the bounded-memory export, the shape every streaming endpoint takes. The key move is on the very first line: a streaming query (a cursor), not db.query() which buffers every row before resolving.
import { pipeline } from 'node:stream/promises';
import { Transform } from 'node:stream';
import { createGzip } from 'node:zlib';
import QueryStream from 'pg-query-stream';
app.get('/exports/encounters', async (req, res) => {
const providerId = req.auth.providerId; // authoritative — never from the query string
const client = await pool.connect();
// 1. SOURCE: a cursor — rows arrive in batches, not all at once.
const cursor = client.query(new QueryStream(
'SELECT id, encounter_date, status FROM encounters WHERE provider_id = $1', [providerId],
));
// 2. TRANSFORM: one row in → one NDJSON line out. Object mode in, bytes out.
const toNdjson = new Transform({
writableObjectMode: true,
transform(row, _enc, cb) { cb(null, JSON.stringify(row) + '\n'); },
});
res.setHeader('Content-Type', 'application/x-ndjson');
res.setHeader('Content-Disposition', 'attachment; filename="encounters.ndjson.gz"');
res.setHeader('Content-Encoding', 'gzip');
// 3. CRITICAL: if the client aborts, destroy the cursor or it leaks.
res.on('close', () => cursor.destroy());
try {
// SINK chain: cursor → NDJSON → gzip → res → TCP → kernel → client.
await pipeline(cursor, toNdjson, createGzip(), res);
} finally {
client.release(); // always return the connection to the pool
}
});
Trace the bytes and the backpressure. Postgres streams rows to the cursor; the cursor fills its small object-mode buffer and stops asking Postgres for more until that buffer drains. toNdjson pulls a row, emits a line. gzip compresses. res (an http.ServerResponse, which is a Writable) writes to the TCP socket, which writes to the kernel send buffer, which is flushed to the client at the client's receive speed. When the client is slow, the kernel buffer fills, res.write() starts returning false, gzip stops being read, the transform stops, the cursor stops pulling, Postgres stops sending — the slowness has traveled all the way back to the database, and memory in your process never exceeds the sum of the highWaterMarks. It is O(highWaterMark), not O(rows). Five million encounters or five, the RSS line is flat.
The res.on('close') handler is not optional. When a client aborts a big export (closes the tab, loses signal), res closes — but your cursor doesn't know that, and without cursor.destroy() it keeps a DB connection pinned, reading rows nobody will ever receive. Skip this line and a few aborted exports drain your connection pool.
The V8 heap, laid out
The heap V8 manages is several spaces, and knowing them lets you read a snapshot:
- New space — small (a few MB), where every object is born. Collected by scavenge: fast, frequent, copies survivors between two semispaces. This is why scavenges are cheap — they touch only the small new space.
- Old space — large, holds objects promoted after surviving two scavenges. Collected by mark-sweep-compact: slow, rare, walks the whole live graph. This is your long GC pause.
- Large object space — objects bigger than V8's regular-object limit (
kMaxRegularHeapObjectSize, just under ~256 KB — think a multi-megabyteBufferor a giant FHIR bundle array) skip new space entirely and are allocated here directly. Relevant because buffering a big response lands here and pressures old-space GC. - Code space, map space — JIT-compiled code and hidden-class descriptors; usually not your problem.
Now the ceiling — and the trap is that there are two of them, and they don't know about each other. V8 has its own limit on the JS heap. The container has a separate, hard limit on the total memory the process may use; that limit lives in its cgroup (the Linux memory box the pod runs inside), and it counts RSS — resident set size, meaning everything the process holds: the JS heap plus buffers, native memory, and overhead. Two facts about these ceilings will save you a confusing afternoon:
- First,
--max-old-space-sizeraises the inner ceiling — the old-space cap, in MB. It's the V8 analog of the JVM's-Xmx. - Second, and this is the one that bites: V8's default heap is often smaller than the container's memory limit, and getting the relationship wrong fails in two opposite ways:
- Heap set too low (the default on a big pod): the JS heap caps you below the container limit, so you waste container memory and do needless GC for no reason.
- Heap set too high: your RSS climbs past the cgroup limit, and the kernel OOMKills the whole process before V8's GC ever gets a chance to run.
You must tune the heap relative to the container — picture two nested boxes, the heap inside the cgroup — which §5 makes concrete.
Finding leaks: the three-snapshot technique
When memory trends up (page three), you hunt the retainer. The mechanics:
Attach node --inspect and open Chrome DevTools' Memory tab (or call v8.writeHeapSnapshot() to dump a .heapsnapshot file you load later). Then run the three-snapshot technique: take a baseline snapshot, exercise the suspected path a few hundred times (hit the endpoint, run the job), take a second snapshot, exercise again, take a third. DevTools' "Comparison" view shows you objects allocated between snapshots that are still alive — anything that should have been temporary but survived. Sort by retained size (how much memory frees if this object dies) and walk the retainers / dominators — the reference chain holding the object alive — back to its root. The dominator is the single object whose removal would free the whole subtree; that's almost always your bug (the module-level Map, the EventEmitter still holding listeners).
One trap that wastes hours: process.memoryUsage() has four numbers and they mean different things. heapUsed is live JS objects (what snapshots show). rss is the whole resident set — heap plus everything else. external and arrayBuffers count memory held by native objects, chiefly Buffers, which live outside the V8 JS heap. So a Buffer leak makes rss and external climb while heapUsed stays flat and the heap snapshot shows nothing. If memory is high but the snapshot looks innocent, check external — you're leaking native buffers, not JS objects.
cluster vs. worker_threads vs. a separate service
Three ways to use more than one core, and the decision is mechanical once you see what each shares:
cluster forks N OS processes that share one listening socket (the master distributes incoming connections, round-robin on most platforms). The workers are shared-nothing — separate heaps, separate event loops, full crash isolation (one worker crashing doesn't take the others down). This scales I/O throughput across cores: each process has its own loop, so N processes serve N loops' worth of requests. In practice, in a containerized world, you often skip cluster and run one Node process per pod, N pods behind a load balancer — same outcome, the orchestrator does the fan-out.
worker_threads spins up isolates inside one process. They can share memory via SharedArrayBuffer, message-pass cheaply, and — critically — share the same process memory ceiling. They exist for CPU offload: move the care-gap scoring burst onto a worker thread so the main loop stays responsive. They do not multiply request throughput, because they share the one process's heap and you typically have only a few of them.
A separate service (child_process or a different deployment entirely) gives full isolation, independent scaling, even a different language or a GPU — at the cost of a network hop and more to operate. In a clinical system this is often where a heavy risk-model or an OCR/document-parsing service ends up.
🧭 Mental model. The decision rule is one sentence: scale process count for event-loop/throughput; scale threads for CPU-bound compute you must keep in-process; extract a service when the CPU work needs its own scaling, runtime, or hardware. "Threads are lighter, just use them" is the junior error — threads don't add request capacity, and the cost of shipping data to them can erase the win, which is the next machine.
MessageChannel, transferList, and the serialization trap
Sending data to a worker isn't free. postMessage(data) structured-clones it — a deep copy — so handing a worker a 50 MB payload (say, a large FHIR bundle) means copying 50 MB across the boundary before any work starts. For large payloads that copy can cost more than the computation you were offloading, and the offload makes things slower. The escapes: a transferList moves an ArrayBuffer to the worker with zero copy (the sender loses access — it's a move, not a share); a SharedArrayBuffer with Atomics lets both sides see the same memory for genuinely shared state. The rule: if you're offloading, either keep the payload small or move/share it — don't clone megabytes.
AsyncLocalStorage, concretely
This is the request-context invariant from §3, made real. AsyncLocalStorage is built on async_hooks: it tracks the chain of async operations and gives each chain access to its own store. You wrap the request at the entry point, and any code deep in the call tree reads the store without it being passed in:
import { AsyncLocalStorage } from 'node:async_hooks';
export const als = new AsyncLocalStorage<{ requestId: string; tenant: string; actorId: string }>();
// Middleware at the entry point — wrap the rest of the request in a store.
app.use((req, res, next) => {
als.run({ requestId: crypto.randomUUID(), tenant: req.auth.tenant, actorId: req.auth.userId }, next);
});
// Anywhere downstream — the logger, a repository, the audit writer — with no ctx param:
function log(msg: string) {
const { requestId, actorId } = als.getStore() ?? {};
console.log(JSON.stringify({ requestId, actorId, msg }));
}
Carrying tenant and actorId this way is exactly what lets every log line and every audit record say which clinic and which user touched PHI, without a context object threaded through the whole call tree. The caveats are real. There's a small per-await overhead (usually negligible, occasionally not in ultra-hot paths). And context can be lost across boundaries that async_hooks doesn't propagate — a manually managed EventEmitter, certain old callback APIs, a connection pool that batches work across requests. When logs lose their request ID despite ALS, suspect one of those non-propagating boundaries.
The profiling toolchain
You don't guess where the time goes; you measure. The kit, from cheapest to deepest:
perf_hooks.monitorEventLoopDelay()— a histogram of loop lag (mean/p50/p99/max). The canary that the loop is being blocked at all. Wire it to a metric; alert on p99.--prof— V8 writes a tick log;node --prof-processturns it into a text summary of where CPU time went. Zero extra tooling, ugly output, always available.--inspect+ Chrome DevTools — live CPU profiler and heap tools; the interactive option.--cpu-prof/--heap-prof— built-in flags that write profile files on exit, ideal for capturing a short run in CI or a container.- Flamegraphs (e.g.
0x) — the picture you actually read. Width = self-time; wide bars are where the CPU is spent. Plateaus = hot synchronous code (your blocking culprit). Tall thin stacks = deep call chains (not necessarily a problem). GC frames showing up wide = allocation pressure, pointing you back to the heap. clinic(doctor / flame / bubbleprof) — diagnostic layer that attributes latency to categories: event-loop delay vs. GC vs. I/O wait vs. user code.clinic doctoris the "what kind of problem do I have?" first pass.
Graceful shutdown, the mechanism
This is the machinery behind page two and the heart of ADR-008. The sequence:
let draining = false;
const inFlight = new Set<ServerResponse>();
app.use((req, res, next) => { // track in-flight requests
inFlight.add(res);
res.on('finish', () => inFlight.delete(res));
res.on('close', () => inFlight.delete(res));
next();
});
function shutdown() {
if (draining) return; // INVARIANT 3: idempotent
draining = true;
readiness.healthy = false; // INVARIANT 1: flip readiness FIRST
// so the LB stops routing new traffic
server.close(async () => { // stop accepting; callback fires when last conn closes
await pool.end(); // close DB pool
await broker.disconnect(); // stop queue consumers (claims/labs workers)
await logger.flush();
process.exit(0); // INVARIANT 4: clean exit
});
// INVARIANT 2: hard deadline backstop — don't hang forever.
setTimeout(() => {
for (const res of inFlight) res.destroy();
process.exit(1); // forced exit, non-zero
}, DRAIN_DEADLINE_MS).unref(); // .unref() so this timer can't keep the process alive
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
server.close() stops the server accepting new connections and fires its callback when the last existing connection finishes — but note the keep-alive subtlety: idle keep-alive connections can keep the server "open" past your drain, so production setups also close idle sockets (libraries like http-terminator/stoppable exist precisely for this). The setTimeout(...).unref() is the backstop: if draining takes longer than the deadline, force-kill the stragglers and exit non-zero so you know it was forced.
The part tutorials always get wrong is the race with the orchestrator. When Kubernetes decides to remove a pod, it does two things roughly in parallel: it sends SIGTERM, and it removes the pod from the Service's Endpoints (so the LB stops routing to it). These are not ordered — the SIGTERM can arrive before the LB has stopped sending you traffic. If you call server.close() immediately on SIGTERM, you'll refuse requests the LB is still routing → 502s, the very thing you were preventing. The fix is to flip readiness to unhealthy first (or use a preStop sleep) so the LB drains its routing before you stop accepting. We name the full Kubernetes wiring — terminationGracePeriodSeconds strictly greater than your drain deadline, preStop hooks, probe configuration — but defer it:
📎 Borrowed on credit: the container/orchestrator side of shutdown. The process-side state machine — SIGTERM → flip readiness →
server.close()→ drain in-flight → close pools → deadline backstop → exit — is fully yours, here, in this chapter. But how Kubernetes drives it — the Endpoints-removal timeline,preStophooks, settingterminationGracePeriodSecondsabove your drain deadline so the platform doesn'tSIGKILLyou mid-drain, the readiness/liveness probe semantics — is application-of-this-mechanism to a specific platform. That belongs to Chapter 36 (containers & 12-factor). Here you build the contract; there you wire it to the orchestrator that honors it. Why it matters now: your drain logic is only correct if the platform's grace period exceeds your deadline, so know the dependency exists even though we configure it later.
The JVM contrast, where it teaches
(Skip this if you've never touched Java — the transferable payoff is one sentence, and it's spelled out in plain terms.) The contrast sharpens why Node's mechanics are what they are. Java is multi-threaded by default — a classic Spring server dedicates one thread per request from a pool (the default is around two hundred). Blocking I/O is fine there: a blocked thread just parks, the OS schedules another, and one slow request doesn't freeze the others. So backpressure and CPU offload feel different on the JVM — a CPU burst occupies one thread, not the whole app. The price is the opposite set of problems:
- you must size the thread pool — too few and requests starve waiting for a free thread, too many and the CPU spends its time switching between threads instead of doing work;
- and any state shared between threads has to be guarded, because two threads can now touch it at once.
That guarding is where Java grows machinery Node simply doesn't need — volatile, the Java Memory Model, and friends are the low-level rules for safely sharing data between threads, and they're problems Node never has because it never shares in-process state. That's the whole payoff: on a thread-per-request runtime, blocking is cheap but you hand-tune threads and guard shared data; on Node, you never guard shared data but you must never block the one loop.
GC mirrors with a twist: V8's generational collector has cousins in the JVM's G1, ZGC, Shenandoah — also generational, but tuned for concurrent, low-pause collection on large heaps. -Xmx is the moral equivalent of --max-old-space-size. Heap dumps via jmap analyzed in MAT are the JVM's heap snapshots, and the dominator tree is literally the same concept — find the object whose removal frees the subtree. And graceful shutdown rhymes exactly: Spring's @PreDestroy plus server.shutdown=graceful is the same drain state machine — stop accepting, finish in-flight, bounded by a timeout. The transferable lesson: your isolation model dictates your concurrency, memory, and shutdown strategy. Learn the shape once and you can read any runtime.
🛑 What we deliberately did not explain. How the kernel's TCP send buffer actually flushes to the wire (Ch 5). How
epoll/kqueuelets the poll phase block efficiently on many sockets (Ch 7 named it; the OS internals are Ch 4). How V8's incremental marking interleaves with your code to shorten pauses — we used the fact of generational GC, not the marking algorithm's internals. How a background job queue durably retries work across process restarts (that's a different machine from in-process worker threads — see §7's distinction and Chapter 26). We opened the machines you operate; we left the layers below them as named rooms.
5. In production: the configuration the laptop never needed
The mechanics above become operations only when you wire them to numbers and a platform. Here is what actually ships.
Set the heap ceiling relative to the container limit. Rule of thumb: --max-old-space-size ≈ 75–80% of the cgroup memory limit, leaving headroom for external/Buffers, RSS overhead, and the non-old-space heap. A 2 GB pod gets roughly --max-old-space-size=1536. Set it too high and RSS blows past the cgroup limit → kernel OOMKill before GC can run (the confusing "I set the heap and still got 137" — you forgot the external overhead above the heap). Leave it default and a big pod may run a small heap, capping throughput for no reason. This number is a deployment config, not a code constant — it changes with the pod size.
Always pipeline() (or await finished()), never bare .pipe() in a request handler — and always destroy on client disconnect. The export endpoint needs both, plus hardening: set Content-Type and Content-Disposition, honor Accept-Encoding for gzip, paginate the cursor, not a pre-fetched result, cap the export's range/size (and fall back to an async background job for truly enormous exports), time-box the query, and emit progress where the format allows. An unbounded streaming export is both a memory risk and, as §8 covers, a PHI-exfil and DoS surface.
Concurrency topology: one process per core for throughput, a bounded worker pool for CPU. Run one Node per pod and let the orchestrator give you N pods (or cluster if you're on bare metal). Reserve worker_threads for specific CPU tasks — care-gap scoring, a heavy FHIR-bundle parse, document/image processing, crypto — behind a bounded pool like piscina. Never spawn a worker per request: that's unbounded concurrency at a CPU-bound resource, the exact thing pools exist to prevent. A fixed pool of, say, cores - 1 workers, fed by a queue, keeps CPU work parallel and bounded.
Pool every scarce resource, and size it to the downstream's capacity. The DB connection pool is sized to what the database can handle — roughly db_core_count × factor, not "infinite." The pool is your backpressure boundary: when it's exhausted, requests queue with a timeout instead of opening unbounded connections that overwhelm the DB. The same discipline applies to HTTP keep-alive agents (maxSockets) talking to the clearinghouse or a lab partner, Redis clients, and file handles. A pool sized to the app's desire rather than the downstream's capacity just relocates the outage to the downstream.
Wrap request entry in AsyncLocalStorage.run() in middleware, and have the logger and audit writer read the store automatically, so every log line, DB query, and audit record carries requestId/tenant/actorId/trace without anyone passing a context object. This is the difference between debuggable and undebuggable logs under concurrency — and, for PHI access, between a usable and a useless audit trail.
Profile continuously in production, and alert on the leading signals. Cheap sampling profilers run in prod with low overhead; don't rely on reproducing problems locally. The alerts that catch trouble early are event-loop delay p99 (rising lag = you're blocking the loop) and heapUsed growth slope (a positive trend over hours = a leak) — not raw RSS, which is a lagging indicator that only screams once you're nearly dead.
🏭 Wire the shutdown to the platform, and prove it every time. Two operational musts. First, your platform's grace period must strictly exceed your drain deadline:
terminationGracePeriodSeconds>DRAIN_DEADLINE_MS(your container platform configures this), or KubernetesSIGKILLs you mid-drain and you're back to dropping requests. Second, log every shutdown:"drained 187 requests in 2,310 ms". That one line, emitted on every deploy, is how you validate the policy in production — if you ever see "force-killed 12 requests after deadline," your deadline is too short or something hangs, and you found out from a log instead of from a clinician who lost a chart save.
6. Common pitfalls
Each as signature → fix — the symptom you'll observe, then the principle that resolves it.
OOMKill on a large response.
Signature: exit 137; memory profile is flat then a cliff straight up; correlates with one big request.
Fix: don't buffer — stream from a cursor with backpressure (pipeline()), cap the export size, and push truly huge exports to an async background job. Raising the heap limit only postpones the next big clinic.
Memory grows forever; GC can't help.
Signature: a sawtooth that trends upward over hours; heapUsed slope is positive; sometimes a MaxListenersExceededWarning in the logs.
Fix: it's unintended reachability. Hunt the retainer with the three-snapshot diff. Usual causes and their cures: a module-level Map/cache → bound it with an LRU; an EventEmitter listener added per request → off() it, or use an AbortController; a setInterval capturing scope → clearInterval on cleanup.
.pipe() swallows a downstream error and the source keeps reading.
Signature: an export "completes" with truncated output and no error logged; a DB cursor or connection leaks after failed downloads.
Fix: use stream.pipeline() (or stream.finished()) so errors propagate and every stream in the chain is destroyed on failure.
Event-loop stall; p99 spikes across all routes.
Signature: unrelated endpoints (even /healthz) slow together; a CPU flamegraph shows one wide synchronous plateau; loop-delay p99 in the hundreds of ms or seconds.
Fix: move the CPU work to a bounded worker pool. Never JSON.parse a 50 MB FHIR bundle or run sync crypto on the loop. If you must stay on the loop, chunk the work and yield with setImmediate between batches.
Worker offload made it slower.
Signature: you moved work to a worker thread and throughput dropped.
Fix: the structured-clone of a huge payload now dominates. Use a transferList (zero-copy move of an ArrayBuffer) or SharedArrayBuffer; for small tasks, keep them on the main thread — the boundary cost wasn't worth it.
Logs lose request correlation under load.
Signature: request IDs in logs are scrambled — one clinician's query appears under another's request ID — only when traffic is concurrent.
Fix: you used a module-level "current request" variable, which is shared across concurrent requests. Use AsyncLocalStorage so each async chain has its own store.
502 spike on every deploy.
Signature: the LB reports a burst of 502/504 at each rollout; some writes are partial; the billing worker retries into duplicate claims.
Fix: the process exits before in-flight work finishes. Implement the drain state machine: flip readiness, server.close(), track in-flight, deadline backstop — and pair it with idempotent writes so retries don't double-submit.
Kubernetes SIGKILLs you mid-drain.
Signature: shutdown logs show "force-killed N requests" on a process that does drain correctly.
Fix: terminationGracePeriodSeconds ≤ your drain deadline. Raise the grace period strictly above the deadline.
Heap snapshot shows nothing but memory is high.
Signature: rss/external climb while heapUsed and the snapshot stay flat.
Fix: you're leaking native Buffers, which live outside the JS heap. Check process.memoryUsage().external/arrayBuffers and find what retains the Buffers.
Default heap caps throughput needlessly.
Signature: a big pod with plenty of free memory still does frequent GC and won't scale; raising replicas helps but the box is half-idle on memory.
Fix: the default heap is below the container limit. Raise --max-old-space-size explicitly toward 75–80% of the cgroup limit.
7. Tradeoffs
Senior judgment is naming the spectrum and saying why you stand where you stand — and, crucially, when you'd reverse.
Stream ↔ buffer-then-send.
Streaming gives flat memory and arbitrarily large payloads, but harder error handling (you may have already sent a 200 and half the body when the DB errors — no clean failure), no Content-Length up front, and partial-response semantics. Buffering is simpler and gives atomic success/failure. Reverse to buffering when the payload is provably small and bounded and you want clean all-or-nothing semantics. Stream when size is unbounded or large.
cluster ↔ worker_threads ↔ separate service. Cluster (or N pods) buys throughput and crash isolation with no shared memory. Threads buy in-process CPU offload with shared memory but the same heap ceiling — they don't multiply request capacity. A separate service buys independent scaling and deploy and even a different runtime, at network and operational cost. Reverse threads → service when the CPU work needs its own scaling curve, a different language, or a GPU (a risk model, an OCR pipeline).
Raise the heap ↔ add replicas.
A bigger --max-old-space-size delays OOM but lengthens GC pauses (more old space to mark-sweep) and concentrates risk in one fat pod. Horizontal scaling spreads risk and keeps pauses short. Reverse — go vertical — only when the workload is genuinely memory-heavy per request and can't be sharded across pods.
AsyncLocalStorage ↔ explicit param passing.
ALS gives clean signatures and automatic propagation, but hidden coupling, async_hooks overhead, and silent failure across non-propagating boundaries. Explicit ctx passing is verbose but fully visible and free. Reverse to explicit in ultra-hot paths and in libraries (where you don't control how callers wire async).
Drain deadline length. A long deadline drops fewer in-flight requests but makes deploys and rollbacks slow — you're stuck on a bad version longer while it drains. A short deadline ships fast but drops more in-flight work. Tie the number to your p99 request duration, not a guess: a deadline a little above p99 finishes almost everything without making a rollback crawl. (We pin this in ADR-008.)
Pool size. A large pool gives more concurrency but can overwhelm the downstream and hides backpressure (everything seems fine until the DB tips over). A small pool gives strong backpressure and predictable queueing latency. Size to the downstream's capacity, not the app's appetite.
🚫 A framing this book rejects. "
worker_threadsand a job queue are the same thing — both run work in the background, so use whichever." They are not the same machine, and conflating them produces broken systems.worker_threadsare in-process CPU offload: ephemeral, sharing your heap ceiling, gone when the process dies, with no durability — perfect for "score this patient panel off the loop right now and give me the answer back in this request." A job queue (Chapter 26) is durable, out-of-process, retryable work that survives restarts and is meant to outlive the request — "submit this 837 claim to the clearinghouse, fax this referral, and don't lose the task if I redeploy." Use a worker thread to keep a synchronous CPU burst off the loop within a request; use a job queue to defer slow or unreliable work beyond the request. Reach for the wrong one and you either block your loop with work that should be a job, or lose durable work — a claim, a lab order — in a thread that vanished on deploy.
8. Security & scale notes
Security and scale are properties of everything here, not a separate section bolted on. This chapter's mechanics touch both directly.
The export endpoint is a PHI-exfil and DoS surface. A streaming export that works is a one-request way to dump an entire clinic's chart history or pin a database for minutes. So: enforce authorization and row-level scoping (a provider streams their encounters — derive provider_id from the authenticated identity, never from the query string, exactly as the §4 code does, and enforce minimum-necessary access), rate-limit the endpoint, cap the range and size, time-box the query, and — because this is a bulk read of PHI — write it to the audit log like any other chart access. An unbounded export endpoint is a credential away from being a reportable breach.
Unbounded buffering is a memory-DoS, and so is a slow client on the read side. A Slowloris-style client that opens a backpressured export and then reads one byte per minute holds a connection and a DB cursor open indefinitely — your backpressure is working exactly as designed, which is the problem: the slow consumer pins resources. Set socket timeouts, cap concurrent in-flight exports, and let the drain/deadline logic reclaim stuck connections.
Decompression and parse bombs target the single thread. A gzip or JSON payload of attacker-controlled size — a hostile inbound lab result, an oversized FHIR bundle — can blow the heap or freeze the loop while it decompresses/parses, and on one thread, freezing the loop freezes every tenant on that process. Size-limit before you decompress or parse, and if a large parse is unavoidable, do it in a worker so the burst doesn't starve the loop.
Workers share the process — treat cross-channel input as untrusted. A worker that crashes or a SharedArrayBuffer race can corrupt state visible to other requests — meaning one patient's data bleeding into another's response. Validate every message crossing the worker channel as if it came from the network; a worker is not a trust boundary you get for free.
Shutdown under load is exactly when you drop or double-process. In-flight writes interrupted at SIGKILL can leave partial state, and client retries against partial state cause duplicates — a claim submitted twice, an e-Rx sent twice. So graceful shutdown is necessary but not sufficient: pair draining with idempotent writes and an explicit at-least-once contract (an idempotency key on POST /claims, say), so a retried request after a forced kill is a no-op, not a duplicate submission to the payer.
Now scale, where the heap and loop set the limits:
🔑 GC pauses are a latency tail, and per-request allocation is a scale lever. Under load, allocation-heavy hot paths push more objects into old space, which lengthens mark-sweep pauses, which appear as p99 cliffs — sudden spikes for everyone, because the pause runs on the one thread. Reducing per-request allocation (reuse buffers, avoid needless object churn in hot paths, stream instead of materialize) isn't a micro-optimization; it's a scale lever that flattens the tail. This connects straight to performance engineering — the full tail-latency treatment comes later.
📎 Borrowed on credit: tail latency as a discipline. We keep brushing against "p99," "the cliff," "the tail" — GC pauses, cold cursors, a slow client. The systematic treatment of tail latency — why averages lie, how to budget and attribute p99/p999, load-shedding, hedged requests — is its own subject, Chapter 30 (performance engineering & tail latency). Here we only need one fact: the things that bound a Node process's memory and unblock its loop are also the things that flatten its latency tail. Bounded streaming, low allocation, and CPU offload are simultaneously correctness, memory, and latency tools.
Heap snapshots contain PHI. A snapshot is a photograph of everything live in memory — including patient names, tokens, in-flight chart notes and claim details. Treat .heapsnapshot files as sensitive artifacts: restrict who can pull them, store them like secrets, and scrub or red-zone them before sharing in a ticket. Reliability tooling that leaks PHI is its own incident — a debugging habit can become a breach.
Capacity planning is "requests per loop-second per core." You scale this workload by adding processes/pods, not threads — threads share the loop's per-process limits. And loop-delay p99 is your earliest saturation signal, ahead of CPU% and latency alarms: when lag starts climbing, you're approaching the cliff, and that's the moment to add capacity, before the non-linear collapse and the restart-loop that makes a saturated process look dead.
9. Interview lens & exercises
Interview questions
Each question separates levels by reasoning, not recall.
"A /export endpoint OOMs the pod. Walk me through fixing it."
- Junior answer: "add pagination" or "raise the memory limit." Treats a working-set problem as a config knob.
- Senior answer: names the cursor → transform → response backpressure chain that keeps memory at O(highWaterMark), insists on
pipeline()so errors destroy the chain, adds client-disconnect cleanup (res.on('close')→cursor.destroy()) so aborts don't leak connections, caps range/size, and falls back to an async background job for truly enormous exports. Distinguishes "the response is too big" (stream it) from "we have a leak" (different bug).
"cluster vs. worker_threads — when each?"
- Junior: "threads are lighter, use them."
- Senior: frames it as throughput/isolation (processes) vs. in-process CPU offload sharing one heap (threads), notes that threads don't multiply request capacity and that structured-clone serialization cost can erase the offload win, and reaches for a separate service when the CPU work needs its own scaling or hardware.
"Memory grows 40 MB/hour. How do you find the leak?"
- Junior: "restart it" or "raise the heap."
- Senior: separates working set from leak, uses the three-snapshot diff with dominator/retainer analysis to find what holds the graph, checks
externalfor Buffer leaks invisible to the JS heap view, and names the usual suspects — module-level caches, unremoved listeners, interval closures.
"Your deploy causes a 502 spike. Why, and the fix?"
- Junior: "add a retry."
- Senior: describes the drain state machine (flip readiness →
server.close()→ drain in-flight → deadline backstop), explains the readiness-flip-before-SIGTERM race with the orchestrator's Endpoints removal, sets the grace period above the drain deadline, tracks in-flight, and pairs it with idempotent writes so retries don't submit a duplicate claim.
"Why does one slow endpoint tank p99 on unrelated routes?"
- Junior: "Node is single-threaded so it's slow."
- Senior: explains the single event loop + a synchronous CPU burst that starves all other callbacks, measures it via event-loop delay and a flamegraph (the wide synchronous plateau), and offloads the work to a bounded worker pool — distinguishing CPU-bound (offload) from a GC pause (reduce allocation).
Exercises & the Pulsely increment
Do these for real — the increment is the point of the chapter.
-
Pulsely increment — the bounded export. Build
GET /exports/encountersstreaming NDJSON + gzip from apgcursor underpipeline(). Seed ~5M rows. Prove withprocess.memoryUsage()that RSS stays flat as the export runs, then implement the naïvedb.query+JSON.stringifyversion and watch it OOM (exit 137) on the same data. Add client-disconnect cursor cleanup, a size/time cap, and an audit-log entry for the bulk PHI read. This is the whole §4 export path, made yours. -
Pulsely increment — graceful shutdown + ADR-008. Implement the drain state machine:
SIGTERM→ flip readiness →server.close()+ an in-flight counter → close thepgpool → forced-exit backstop on a deadline. Then write ADR-008 — Graceful-shutdown & connection-draining policy. It must state: which signals you handle (SIGTERM/SIGINT); your drain deadline and why it's tied to p99 request duration; the requiredterminationGracePeriodSeconds> drain deadline relationship with the orchestrator; the readiness-flip-before-stop-accepting ordering and the Endpoints-removal race it solves; what gets force-killed at the deadline and the exit code that signals it; and the idempotency assumption clients must satisfy for safe retries (an idempotency key on claim submission). Validate it: hammer the export endpoint with concurrent traffic while sendingSIGTERM, and confirm zero dropped responses and a"drained N requests in M ms"log line. -
Leak hunt. Introduce a module-level unbounded
Mapcache keyed per request; reproduce the steady climb; take three heap snapshots (baseline → exercise → exercise) and find the retainer/dominator in DevTools. Fix it with a bounded LRU. Then plant a Buffer leak, show it's invisible in the JS heap view but plainly visible inprocess.memoryUsage().external, and explain why (Buffers live outside the V8 heap). -
Offload drill. Move Pulsely's CPU-bound care-gap scoring (or a large FHIR-bundle parse) into a
piscinaworker pool. Measure event-loop delay (monitorEventLoopDelay) and p99 before and after, and prove the latency on unrelated endpoints — a clinician pulling up a chart — recovers once the burst is off the loop. Then deliberately trigger the serialization-cost trap: feed the worker a too-large payload via structured clone, watch the offload get slower, and fix it with atransferList.
Key takeaways
- The laptop hides Node's three load-bearing constraints — one JS thread, an OS-bounded heap, cooperative scheduling. Production stresses all three at once.
- Every problem here is bounded flow with backpressure: rows vs. the socket (stream it), allocations vs. death (don't leak), one handler's CPU vs. the loop's fairness (offload it), new requests vs. a dying process (drain it).
- The backpressure invariant: honor
write()'s return value and'drain'; usepipeline()(never bare.pipe()) so memory is O(highWaterMark), not O(rows), and errors destroy the whole chain. - Memory is two questions: working set (bounded by streaming/pools) and leaks (unintended reachability — the GC can't reclaim reachable-but-forgotten). Find leaks with the three-snapshot diff; remember Buffers live in
external, outside the JS heap. - Scale processes for throughput, threads for in-process CPU offload, a service for independent scaling — and
worker_threads(ephemeral, in-process) are not a durable job queue. - Carry per-request context with
AsyncLocalStorage, never a global, or your logs and PHI audit trail scramble under concurrency. - Shutdown is a state machine —
RUNNING → DRAINING → CLOSED— with four invariants (no new requests, bounded in-flight, idempotent, meaningful exit code), flipping readiness beforeserver.close()to win the orchestrator race. ADR-008 writes the policy down. - GC pauses and unbounded streams are also latency-tail problems; bounded streaming, low allocation, and CPU offload flatten p99.
← Previous: Ch 7 — The Node Event Loop · Up: Part II overview · Master TOC · Next: Ch 9 — TypeScript & the JVM Contrast →