Chapter 3 — OS & Runtime Fundamentals: Processes, Threads, Memory, Syscalls
Part I · Foundations | Prerequisites: Ch 2 | Builds: intuition for what one connection/process actually costs the OS
Earlier you built a server from the floor up: a process that owns a listening socket, runs an accept loop, and frames HTTP out of raw bytes. You proved to yourself that "the server" is a process holding a file descriptor. This chapter pays off the next instalment of that promise by zooming in one more level — not to the wire, but to the machine the process runs on.
Because here's the thing nobody tells the pivoter. Every scaling decision you will ever make — replica counts, container memory limits, the dreaded "why did it fall over at 2 a.m. when CPU was only 5%" — comes down to the same thing. Your process consumes a handful of finite, named OS resources (CPU time, memory pages, file descriptors) through syscalls, and scaling is just an argument about which of those runs out first. Get the units right and capacity planning stops being superstition and becomes arithmetic.
You write code in functions and requests. The kernel keeps its books in processes, pages, descriptors, and scheduler time-slices. Outages live in the gap between those two vocabularies. This chapter is about closing the gap — not so you can become a kernel hacker, but so that when the pager goes off you can reason from the OS up instead of guessing from the framework down.
1. The problem: the outage your app logs can't explain
It's 2 a.m. and Pulsely v0 — the bare HTTP service you built earlier — has stopped accepting connections. The night-shift clinicians trying to pull up charts get ECONNREFUSED or just hang. You SSH in, braced for a runaway loop or a memory bomb, and find… nothing. CPU is sitting at 5%. There are gigabytes of free RAM. The app logs are clean: the last line is a perfectly ordinary chart-fetch, served fine, and then silence. Nothing your code did explains why the process won't take new callers.
The cause isn't in your code at all. It's EMFILE: too many open files — the process hit the kernel's per-process cap on open file descriptors, and since a connection is a file descriptor, the moment you ran out of fds the server could no longer accept(). The default cap on a fresh box is often 1024. You weren't leaking memory; you were leaking handles, or simply holding more connections than the OS would let one process own. No amount of staring at your handler code would have found it, because the limit that broke you was never in your code's vocabulary.
Now a second incident, a week later, different meter. Pulsely's RSS climbs steadily to 4 GB and then the process just vanishes. No stack trace, no graceful exit — the encounter a provider was signing simply never saved. You check dmesg and there it is: Out of memory: Killed process 18271 (node). The OOM killer — a kernel mechanism, not your app — reaped you for crossing a memory limit. In application terms there was "no leak": no growing array you could point to. The real problem was that nobody had ever answered the question how much memory does one request cost me? — so nobody noticed that a thousand of them in flight cost more than the box (or the container limit) could give.
🧭 Mental model. Developers reason in functions and requests; the kernel reasons in processes, pages, descriptors, and time-slices. Almost every "mystery" outage is a resource exhausted in the kernel's vocabulary while everything looks fine in yours. The fix is not to memorize incantations — it's to learn the kernel's accounting units well enough that you can predict which meter saturates first, and watch it.
This is foundational precisely because every later topic in the book is an allocation of one of these resources. A connection pool budgets fds and memory. A thread pool budgets execution. A worker concurrency limit budgets CPU. A container memory limit and an autoscaler are arguments about RSS and CPU time. Get the units right now, in this chapter, and the rest of the book is arithmetic on top of them.
2. The mental model: one process, three meters
Hold this picture for the rest of the book. A running server is one (or a few) processes. Each process is three things bundled together:
- An isolated virtual address space — its own private view of memory, which no other process can read.
- A table of kernel-managed handles — the file descriptors: every open socket, file, pipe, and timer is an integer in this table.
- One or more threads of execution — the things the scheduler time-shares onto physical CPU cores.
That's the anatomy. Now the operating insight: a process is a consumer standing at three meters, and each meter can take the whole server down on its own.
┌─────────────────────────┐
│ your process │
│ (one address space, │
│ one fd table, N │
│ threads of execution) │
└───────────┬─────────────┘
│ consumes
┌───────────────────────┼───────────────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ CPU-TIME│ │ MEMORY │ │ FDs │
│ meter │ │ meter │ │ meter │
│(scheduler │ (pages/ │ │ (handle │
│ slices) │ │ RSS) │ │ table) │
└─────────┘ └─────────┘ └─────────┘
capacity = MIN(across the three meters), never the average
The 2 a.m. page was the fd meter pinned while the other two sat idle. The OOM kill was the memory meter pinned. A CPU-bound handler that freezes everything is the CPU-time meter pinned. Your effective capacity is the minimum across the three, not the average — which is exactly why "we have plenty of RAM and CPU" is no comfort when fds are gone.
🔑 The minimum-meter invariant. A server's capacity is the smallest of its three resource budgets, not the comfortable-looking average. You can be drowning on one meter while two others idle. This is why load testing must watch all three at once, and why "CPU is low so we're fine" is one of the most expensive sentences in this book.
Two more pieces complete the model.
The kernel is a gatekeeper, not a library. Your code runs in user space, and user space is deliberately powerless: it cannot touch a disk, send a packet, or create a thread by itself. To do anything privileged it must ask the kernel through a syscall — a guarded doorway with a real toll. This is not bureaucracy; it's the only reason a buggy or hostile process can't read another process's memory or scribble on the network card. In a system holding PHI, that same wall is what stops one tenant's process from reaching into another's memory.
A connection is not a thread and not a process. This is the single most load-bearing correction in the chapter. A connection is mostly a file descriptor, plus a pair of kernel socket buffers, plus a little user-space bookkeeping — measured in kilobytes, not megabytes, and it consumes zero execution while it sits idle. Internalizing this is precisely what lets one Node process hold ten thousand connections on a few megabytes of RAM. The connection count and the count of things-that-execute are different numbers, decoupled by design.
Carry forward this durable shape: request → thread of execution → syscalls → kernel resources. Every performance story you will ever debug is a bottleneck somewhere on that chain.
3. Theory & invariants
A mental model tells you how to picture the machine. Invariants tell you what stays true when you're tired and the pager is loud. These are the load-bearing rules; later chapters will lean on every one.
Two worlds, one guarded door
🔑 The user/kernel boundary. Your process lives in user space and can do nothing privileged — no I/O, no fork, no socket — without crossing into kernel space via a syscall. The boundary is a hardware-enforced protection ring (a privilege level baked into the CPU chip itself, not a software check your code could bypass), and crossing it is mandatory for I/O and intentionally expensive. Every byte Pulsely reads off a socket is a trip through this door.
That expense is structural, not incidental. A syscall costs a mode switch (the CPU flips from user to kernel privilege and back), register save/restore, and cache/TLB disturbance — on the order of hundreds of nanoseconds to a few microseconds. That is dirt cheap next to a disk seek, but enormous next to a plain function call. Hold that ratio: it is the entire reason buffering, batching, and event loops exist. You do not pay the toll once per byte if you can pay it once per 64 KB.
Processes: isolation bought with duplication
🔑 Process invariants. Each process gets an isolated address space (process A literally cannot read process B's memory), its own fd table, its own PID. When a process
fork()s a child, the two share physical pages copy-on-write — identical until one writes, then the touched page is duplicated. Isolation is the guarantee; the cost you pay for it is duplication.
Isolation is why one crashing process can't corrupt its neighbor, and why "one container per process" gives you a clean blast radius. The cost is that processes don't share state cheaply — to communicate they must go through the kernel (pipes, sockets, shared memory you set up explicitly).
Threads: sharing bought with danger
🔑 Thread invariants. Threads within one process share that process's address space and fd table, but each has its own stack and registers. Sharing is cheap — no copy, no kernel hop to pass data — and dangerous: two threads touching the same memory without coordination is a data race. Threads are the exact inverse tradeoff of processes: cheap sharing, costly safety.
So the process/thread choice is a single dial between two failure modes: processes give you safety at the cost of cheap communication; threads give you cheap communication at the cost of safety. Neither is "better." The workload decides.
Connection ≠ unit of execution
🔑 Concurrency model is a choice, decoupled from connection count. N concurrent connections can be served by one thread (an event loop), a fixed pool of threads, or N threads/processes. The number of connections and the number of executors are independent quantities. A later chapter is a full derivation of why one-thread-per-connection stops working around ten thousand connections — but the seed is here: connections are cheap state, executors are expensive, and you get to choose how many executors juggle how many connections.
Virtual memory: VSZ versus RSS
Every process sees a flat, private, enormous address space — as if it owned all of memory. Here's how that illusion is kept, in slow motion:
- Every process is handed what looks like a huge private block of memory.
- In reality the kernel, helped by a chip on the CPU called the MMU (memory management unit), only hands over a real chunk of physical RAM the first time the process actually touches that address — never before.
- This lazy hand-out has a name: demand paging.
In plain terms: you reserve the whole address space up front, but you only pay in real RAM for the parts you use. That distinction produces the two numbers that confuse more engineers than any other pair:
🔑 VSZ vs RSS — the number that OOM-kills you. VSZ (virtual size) is the address space the process has reserved or mapped — often gigabytes, frequently mostly untouched, and largely meaningless for capacity. RSS (resident set size) is the physical RAM actually backing the process right now — and RSS is the number the OOM killer reads. Alert on RSS. A VSZ of 8 GB on a process using 200 MB of real memory is normal and harmless; an RSS approaching your container limit is a countdown.
Stack versus heap
Two regions of that address space behave by opposite rules:
- Stack — per-thread, LIFO, fixed and bounded in size, automatically managed (a function's frame pops when it returns). Overflow it (unbounded recursion) and you get a hard, immediate
stack overflow. - Heap — process-wide, dynamically allocated, and must be reclaimed — by a garbage collector in Node and the JVM, by
free/RAII elsewhere. Exhaust it and you get a different failure: allocation failure or OOM.
Stack overflow and heap exhaustion are genuinely different bugs with different signatures; conflating them sends you debugging the wrong region.
File descriptors are a finite, integer table
🔑 The fd invariant. File descriptors are a finite, integer-indexed table per process (with a system-wide cap above it). Sockets, regular files, pipes, epoll instances, timers — all of them consume an fd. An fd you open and never close is leaked forever, until the process dies. Run out and you cannot
accept(),open(), orconnect()anything:EMFILE. The 2 a.m. page was this invariant collecting its debt.
These rules are not trivia. The rest of the book — pools, workers, limits, autoscalers — is engineering against them.
4. Under the hood: a syscall, the loop, and where memory hides
Let's kill the magic, the way we did with the spine earlier. We'll trace a syscall, look at how Node actually waits on thousands of connections, find out where its memory really lives, and contrast it with the classic JVM model — just enough mechanics that the later deep dives have somewhere to land.
Anatomy of a syscall
When Pulsely reads a socket, the path looks like this:
your JS ─▶ libuv binding ─▶ libc wrapper ─▶ `syscall` instruction (TRAP)
│
┌───────▼────────┐
│ KERNEL SPACE │
│ syscall handler│
│ does the work │
└───────┬────────┘
│ return
your JS ◀────────────── result bubbles back ◀────────┘
The syscall instruction is a controlled trap into the kernel: the CPU switches privilege level, jumps to a fixed kernel entry point, the handler runs, and control returns to your code at the next instruction. Two distinct costs hide here, and confusing them muddles every performance conversation:
- A mode switch is user↔kernel within the same process. Relatively cheap. Every syscall pays at least this.
- A context switch is the kernel saving one task's entire state and loading another task's — different process or thread entirely. This is the expensive one: it throws away the CPU's fast-access caches and the TLB (the small lookup table that maps virtual to physical memory addresses), so for a while after the switch even normal work runs slow because those caches have to refill. If you've felt the difference between a hard browser reload and a client-side route change, that's the intuition — the route change reuses everything already in memory, while the full reload cold-starts the whole cache and the first few interactions feel sluggish. Context switches are why over-subscribing threads (far more runnable threads than cores) quietly destroys throughput even when CPU "looks busy."
You don't have to take this on faith. Run strace -c -f -p <pid> against Pulsely under load for a few seconds and you'll see the syscall histogram: epoll_wait, read, write, accept4 dominating the counts. That list is a server's job description, written in the kernel's words.
How one thread waits on ten thousand connections (Node/libuv)
Here is the mechanism behind the slogan "Node handles many connections with one thread" — stated carefully, because the full derivation and the event-loop mechanics are borrowed on credit just below, and we will not trespass.
The single JS thread runs an event loop. For network I/O on Linux, the loop uses epoll: instead of dedicating an executor to each socket and asking each one "any data yet?", the kernel maintains the watch-list and a single syscall — epoll_wait — returns "these N fds are ready to touch right now without blocking." One syscall reports readiness across thousands of fds. The thread then services only the ready ones and goes back to waiting. The trick is readiness notification, not thread-per-connection — and it works precisely because, as §2 said, an idle connection consumes no executor.
📎 Borrowed on credit: the event loop and libuv internals. Why a single-threaded readiness loop is the inevitable answer to many concurrent connections — and exactly how
select/poll/epolldiffer and trigger — is derived in Chapter 4 (I/O & concurrency models), and the loop's phase-by-phase mechanics are dissected in Chapter 7. Here we only need the shape: one thread, oneepoll_wait, readiness over many fds. We deliberately stop at the door.
One more piece: not all work is network I/O. Some operations — filesystem calls, DNS lookups, crypto, compression — have no clean non-blocking kernel interface, so libuv offloads them to a small thread pool (UV_THREADPOOL_SIZE, default 4). When your fs- or crypto-heavy service mysteriously serializes at four concurrent operations, that default is why.
Where Node's memory actually lives
process.memoryUsage() exposes the truth, and it surprises almost everyone:
- V8 heap — your JavaScript objects, GC-managed, capped by
--max-old-space-size. Shows up asheapTotal/heapUsed. - Off-heap —
Buffers, native addon memory, libuv internals, thread stacks. Shows up asexternalandarrayBuffers, not in the heap numbers.
And critically:
🏭 RSS = V8 heap resident + off-heap. A
Buffer-heavy service — say, Pulsely streaming scanned intake forms or lab-result attachments through its upload endpoint — can blow its RSS past the container limit and get OOM-killed whileheapUsedsits flat and the V8 heap limit is never hit. The "memory leak" that isn't a JS leak is almost always off-heap growth: un-paused streams, in-memory queues, buffers you never released. Whenrss/externalclimb butheapUseddoesn't, stop profiling the heap and go hunt the Buffers.
Counting fds
Every socket, file, and timer in Node is an fd. Count them three ways: ls /proc/<pid>/fd | wc -l, lsof -p <pid>, or process.report. A socket you never .destroy() or .end() is a leaked fd — and a thousand of those is your EMFILE page.
The JVM contrast: thread-per-request and the memory wall
(Skip the Java specifics if they're not your world — the transferable payoff is the arithmetic, not the framework.) The enterprise lens makes the concurrency-is-a-choice point concrete. Classic Java on Tomcat uses thread-per-request: each in-flight request occupies one OS thread, and each OS thread reserves a stack — typically 512 KB to 1 MB. The arithmetic is brutal and clarifying:
Node (event loop): 10,000 connections → 1 JS thread + small libuv pool
+ 10,000 fds + socket buffers ≈ a few MB of executor cost
Tomcat (thread/request): 10,000 concurrent requests → ~10,000 threads
× ~1 MB stack ≈ ~10 GB reserved, before any work
// Spring MVC — one OS thread is bound to this call for its whole duration,
// blocking on the DB. Simple to write; that's the appeal. Each in-flight
// request = one thread = ~1 MB stack. Connection count ≈ thread count ≈ a wall.
@GetMapping("/patients/{id}/encounters")
public EncounterList encounters(@PathVariable String id,
@AuthenticationPrincipal Clinician clinician) {
return encounterService.forPatient(id); // blocks the thread until the DB answers
}
// Node — the same handler does NOT own a thread while awaiting the DB.
// The await yields the single thread back to the loop to serve others.
app.get('/patients/:id/encounters', async (req, res) => {
const encounters = await encounterService.forPatient(req.params.id); // thread is FREE during this wait
res.json({ items: encounters });
});
Neither is "better" — that's the whole point. Thread-per-request gives you blocking code that reads top-to-bottom and trivial CPU parallelism, at the cost of a hard memory ceiling. The event loop gives you enormous connection density at low memory, at the cost that a single blocking call poisons everyone (more on that in §6). Modern Java muddies the line with NIO selectors and virtual threads, which is itself proof that the concurrency model is a dial, not a property of the language.
CPU scheduling, briefly
The kernel scheduler is preemptive: it slices CPU time across runnable threads, parking and resuming them. Two things every backend engineer must know:
- Load average is not CPU%. It counts tasks that are runnable or in uninterruptible sleep (often disk I/O), not the percentage of CPU burned. A load average of 8 on a 4-core box means tasks are queueing for cores. You can have high load with modest CPU% (I/O wait) — reading them as the same number sends you tuning the wrong meter.
- A CPU-bound handler starves the Node event loop. Because there's one JS thread, a synchronous 500 ms computation parks every other connection for 500 ms — health checks time out, the whole service stalls, and every clinician waiting on a chart waits with it. A thread-per-request server wouldn't stall the same way; the busy thread just keeps one core while others serve. This asymmetry is the price of the event loop's density.
Signals: how the OS taps your process on the shoulder
Signals are asynchronous notifications from the kernel to your process. The ones a server operator must know:
SIGTERM— "please shut down." Catchable. This is what orchestrators (Kubernetes, systemd) send first on a deploy. You get to run cleanup.SIGKILL— "shut down now." Uncatchable, immediate, no cleanup. Sent after the grace period expires if you didn't leave.SIGINT— Ctrl-C in your terminal.SIGSEGV— you touched memory you shouldn't (segmentation fault).SIGCHLD— a child process you spawned has exited.
Node exposes the catchable ones as events: process.on('SIGTERM', …).
🏭 Ignoring
SIGTERMmeans dropping in-flight requests on every single deploy. If your process doesn't handleSIGTERM, the orchestrator's polite "wind down" is wasted, the grace period elapses, andSIGKILLsevers every connection mid-flight — including the one saving a signed encounter. The mechanics of doing this right — stop accepting, drain, then exit — are owned by Chapter 8 (graceful shutdown); here we only establish why the signal matters: it's the OS handing you a chance to leave cleanly, and throwing it away is self-inflicted downtime stamped on every release.
5. In production: setting limits before they set you
The default limits on a fresh box are toys. Production is the discipline of choosing the real ones deliberately, before the meter you forgot about pins at 2 a.m.
Raise the fd limit on purpose. The per-process cap is ulimit -n, with a soft and hard value. The infuriating gotcha: setting it in your interactive shell does nothing for a process the orchestrator launches. The limit must be set where the process actually starts — systemd's LimitNOFILE=, /etc/security/limits.conf, a container's --ulimit nofile, or the k8s pod spec. The default of 1024 is fine for a laptop demo and absurd for a server holding thousands of keep-alive connections. Raise it before you need it.
Make the memory limit and the heap limit agree. Two limits govern Node's memory, and they must be set with a relationship, not in isolation:
- the cgroup memory limit (a cgroup is the Linux mechanism Kubernetes and Docker use to cap how much memory and CPU a container may use; in k8s it's
resources.limits.memory) — cross it and the kernel OOM-kills you. - the V8 heap limit (
--max-old-space-size) — cross it and V8 throws a clean JS OOM you can at least log.
🏭 Set the heap limit below the cgroup limit, with headroom for off-heap. If
--max-old-space-sizeexceeds the cgroup limit, V8 happily keeps allocating past the container's ceiling and you get OOM-killed (silentSIGKILL) instead of a clean, logged V8 OOM. And remember §4: RSS = heap + off-heap, so leave room above the heap limit for Buffers and native memory. The classic footgun is the container that thinks it has the whole host's RAM — older runtimes that don't read the container's cgroup limit and instead size the heap to the whole physical host's RAM, so V8 thinks it has, say, 64 GB when the container is capped at 512 MB, and gets OOM-killed almost immediately.
Graceful shutdown, in shape. On SIGTERM: flip the readiness probe to "not ready" so the load balancer stops routing to you, call server.close() to stop accepting new connections, drain the in-flight ones, then exit — all inside the orchestrator's terminationGracePeriodSeconds. (Full mechanics: Chapter 8.)
Watch all three meters. The triage loop that would have prevented both opening incidents:
/proc/<pid>/status → VmRSS, VmSize, FDSize, Threads
/proc/<pid>/limits → the actual fd/memory caps THIS process got
ls /proc/<pid>/fd | wc -l → current open fd count
vmstat 1 → `cs` (context switches), run queue, memory
cgroup memory.current vs memory.max → RSS against the real limit
Export RSS and open-fd count as metrics, and — this is the line that earns its keep — alert on fds approaching the ulimit. An alert at 80% of the fd cap is the alert that turns a 2 a.m. page into a Tuesday-afternoon ticket.
One process leaves N−1 cores idle. A single Node process uses one core for JS. To use a whole machine you run one process per core — historically via cluster or PM2, but the modern preference is one container per process, replicated by the orchestrator, so the scheduler treats each as an independent, separately-limited unit. If you run a single Node process on an 8-core box and wonder why throughput caps early, this is why.
Tuning knobs that actually move the needle. UV_THREADPOOL_SIZE for fs/crypto-heavy services (raise it only when you've measured the pool as the bottleneck); socket keep-alive timeouts to release idle fds back to the table; listen() backlog for accept-queue depth.
6. Common pitfalls
Each is written signature → fix: the symptom you'll observe, then the principle that resolves it.
EMFILE: too many open files.
Signature: the process stops accepting connections; CPU and RAM look fine; logs are clean. New accept()/connect()/open() calls fail with EMFILE.
Fix: find the leak with lsof -p <pid> or ls /proc/<pid>/fd — usually sockets or streams never .destroy()/.end(). Close every fd, raise LimitNOFILE where the process launches, and add an open-fd-vs-limit metric and alert. Distinguish a leak (fd count rises and never falls) from legitimate load (high but stable) — the fix differs.
OOM-killed silently.
Signature: the process vanishes with no stack trace; dmesg | grep -i kill shows Killed process … (node). App logs end mid-stride because SIGKILL is uncatchable.
Fix: set --max-old-space-size below the cgroup limit so you get a catchable V8 OOM instead; profile both heap and off-heap; size the container for real measured RSS, not VSZ.
The "memory leak" that's actually off-heap growth.
Signature: heapUsed is flat but rss and external/arrayBuffers climb steadily.
Fix: track external and arrayBuffers, not just the heap. Hunt unbounded buffering — un-paused streams, in-memory queues, request bodies read without a cap.
A CPU-bound handler freezes the entire server.
Signature: one synchronous loop (a big JSON parse, a sync crypto call, an O(n²) over a large array) runs, and every connection stalls at once; health checks time out and the LB ejects a process that isn't actually dead.
Fix: never run unbounded synchronous work on the event-loop thread. Offload to a worker thread, the libuv pool, or a separate service. This is the dark side of the event loop's density — one blocking call is everyone's blocking call.
Deploys drop in-flight requests.
Signature: every release produces a little spike of 502s and severed connections.
Fix: handle SIGTERM — flip readiness, stop accepting, drain, exit within the grace period. The absence of a handler is the bug.
Reading VSZ and panicking.
Signature: top shows VSZ in the gigabytes and someone declares a leak.
Fix: VSZ is mapped address space, routinely huge and benign. Alert on RSS against the cgroup limit. VSZ is noise; RSS is the number that kills you.
Raised the ulimit in the shell, but the service still has 1024.
Signature: you ran ulimit -n 65536, restarted nothing meaningful, and EMFILE returns.
Fix: the interactive shell's limit doesn't propagate to an orchestrator-launched process. Set it in the systemd unit / container spec / pod manifest — wherever the process is actually born — and verify via /proc/<pid>/limits.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand. Every dial here is a choice between exhausting one meter and exhausting another.
Process-per-X ↔ thread-per-X ↔ event loop. Processes buy isolation and crash-safety (one segfault doesn't take the others) at the cost of memory and expensive communication. Threads buy memory density and cheap sharing at the cost of data-race danger. An event loop buys connection density at low CPU and memory at the cost of catastrophic sensitivity to any blocking call. You reverse toward processes when blast radius matters, toward the event loop when you have many slow, idle, I/O-bound connections, and away from the event loop the moment the workload turns genuinely CPU-bound.
Thread-per-request (Java/Tomcat) ↔ event loop (Node). Threads give you blocking code that reads linearly and trivial CPU parallelism, but a hard memory ceiling (~1 MB/thread) and context-switch overhead at high concurrency. The event loop gives you ten thousand cheap connections on one thread, but stalls entirely if any handler blocks. Pick threads for CPU-heavy, lower-concurrency request work; pick the event loop for many slow or idle I/O-bound connections — Pulsely's care-team messaging fan-out and vitals-alert long-polls are textbook event-loop territory.
More connections ↔ more memory. "Support more concurrent connections" is never free — each connection costs an fd, a pair of kernel socket buffers, and user-space bookkeeping. Raising the connection cap is raising the RAM and fd budget. The honest move when RSS is the constraint is to bound max concurrent connections deliberately rather than let the OOM killer choose the cutoff for you, randomly, at the worst moment.
One big process ↔ many small ones. Fewer processes mean lower baseline overhead but a single OOM or segfault takes everything down together. Many small processes cost more baseline memory but give you blast-radius isolation and scheduling flexibility. Reverse toward more, smaller processes when an outage's blast radius is what you most need to contain.
Tuning UV_THREADPOOL_SIZE up. More parallelism for fs/crypto work, paid for in more thread stacks (RSS) and more context switches. Raise it only when measurement proves the pool is the bottleneck — speculative tuning here just adds RSS and scheduler churn for nothing.
🚫 A framing this book rejects. "Just add more threads — threads are how you handle more load." It feels obvious and it's a trap: every thread reserves a stack (~1 MB) and adds context-switch pressure, so past the core count you buy memory and scheduler thrash, not throughput. More threads is not more capacity; it's a different — often worse — allocation across the same three meters. Concurrency is a model you choose, not a quantity you crank.
8. Security & scale notes
Security and scale are properties of everything, so we weave them in rather than quarantine them. At the OS level they converge on one idea: a resource limit is simultaneously a capacity number and an attack surface.
fd/connection exhaustion is a denial-of-service vector. The very fd table that the 2 a.m. page exhausted by accident can be exhausted on purpose. Slowloris-style attacks — which you've already met as a wire-protocol hazard, and which a later chapter defends properly — hold connections open precisely to consume your fds and accept capacity until legitimate clients can't get in. For a clinical system, "legitimate clients can't get in" means clinicians locked out of charts, so this is a patient-safety concern, not just an uptime metric. The defenses live at the OS budget: connection and request timeouts that release fds, a max-connection cap, and a front-line proxy that absorbs the trickle. The limit is the surface you defend.
Memory amplification is a DoS too. An unbounded request body, or buffering a whole upload in memory, lets a small request drive large RSS — and a handful of them OOM-kills the process. Enforce body-size limits and backpressure so that one cheap request can't cost you the whole memory meter.
The user/kernel boundary is itself a trust boundary. Syscalls are exactly where an untrusted user request turns into a privileged kernel action. That makes least-privilege an OS-level concern: run containers as non-root, drop capabilities you don't need, and use seccomp to shrink the set of syscalls the process is even allowed to make. The payoff is blast-radius: a compromised process handling PHI can only do what its remaining syscall surface permits, so a tight surface turns a full breach into a contained one.
Under load, the bottleneck migrates between meters. This is the scale lesson the three-meter model exists to teach. As connections climb, the first meter to saturate is workload-dependent — event-loop CPU or syscall rate for chatty small requests, fds for many idle keep-alives, RSS for buffer-heavy document uploads. So load testing must watch all three at once, because the one that pins first is the one that defines your real capacity. The context-switch count (vmstat's cs column) is the early-warning gauge that you've over-subscribed threads and started paying churn instead of buying work.
🔑 Capacity is the first meter to saturate, and it moves. You cannot capacity-plan against a single number, because which meter pins first changes with the workload. Plan against the minimum across all three, instrument all three, and re-check which one is closest to the edge as traffic shape changes. The meter you're not watching is the one that pages you.
Noisy neighbors. Without cgroup CPU and memory limits, one greedy process starves its co-tenants on a shared host. Limits aren't only a safety rail against your own bugs — they're the isolation that keeps your service's bad day from becoming everyone's.
9. Interview lens & exercises
Interview questions
Backend interviews probe whether you reason about the machine or merely recite it. The level shows in the narration.
"What's the difference between a process and a thread, and when would you choose one for a server?"
- Junior answer: "Processes are heavier; threads share memory." True and shallow.
- Senior answer: narrates the isolation-vs-density tradeoff — processes give crash blast-radius safety at the cost of duplication and expensive communication; threads give cheap sharing at the cost of data races and a ~1 MB-per-thread memory ceiling — and lands the concurrency-model-is-a-choice point, naming the workload (CPU-bound favors threads/parallelism; many idle I/O-bound connections favor the event loop) that flips the decision.
"You're getting EMFILE: too many open files in production — walk me through diagnosis and fix."
- Junior: "Raise the ulimit."
- Senior: distinguishes a leak from legitimate load, uses
lsof//proc/<pid>/fdto find unclosed sockets, fixes the leak and raisesLimitNOFILEand adds a proactive fd-vs-limit alert — and notes that the limit must be set where the process is launched (systemd/container), not in the interactive shell.
"RSS vs VSZ — which do you alert on, and why?"
- Junior: "They're both memory."
- Senior: RSS is the physical RAM backing the process and the OOM-kill trigger; VSZ is mapped address space, often huge and benign. Alert on RSS against the cgroup limit, with headroom reserved for off-heap Buffers.
"How does a single-threaded Node server handle thousands of concurrent connections?"
- Junior: "It's async."
- Senior:
epollreadiness notification over non-blocking sockets — oneepoll_waitreports which of thousands of fds are ready — plus a small libuv thread pool for genuinely blocking work; and explicitly notes that a CPU-bound handler breaks the model by parking the one thread for everyone.
"What happens, at the OS level, when your service gets a deploy?"
- Junior: "It restarts."
- Senior: the orchestrator sends
SIGTERM(catchable) → you flip readiness, stop accepting, drain in-flight → if you overrun the grace period,SIGKILL(uncatchable) severs everything. No handler ⇒ dropped in-flight requests on every release.
Exercises & the Pulsely increment
Do these against the real Pulsely v0 process you built earlier. The goal is a number, not a vibe.
-
(Pulsely increment) Build the per-connection budget. Record a baseline from
/proc/<pid>/status(VmRSS,FDSize,Threads) andprocess.memoryUsage(). Then, with a load generator, hold 1, 100, and 1,000 idle keep-alive connections. Measure ΔRSS per connection and Δfd per connection, and write the one-line budget: "one idle keep-alive connection costs ≈ X KB RSS + 1 fd + one socket-buffer pair." That sentence is the unit every later capacity decision multiplies. -
Reproduce
EMFILEon purpose. Lowerulimit -nto something small, open connections until the server stops accepting, and confirm the failure signature —EMFILE, low CPU, free RAM, clean app logs. Now you'll recognize the 2 a.m. page on sight. -
stracethe job description. Runstrace -c -fagainst Pulsely under load for ten seconds. Identify the top three syscalls by count and by time, and explain in a sentence each whyepoll_wait/read/writedominate. You're reading the server's work in the kernel's own words. -
Force the off-heap surprise. Stream large
Buffers — say, scanned intake forms or lab attachments — through the service without backpressure and watchrss/externalclimb whileheapUsedstays flat: the "leak that isn't a leak." Then add a body-size limit and re-measure to prove the cap holds RSS down. -
Prove graceful shutdown saves requests. Add a
SIGTERMhandler that stops accepting, drains in-flight requests, and exits. Under steady load from a generator, trigger a restart and confirm zero in-flight requests are dropped — then compare against the no-handler baseline that drops them. (Mechanics owned by Chapter 8; here you're just seeing the difference the signal makes.)
Key takeaways
- A server is a process consuming three finite, named OS resources — CPU time, memory pages, and file descriptors — through syscalls. Capacity is the minimum across the three meters, never the average.
- The outage your app logs can't explain is almost always a resource exhausted in the kernel's vocabulary (
EMFILE, OOM-kill) while everything looks fine in yours. - A connection ≠ a unit of execution. A connection is mostly one fd + socket buffers + bookkeeping and consumes zero execution while idle — which is why one thread can hold ten thousand of them. The concurrency model is a choice decoupled from connection count.
- VSZ vs RSS: VSZ is mapped address space (often huge, benign); RSS is physical RAM and the number that OOM-kills you. Alert on RSS, against the cgroup limit, with headroom for off-heap Buffers.
- A syscall crosses a guarded user/kernel boundary at real cost (mode switch always; the expensive context switch when the kernel swaps tasks) — which is why buffering, batching, and readiness loops exist.
- Node serves many connections via
epollreadiness on one thread plus a small libuv pool; a single blocking/CPU-bound call stalls everyone. The JVM's thread-per-request model trades that density for a ~1 MB-per-thread memory wall — proof the model is a dial, not a property of the language. - Set limits where the process is born (fd caps, heap below the cgroup limit, graceful-shutdown grace periods), and instrument all three meters — the one you don't watch is the one that pages you.
- Every later chapter — concurrency models, the event loop, pools, workers, autoscalers — is an allocation of the resources you just learned to count.
← Previous: Ch 2 — The Server as a Process · Up: Part I overview · Master TOC · Next: Ch 4 — I/O & Concurrency Models →