Skip to main content

Chapter 2 — The Server as a Process: Sockets, Ports & the Accept Loop

Part I · Foundations | Prerequisites: Ch 1 | Builds: Pulsely v0 — a raw TCP server that speaks HTTP/1.1 by hand

Earlier you drew the spine — browser → DNS → TCP → TLS → load balancer → server → handler → database — and I promised that every later chapter would zoom into one box. This is the first zoom. We are climbing inside the box labeled server and turning on the lights, and what we find is going to feel almost insultingly simple after all the framework magic you're used to: a server is a long-lived process that holds one special file, sits in a loop saying "next, please," and reads and writes raw bytes. There is no app.get. There is no router. There is no JSON. Those are conveniences you will build on top of the floor, and you cannot reason about timeouts, keep-alive, backpressure, or half the production outages in this book until you have stood on the floor yourself.

So we are going to build a web server with no web framework — not even Node's http module — accept a connection by hand, parse an HTTP/1.1 request out of the byte stream with our own fingers, and write a correct response back one header at a time. By the end you'll have Pulsely v0: a raw TCP server that answers GET / with {"service":"pulsely","version":0} and keeps the connection alive for the next request. It is code you would never ship. Building it once is the difference between an engineer who uses a server and one who understands one.


1. The problem: why your process won't stay alive (and why it should)​

Here is the first thing that confuses every developer pivoting into backend, and it happens in the first five minutes. You write a Node script:

console.log('Pulsely starting…');

You run it. It prints the line and exits. The shell prompt comes back. That's a script — it runs, it returns, it's done. Now you write what you think is a server, and you're baffled when it also exits, or when it stays alive and you have no idea what's keeping it alive. Both reactions reveal the same missing model: why does a server process stay resident at all?

A normal program is a function the OS calls main() on; when main returns and there's nothing left to do, the process dies. A server stays alive because it has registered ongoing interest in an external event that hasn't happened yet — specifically, it owns an open listening socket, and the runtime knows "there might be a connection on that socket later, so I can't exit." The event loop staying alive is not magic and it is not a setting; it is a consequence of holding an open socket the OS might hand traffic to. Kill the socket and the process falls through to the end of main and dies. This is why a Node server with an active listen() never reaches the end of the file, and why a forgotten server.close() can make a process hang forever in a test suite. Holding the socket is holding the door open.

Now the second confusion, and this one pages people at 2 a.m. You redeploy, the new process starts, and it crashes instantly:

Error: listen EADDRINUSE: address already in use :::3000

EADDRINUSE. You didn't change the port. Nothing is obviously running there. What happened is that the OS — not your app, the kernel — still considers port 3000 owned by the corpse of the previous process (or by a connection in a lingering close state we'll meet shortly). This is your first hard lesson about ports: a port is not an application concept; it is a scarce, kernel-managed resource, and your process can only borrow one, with the kernel's permission, one borrower at a time. You don't "run on port 3000." You ask the kernel to route a slice of the machine's network traffic to you, and the kernel says yes or no.

Two more felt pains, because they foreshadow the rest of the chapter:

  • A load balancer's health check passes, but real users get 502s. The process is listening — the check connects fine — but it isn't accepting connections fast enough, or it's wedged after accepting. Listening and accepting are different verbs, and the gap between them is where availability bugs live.
  • Two services on one box both try to bind :3000. One wins, one gets EADDRINUSE. The collision forces the real question: what does "binding a port" actually mean to the OS, such that exactly one process can do it?

Why build down at this layer at all, when you'll spend your career in Express or NestJS or Spring? Because every one of those is a thin tower built on three primitives: accept a connection, read bytes, write bytes. Frameworks hide the tower so well that when something goes wrong at the floor — a slow client, a malformed request, a leaked connection, a desynced keep-alive stream — the framework has no vocabulary to explain it and neither do you. We're learning the floor so the rest of the book has somewhere solid to stand.

🧭 Mental model. A "server" is not a framework, a file, or a folder. A server is a running process that owns a file descriptor the kernel has marked listening, sitting in a loop that asks the kernel for the next connection. Everything else — routing, middleware, ORMs — is decoration on that one sentence. When you can't find the server in a system, find the process holding the listening socket. That's it. That's the server.


2. The mental model: a host, a queue, and two kinds of socket​

Hold one picture for the whole chapter, and it will carry you through everything that follows. Picture a restaurant.

There is exactly one host at the door. The host's only job is to greet each arriving party and seat them at a table. The host never takes orders, never brings food, never clears plates. The host greets, seats, and immediately returns to the door for the next party. In our server, the host is the listening socket, and the act of greeting-and-seating is the accept() call. Each party that gets seated gets their own dedicated table — and that table is a connection socket, a brand-new, separate socket that carries the actual conversation with that one client.

This is the single most important distinction in the chapter, and it is the one beginners get wrong constantly:

  • The listening socket — there is exactly one of it. It is passive. It never carries a single byte of HTTP. Its only purpose is to be the thing accept() pulls new connections out of. Think: the host's podium.
  • The connection sockets — there are many, one per connected client. Each is active and carries the real bytes — the request in, the response out. Think: the tables.

Conflate these two and nothing makes sense. People say "the server reads from the socket" and don't realize they've smeared two completely different objects into one word. The listening socket births connection sockets; the connection sockets do the work. When we say "the accept loop," we mean: the host standing at the podium, repeatedly seating the next guest.

arriving clients the SERVER process
---------------- -------------------------------

client A ──┐
│ ┌──────────────────┐ accept() → ┌─ conn socket (A) ── bytes ──▶ handler
client B ──┼──▶│ LISTENING SOCKET │ ───────────── ├─ conn socket (B) ── bytes ──▶ handler
│ │ (one, passive) │ accept() → └─ conn socket (C) ── bytes ──▶ handler
client C ──┘ └──────────────────┘
"the host" each accept() hands you
ONE new table to talk on

Now the kernel's role. When packets arrive at the machine's network card destined for port 3000, something has to decide which open socket they belong to — because client A and client B and client C might all be talking to port 3000 at the same instant. That something is the kernel, acting as a switchboard: it inspects each packet and demultiplexes it — in plain terms, sorts each incoming packet onto the right conversation — to the correct connection socket. (If it helps, it's like the way React Query routes a response back to the exact useQuery call that asked for it, matched by query key. The kernel does the same trick, keying each packet to a connection.) Your process never sees this. Your process just says "give me the next caller" (accept) and "give me the next bytes on this table" (read), and the kernel does the routing underneath. We'll see how the kernel tells the conversations apart in §3 — it's the 5-tuple — but hold the shape now: you ask for callers and bytes; the kernel does the sorting.

Two more pieces of the model, then we go deep.

HTTP is not a thing the socket gives you. It's a byte format you agree to. This trips up everyone. The socket hands you a stream of raw bytes — an undifferentiated river. There is no "message," no "request object," no boundary marker the network enforces. HTTP/1.1 is simply a convention both sides agreed to: "we'll write the method and path on the first line, then headers, then a blank line, then a body of a length I'll tell you about." The server's job is to read the river and frame it back into messages using those rules. The network gives you bytes; HTTP is the agreement about what the bytes mean.

🧭 Mental model. A request/response is a conversation over one pipe. Old HTTP hung up the pipe after every exchange — ask, answer, click, dial again. Keep-alive means: don't hang up. Keep the pipe (the connection socket) open and have the next conversation on it. That single optimization — reuse the warm pipe instead of paying TCP+TLS setup again — is why persistent connections are the default in HTTP/1.1, and why framing has to be exact: if you misjudge where one message ends, you've corrupted the start of the next one on the same pipe.


3. Theory & invariants: ports, the 5-tuple, and HTTP framing​

A mental model tells you how to picture the server. Invariants tell you what must hold for it to work at all. There are three clusters here — how connections are identified, how sockets come to life, and how HTTP messages are bounded — and getting any of them wrong produces a specific, recognizable failure.

Ports and the 5-tuple​

A port is a 16-bit number — 0 through 65535 — that lets one machine host many distinct services behind a single IP address. The ranges matter operationally:

  • Well-known / privileged (0–1023): 80 (HTTP), 443 (HTTPS), 22 (SSH). Binding these on Unix requires elevated privilege — a fact that quietly shapes how every container is deployed (we hit this in §5).
  • Registered (1024–49151): where your app lives by convention — 3000, 8080, 5432 (Postgres).
  • Ephemeral (typically 49152–65535): what the client's OS hands out as a temporary source port for each outbound connection.

Here is the invariant that makes servers possible at all, and it's the answer to a great interview question ("how can thousands of clients hit port 3000 at once?"):

🔑 The 5-tuple uniqueness invariant. A TCP connection is uniquely identified not by a port but by the tuple (protocol, source IP, source port, destination IP, destination port). Your server's (dest IP, dest port) is fixed — say 10.0.0.5:3000 — but every client brings a different (source IP, source port), so every connection's full 5-tuple is unique. The kernel demultiplexes incoming packets by this whole tuple, which is why ten thousand clients can talk to the same listening port simultaneously without collision, and why a single client can open many connections to you (it just uses a different ephemeral source port for each). The listening socket is bound to one (IP, port); the connections are distinguished by the full five.

That last point is worth pinning: one listening socket per (IP, port, protocol) — that's the binding invariant, the reason two processes can't both bind :3000. But that single listening socket can spawn an effectively unlimited fan of connection sockets, each its own 5-tuple, each its own table.

listening socket: bound to (TCP, *, *, 10.0.0.5, 3000) ← ONE of these

connection A: (TCP, 203.0.113.7, 51514, 10.0.0.5, 3000) ┐
connection B: (TCP, 203.0.113.7, 51515, 10.0.0.5, 3000) ├─ MANY of these,
connection C: (TCP, 198.51.100.2, 49888, 10.0.0.5, 3000) ┘ all distinct tuples

Notice A and B share a source IP (same client machine) but differ in source port — that's one browser opening two connections. All distinct. All fine.

The socket lifecycle​

Under every server, framework or not, the same four syscalls bring a listening socket to life, in this exact order:

socket() → bind() → listen(backlog) → accept() ─┐
▲ │ returns a NEW
└────────┘ connection socket,
loop back for the next
  • socket() — create a socket object; you get back a file descriptor (just an integer the kernel hands you to refer to this thing). It's not connected to anything yet.
  • bind() — claim an (IP, port). This is where EADDRINUSE is thrown if someone already holds it.
  • listen(backlog) — flip the socket into passive mode: "I am now the host; queue up arriving connections for me." The backlog argument sizes the kernel's queue of completed connections waiting to be accepted (more on this in §4).
  • accept() — pull the next completed connection off that queue. Crucially, accept() returns a brand-new socket — a fresh file descriptor for that one connection. The listening socket stays put; you loop back and accept again.

🔑 Listening ≠ accepting. listen() makes you reachable; accept() is what actually services a waiting client. A process can be listening (so a TCP connect, and therefore a naive health check, succeeds) while being too wedged to accept(), so real requests pile up unanswered in the backlog queue and time out. This is the precise mechanism behind "health check green, users get 502s." The kernel completes the TCP handshake for you and parks the connection in the accept queue; if your loop never gets there, the client connected to nobody.

A connection, once accepted, lives through a lifecycle with vocabulary you'll see in netstat/ss output. It sits in ESTABLISHED while data flows. Then it closes — and here's the part worth slowing down for.

When a connection closes, one side hangs up first. That side is the active closer; the side that merely receives the hang-up is the passive one. After hanging up, TCP doesn't free the socket immediately. It parks it in a holding state called TIME_WAIT for a short while — a deliberate pause, so that any late packets still in flight arrive at a socket that's expecting them, instead of colliding with a brand-new connection that happens to reuse the same numbers. That pause is exactly why a server you just killed can still look like it "owns" the port for a few seconds, producing EADDRINUSE on an instant restart — and why the SO_REUSEADDR socket option (which lets you re-bind a port still sitting in that state) exists. We'll wire it up in §5; for now, file the cause: a closed connection's socket doesn't vanish instantly, and the kernel's caution is what bit your redeploy.

HTTP/1.1 framing — where the body ends​

The socket gives you bytes. HTTP/1.1 is the agreement for carving those bytes into messages. The structure of one message is rigid:

┌───────────────────────────────────────────────┐
│ request-line: GET /encounters HTTP/1.1\r\n │ ← method SP target SP version
├───────────────────────────────────────────────┤
│ header: Host: api.pulsely.health\r\n │
│ header: Content-Type: application/json\r\n│ ← name ":" value, one per line
│ header: Content-Length: 18\r\n │
├───────────────────────────────────────────────┤
│ blank line: \r\n │ ← THE delimiter: head ends here
├───────────────────────────────────────────────┤
│ body: {"reason":"cough"} │ ← exactly Content-Length bytes
└───────────────────────────────────────────────┘

The line-protocol details are unforgiving and worth memorizing:

  • Lines end in CRLF — \r\n, carriage-return then line-feed. Not bare \n. Get this wrong and strict clients hang or reject your response.
  • The headers section ends with an empty line — a \r\n on its own. The byte sequence \r\n\r\n is the boundary between head and body. Finding it is the first job of any parser.
  • Header names are case-insensitive (Content-Length == content-length); the format is Name: value.
  • It's ASCII for the framing; bodies can be anything, including UTF-8 — which sets up a famous bug in a moment.

Now the load-bearing invariant of the whole protocol:

🔑 The body-length invariant. The length of an HTTP body is never implicit and never guessed from the bytes — there is no magic terminator inside the body. The length comes from exactly one of two sources: the Content-Length header (an exact byte count) or Transfer-Encoding: chunked (the body arrives in self-describing size-prefixed chunks). The receiver must know, before reading the body, precisely how many bytes belong to this message — because the very next byte after the body is the start of the next request on a kept-alive connection. Miscount by one byte and every subsequent request on that connection is parsed from the wrong offset: the pipe is desynchronized and silently corrupt.

This invariant has a dangerous corner. What if a request arrives with both a Content-Length and a Transfer-Encoding: chunked, and they disagree? Or two conflicting Content-Length headers? Different servers in a chain might resolve the ambiguity differently — one trusts Content-Length, the next trusts the chunked framing — and now a front proxy and your backend disagree about where one request ends and the next begins. An attacker exploits that disagreement to smuggle a second request past the proxy's view. This is HTTP request smuggling, and the defense starts right here in the framing rule:

🔑 Framing must be unambiguous or rejected. A correct HTTP/1.1 server picks one authoritative length rule and rejects any request whose framing is ambiguous or self-contradictory (both Content-Length and Transfer-Encoding, duplicate conflicting lengths). Ambiguity is not something to "best-effort parse"; it's something to refuse with 400 Bad Request. We name the smuggling threat fully in §8; the seed is: one framing rule, no guessing.

Finally, a sequencing invariant that makes keep-alive tractable:

🔑 One-at-a-time per connection. On a single HTTP/1.1 connection, responses must be returned in the same order as the requests arrived — no interleaving. A client may fire several requests back-to-back without waiting (pipelining), but the server must answer them in order on that socket. This is why strict, correct framing isn't optional for keep-alive: the entire scheme depends on both sides agreeing, byte-for-byte, where each message ends so the next can begin.


4. Under the hood: building Pulsely v0 by hand​

Enough theory. Let's build it, in Node's net module — the raw TCP layer, beneath the http module. We're going to watch every invariant from §3 turn into code.

The accept loop is an event, not a while​

In a low-level language you'd write a literal while (true) { accept(); }. Node hides the loop: net.createServer() gives you a server whose 'connection' event fires once per accepted connection — Node runs accept() for you on the event loop and calls you back with the new connection socket. So the 'connection' callback is your accept-loop body; the socket argument is one freshly-accepted connection (one table).

import net from 'node:net';

const server = net.createServer((socket) => {
// This runs ONCE PER CONNECTION. `socket` is the connection socket — one client.
// The "accept loop" is Node calling this for us, again and again.
handleConnection(socket);
});

server.listen(3000, '0.0.0.0', () => {
console.log('Pulsely v0 listening on 0.0.0.0:3000');
});

server.listen(3000, '0.0.0.0') is our bind() + listen(). The '0.0.0.0' matters enormously in production and we'll come back to it. The callback to createServer is our accept() loop body.

Reading is a river of Buffers, not a request​

Here is the trap that catches everyone. You attach a 'data' handler and assume each 'data' event hands you one whole request. It does not. TCP is a byte stream; the kernel and the network deliver bytes in arbitrary fragments. A single 'data' event might contain:

  • half of a header line, with the rest arriving in the next event;
  • a complete request plus the first 12 bytes of the next one (pipelined);
  • one byte (a slow or malicious client — hold that thought for §8).

So you cannot parse on each chunk. You must accumulate into a buffer and frame yourself: keep appending bytes until you can prove you have a complete message, then parse, then consume exactly that message's bytes and leave the remainder for the next round.

function handleConnection(socket: net.Socket) {
let buffer = Buffer.alloc(0); // bytes received but not yet framed into a request

socket.on('data', (chunk: Buffer) => {
buffer = Buffer.concat([buffer, chunk]); // append to the river so far

// A connection may carry many requests (keep-alive / pipelining),
// so loop: pull off as many COMPLETE requests as the buffer holds.
let req;
while ((req = tryParseRequest(buffer)) !== null) {
buffer = buffer.subarray(req.totalBytes); // consume EXACTLY this request's bytes
respond(socket, req); // answer it (in order — §3 invariant)
}
});

socket.on('error', (err) => {
// A client RST (ECONNRESET) must NOT crash the process — see §6.
console.warn('socket error:', err.message);
});
socket.on('close', () => {
console.log('connection closed');
});
}

Note the two error handlers already attached. Forgetting them is a real outage and we'll dwell on it in §6.

Framing the request by hand​

tryParseRequest is where §3's framing invariant becomes literal code. The algorithm:

  1. Find \r\n\r\n — the head/body boundary. If it's not in the buffer yet, the head is incomplete; return null and wait for more bytes.
  2. Parse the request line (METHOD SP target SP HTTP/1.1) and the headers (split each on the first :, lowercase the name).
  3. Determine body length from Content-Length. If there's a body and we don't yet have that many bytes after the boundary, the message is incomplete; return null.
  4. Only when the entire message is present do we return a parsed request and report totalBytes so the caller can consume exactly that much.
const CRLFCRLF = Buffer.from('\r\n\r\n');

function tryParseRequest(buf: Buffer) {
const headEnd = buf.indexOf(CRLFCRLF);
if (headEnd === -1) return null; // head not fully arrived yet — wait

const headText = buf.subarray(0, headEnd).toString('ascii');
const lines = headText.split('\r\n');
const [method, target, version] = lines[0].split(' ');

const headers: Record<string, string> = {};
for (const line of lines.slice(1)) {
const i = line.indexOf(':');
if (i === -1) continue;
const name = line.slice(0, i).trim().toLowerCase(); // case-insensitive (§3)
headers[name] = line.slice(i + 1).trim();
}

// Body length is NEVER guessed — it comes from Content-Length (§3 invariant).
// (A real server also handles Transfer-Encoding: chunked and REJECTS the
// ambiguous case where both are present — request-smuggling defense, §8.)
if (headers['transfer-encoding'] && headers['content-length']) {
throw new HttpError(400, 'ambiguous framing'); // refuse, don't guess
}

const bodyStart = headEnd + CRLFCRLF.length;
const contentLength = Number(headers['content-length'] ?? 0);

// Do we have the WHOLE body yet? If not, wait for more bytes.
if (buf.length - bodyStart < contentLength) return null;

const body = buf.subarray(bodyStart, bodyStart + contentLength);
const totalBytes = bodyStart + contentLength; // exactly this request's footprint

return { method, target, version, headers, body, totalBytes };
}

Read step 4 twice. The line if (buf.length - bodyStart < contentLength) return null; is the entire reason keep-alive works: we refuse to "respond before the full body arrives," and we consume exactly Content-Length bytes, so the next request in the buffer starts at the right offset.

Writing the response by hand — and the UTF-8 trap​

Now the ruling. We assemble a status line, headers, a blank line, and the body — as bytes:

function respond(socket: net.Socket, req: ParsedRequest) {
const payload = { service: 'pulsely', version: 0 };
const body = Buffer.from(JSON.stringify(payload), 'utf8');

// Honor keep-alive: HTTP/1.1 defaults to persistent; close only if asked.
const wantsClose = req.headers['connection']?.toLowerCase() === 'close';

const head =
`HTTP/1.1 200 OK\r\n` +
`Content-Type: application/json\r\n` +
`Content-Length: ${body.length}\r\n` + // BYTE length, not string length!
`Connection: ${wantsClose ? 'close' : 'keep-alive'}\r\n` +
`\r\n`; // the blank line — head ends here

socket.write(head, 'ascii');
socket.write(body);

if (wantsClose) socket.end(); // active close; otherwise keep the pipe for the next req
}

Look hard at Content-Length: ${body.length}. Because body is a Buffer, body.length is the byte count — which is correct. The lurking bug, which you will hit, is computing the length from a JS string instead:

const s = JSON.stringify({ name: 'José Muñoz' });
s.length; // 21 ← number of UTF-16 code units (WRONG for the wire)
Buffer.byteLength(s, 'utf8'); // 23 ← number of bytes on the wire (RIGHT)

The é and the ñ are each two UTF-8 bytes, not one; a patient name like José Muñoz — the kind of accented name that fills any real Pulsely chart — makes the string length and the byte length diverge. Send the string length as Content-Length and the client reads too few bytes — a truncated, garbled body (a mangled patient name is corrupt PHI) and, on a keep-alive connection, a desynced parser for everything after. Content-Length is a count of bytes on the wire. Always derive it from the encoded Buffer, never from string.length.

What the JVM does differently (and why it teaches)​

Skippable aside — the transferable payoff is the last two sentences; skim the Java if it's not your world.

The same syscalls underlie every runtime; what differs is the concurrency strategy sitting on top of accept(). In classic Java, you'd write the accept loop literally, and accept() blocks the thread until a connection arrives:

ServerSocket server = new ServerSocket(3000);
while (true) {
Socket conn = server.accept(); // BLOCKS this thread until a client connects
new Thread(() -> handle(conn)).start(); // one OS thread per connection — the classic model
}

That's the thread-per-connection model: each connection gets a dedicated OS thread that blocks at each read/write. Spring (on Tomcat) refines it to a thread pool — a fixed set of worker threads checked out per request — but the shape is the same: a thread is parked, blocking, for the life of a connection's I/O. Node took the opposite bet: one thread, never blocking, the event loop driving accept and read/write as readiness events. Same accept() syscall at the bottom of both; radically different answer to "how do I serve ten thousand of these at once?" I'm flagging this contrast, not resolving it — which model wins under which workload is a genuinely deep question, and it owns the next two chapters.

📎 Borrowed on credit: the concurrency model. Why one Node thread can hold thousands of these connections without a thread each — epoll readiness notification, non-blocking sockets, the libuv pool — and why a thread-per-connection server hits a memory wall, is the spine of Chapter 3 (processes, threads, memory) and Chapter 4 (I/O & concurrency models). Here, just hold the fact: the accept loop is universal; the strategy for servicing accepted connections is a choice made above it.

The accept queue and backlog​

One more under-the-hood piece. Between "a client's TCP handshake completed" and "your code called accept()," the connection waits in a kernel queue. The size of that queue is the backlog — the second argument to listen(), capped by the OS limit SOMAXCONN. When connections arrive faster than your loop accepts them, they queue up to backlog. Once that queue is full, here's what happens, step by step:

  • The kernel doesn't send back a polite "go away." There is no error packet at all.
  • Instead it simply drops the client's final handshake packet — the ACK, the last of the three messages that finish opening a TCP connection.
  • The client's OS assumes that packet got lost somewhere in the network, waits, and resends it — over and over.
  • From the client's side, nothing errors. The connection just seems to take forever.

That's why an overloaded server appears to "hang" rather than returning a clean error. This is the same queue that fills when your process is "listening but not accepting." It's also a knob with a non-obvious tradeoff (§7): a bigger backlog hides capacity problems and inflates tail latency; a smaller one sheds excess load early and fast.


5. In production: what you actually run, and how to not get paged​

Let me be blunt about Pulsely v0: you would never run this in production. We built it to understand the floor, not to ship it. Hand-rolled HTTP parsers are a reliable source of security bugs (every framing edge case is yours to get right), and you'd be reinventing decades of hardening. In production you run a battle-tested server — Node's http module, or Express/Fastify on top of it — and you put a reverse proxy (nginx, Envoy, an ALB) in front. But the hygiene below the framework is yours to get right, framework or not, so here's the production-grade socket discipline you should internalize now.

Bind the right address, or "works locally, 502 in prod." server.listen(3000) and server.listen(3000, '127.0.0.1') are dangerously different. 127.0.0.1 (loopback) means only this machine can reach the socket — perfect on your laptop, catastrophic in a container, where the orchestrator and load balancer reach you over the pod network and get nothing but refused connections. 0.0.0.0 means "all network interfaces" — reachable from outside the box. In containers, bind 0.0.0.0 (and control real exposure with network policy and the proxy), or your service will pass every local test and serve nothing but 502s the moment it's deployed.

Never run as root to grab port 80. Ports below 1024 are privileged. The wrong fix is running your process as root so it can bind(:80) — now a code-execution bug in your handler is a root shell. The right pattern: bind an unprivileged high port (:3000, :8080) as a non-root user, and let the reverse proxy or orchestrator map public :80/:443 down to it. Least privilege at the process boundary; the app never needs root.

SO_REUSEADDR and graceful shutdown to kill EADDRINUSE on redeploy. Remember the TIME_WAIT lingering from §3? Enabling address reuse lets a restarting process re-bind a port still in that transient state instead of crashing. But the deeper fix is to shut down cleanly: on SIGTERM (what every orchestrator sends to ask you to stop), stop accepting new connections, let in-flight requests finish, then exit — so connections close in an orderly way and the port frees promptly. The mechanics of draining correctly are involved enough to own their own chapter:

📎 Borrowed on credit: graceful shutdown. Trapping SIGTERM, flipping the readiness probe so the load balancer stops routing to you, draining in-flight requests, and exiting within the orchestrator's grace period is the full discipline — and it's owned by Chapter 8 (the request lifecycle & graceful shutdown). Here, just know the shape: stop accepting, drain, exit — and that skipping it means every deploy drops the requests that were mid-flight.

Set timeouts explicitly — the defaults are "wait forever." A connection that opens and then dribbles its request one byte at a time, or one that never sends the final \r\n\r\n, will — with default settings — occupy a connection slot indefinitely. You must set explicit header-read, idle, and request timeouts so a connection that isn't making progress is forcibly closed. We will meet the attack that abuses missing timeouts in §8 and §6, and the defense in full later:

📎 Borrowed on credit: timeout & proxy-buffering defenses. This chapter introduces the slow-client hazard (slowloris, slow-read, connection exhaustion) as a thing that exists. The actual defenses — tuned read/idle/request timeouts at the server, and a buffering reverse proxy that absorbs slow clients before they ever reach your app — are owned by Chapter 4. I name the hazard here; Chapter 4 hands you the shield.

Watch your file descriptors. Every open connection is a file descriptor, and the OS caps how many you can hold (ulimit -n). A connection leak — sockets you accept but never close — climbs toward that cap until accept() itself fails with EMFILE: too many open files, and then your server stops accepting everything. The operational floor: log accept/close, and expose currently-open-connection count and open-fd count as metrics, because request rate alone won't show you a slow leak marching toward a cliff. (The OS-resource view of this — fds, RSS, the EMFILE page at 2 a.m. — is exactly what Chapter 3 instruments.)

ADR-002 — Terminate TLS at a reverse proxy, not in the app process​

This is a real decision you'll make on essentially every backend, so let's make it deliberately. (We are previewing the decision and its rationale; we are not implementing TLS in this chapter — Pulsely v0 speaks plaintext.)

ADR-002 — Terminate TLS at the reverse proxy. Context. Pulsely must serve https://. TLS termination can happen in the app process (the Node server holds the certs and does the handshake) or at a reverse proxy (nginx/Envoy/ALB terminates TLS and forwards plaintext HTTP to the app over the internal network). Decision. Terminate TLS at a reverse proxy. The app process speaks plaintext HTTP/1.1 on an unprivileged port; the proxy owns certificates and the handshake. Rationale. (1) Certificate management — issuance, rotation, and renewal (e.g. ACME/Let's Encrypt) live in one place, not baked into every app instance. (2) CPU offload — the handshake's asymmetric crypto is handled by the proxy, often hardware-accelerated, keeping the app's cores for application work. (3) Simpler app — no cert files, no TLS config, no private keys in the app's blast radius. (4) Centralized policy — cipher suites, TLS versions, HSTS, and security headers are enforced uniformly at the edge. (5) It composes with everything else the proxy already does — buffering slow clients (the §8 defense), health checks, and load balancing. Tradeoff / cost. Traffic between the proxy and the app travels as plaintext inside the trust boundary (the private network/cluster). You're accepting that the internal hop is unencrypted — and since Pulsely carries PHI, that acceptance is a HIPAA judgment call, not a throwaway one. When you'd reverse it. A zero-trust environment where even in-cluster traffic must be authenticated and encrypted (regulated data such as PHI, multi-tenant clusters, "assume the network is hostile") — there you'd terminate or re-encrypt with mutual TLS between proxy and app. For Pulsely's stage, edge termination is the right call.

🏭 The practical upshot: nearly every production backend you'll ever touch speaks plaintext HTTP internally and lets the edge handle TLS. When you see your app log http:// and panic, this ADR is why it's fine — the https:// was terminated one hop earlier, at the proxy, exactly as designed.


6. Common pitfalls​

Each is signature → fix — the symptom you'll observe, then the principle that resolves it. Every one of these is a bug I have personally watched ship.

EADDRINUSE on restart. Signature: a redeploy crashes immediately with "address already in use," though nothing is obviously running on the port. Fix: the prior socket is still bound or lingering in TIME_WAIT. Enable SO_REUSEADDR, and — the real cure — shut down cleanly on SIGTERM so the port frees promptly. Don't paper over it by changing the port.

Assuming one 'data' event equals one request. Signature: parses that work in dev (small fast requests) and corrupt intermittently under load or with large/pipelined requests; bodies truncate; headers come back malformed. Fix: accumulate bytes into a buffer and frame yourself on \r\n\r\n + Content-Length. A 'data' event is an arbitrary slice of a byte stream, never a message boundary.

Content-Length = string length, not byte length. Signature: responses (or request bodies) with non-ASCII — an accented character in a patient name or clinical note (José, Muñoz, Zoë, a ° in a vital) — come out truncated or garbled, and keep-alive connections desync afterward. Fix: Content-Length is a count of bytes on the wire. Compute it from the encoded Buffer (Buffer.byteLength(s, 'utf8') or buffer.length), never from string.length.

Using \n instead of \r\n, or forgetting the blank line. Signature: the client hangs waiting for a response, or rejects it as malformed; some clients are lenient and some aren't, so it "works in curl but breaks in the browser." Fix: HTTP/1.1 lines end in \r\n, and the head ends with a bare \r\n (the empty line) before the body. Be strict on output even where you're lenient on input.

Not handling keep-alive framing. Signature: the second request on a connection is mis-parsed; responses appear to "shift" — request 2 gets request 1's answer; everything after the first request on a kept-alive socket is wrong. Fix: consume exactly Content-Length bytes per request and reset parser state before the next. The next request begins at the byte immediately after this body — off by one and the pipe is corrupt.

Binding 127.0.0.1 in a container. Signature: flawless locally; in production the load balancer's health checks and all real traffic get refused — 502s everywhere. Fix: bind 0.0.0.0 so the socket is reachable on the pod/container network; control real exposure with network policy and the reverse proxy, not by hiding on loopback.

No per-socket 'error'/'close' handler. Signature: a client that resets the connection (ECONNRESET) throws an unhandled error event that crashes the entire process — one rude client takes down a server serving thousands. Fix: attach 'error' and 'close' handlers to every connection socket. Network peers vanish, reset, and misbehave constantly; that's normal, not exceptional, and must never be fatal.

Responding before the full body has arrived. Signature: POST/PUT handlers race or hang; bodies are partially read; behavior depends on packet timing and is impossible to reproduce locally. Fix: per the framing invariant, wait until you have the complete message (head and all Content-Length body bytes) before you respond. Completeness is a precondition, not a hope.


7. Tradeoffs​

Senior engineering is naming the spectrum and saying why you stand where you stand. This chapter has several.

Raw TCP / hand-rolled HTTP ↔ the http module ↔ a full framework. Raw gives you total control and genuine understanding; a framework gives you correctness and velocity. The cost of "raw" is that every framing edge case, security hardening, and protocol subtlety is now yours to get right — and you will get some wrong. You reach for raw or near-raw only for ultra-custom wire protocols or a measured, perf-critical hot path. For Pulsely, raw is purely pedagogical: we built v0 to see the floor, and later chapters climb back up to a real server and a framework. Understanding the floor doesn't mean living on it.

Persistent (keep-alive) ↔ connection-per-request. Keep-alive saves the TCP+TLS handshake on every request after the first — big latency and CPU wins. The cost: you hold a file descriptor and kernel socket buffers open for idle clients between requests. You lean keep-alive almost always; you'd reconsider when you have enormous fan-out of mostly-idle clients where the held FDs cost more than the saved handshakes — at which point idle timeouts that reclaim quiet connections become the balancing lever.

The accept() concurrency model: single loop ↔ thread-per-connection ↔ thread pool. Event loop (Node) buys connection density at low memory but is vulnerable to any one handler blocking the loop; thread-per-connection (classic Java) buys simple blocking code and easy CPU parallelism but pays ~1 MB of stack per connection and hits a memory wall; a thread pool (Spring/Tomcat) bounds the threads but then bounds your concurrency to the pool size. The decision is real, and it's decided by workload — named here, owned by Chapters 3–4.

TLS in-process ↔ TLS at the proxy (ADR-002). At-proxy buys operational simplicity, CPU offload, and centralized cert/policy management at the cost of a plaintext hop inside the trust boundary. In-process buys end-to-end encryption at the cost of cert management on every instance. You reverse toward in-process (or mTLS) only under a zero-trust mandate — and PHI on the wire is exactly the kind of pressure that tips it. For most systems, terminate at the edge.

backlog size. A large backlog absorbs bursts but hides capacity problems and inflates tail latency (connections wait a long time before being accepted instead of being refused fast). A small backlog sheds excess load early — clients get a fast "no" and can retry elsewhere — but drops connections sooner under spikes. Neither "bigger" nor "smaller" is universally right; it's a load-shedding policy choice.

Bind to all interfaces ↔ a specific interface. 0.0.0.0 is convenient and necessary in containers; binding a specific internal interface shrinks the attack surface. Convenience versus exposure — decide deliberately, don't default thoughtlessly to "all" on a machine where the service should be internal-only.

🚫 A framing this book rejects. "Frameworks handle the network, so I never need to understand sockets." Wrong, and expensively so. The framework handles the happy path. The moment something goes wrong at the floor — a desynced keep-alive stream, a slowloris stall, an EMFILE cliff, a Content-Length mismatch from an upstream — the framework has no words for it, and an engineer who's never seen the floor has no words either. You don't need to write socket code in production. You absolutely need to be able to reason about it when it breaks.


8. Security & scale notes​

The instant you speak the wire yourself, you inherit a threat surface. Even behind a framework, these are properties of the layer, and you should recognize them.

Malformed and ambiguous requests are attacks, not accidents. A hostile client sends garbage request lines, oversized header blocks meant to exhaust your buffers, and header values laced with unsanitized \r\n to inject extra headers (header/response splitting). The defense is to be strict: cap header size, validate the request line, and reject — not "best-effort parse" — anything malformed.

HTTP request smuggling — why "one framing rule" is a security rule. Recall §3's body-length invariant. When a request carries both Content-Length and Transfer-Encoding: chunked, or duplicate conflicting lengths, two servers in a chain (your reverse proxy and your app) may resolve the ambiguity differently and disagree about where one request ends and the next begins. In plain terms: the proxy reads the bytes and thinks "that's one request," forwards them — but your app reads the same bytes and thinks "that's one and a half requests." The extra half, which the proxy never inspected, becomes a second request that your app runs as if it were trusted. In Pulsely that trusted-but-smuggled request could ride in on another user's connection and pull back a chart that isn't theirs — a wrong-patient disclosure, which is a reportable PHI breach, not just a bug. The defense lives in the framing rule itself: pick one authoritative length source and reject ambiguity with 400. This is precisely why §3 told you never to guess — guessing is the vulnerability.

Slowloris and slow-read — availability is a resource you defend. This is the hazard this chapter introduces. An attacker opens many connections and trickles bytes — one byte every few seconds, never completing the request — or reads your response one byte at a time. With no header/idle/request timeout, each such connection occupies a slot indefinitely, and a handful of clients can exhaust your entire accept capacity while sending almost no data. CPU is near zero; memory is fine; the server simply stops being able to serve anyone — and an EHR that can't answer during a clinic day is its own kind of harm. This is your first encounter with a profound idea: availability is a finite resource, and it can be attacked directly without ever breaching correctness. (The defenses — server-side timeouts and a buffering reverse proxy — are owned by Chapter 4, per the 📎 in §5.)

Connection / file-descriptor exhaustion. Every open socket is a file descriptor, and the OS caps them. A connection leak (or a slowloris flood, or just a legitimate traffic spike with no max-connection cap) climbs toward ulimit -n; cross it and accept() fails with EMFILE and the server stops accepting all traffic — a total outage triggered by one leaky endpoint or one attacker. Bound max concurrent connections and alert on FD count approaching the limit before it becomes a 2 a.m. page.

Unbounded body reads are a trivial OOM DoS. Our v0 parser trusts Content-Length and buffers the whole body in memory. A malicious Content-Length: 5000000000 (or a flood of large bodies) drives RSS up until the OS OOM-kills the process — a denial of service from one crafted request. The defense is a maximum body size cap: reject requests claiming more than your limit before buffering them.

Now scale, where the accept loop itself teaches the lesson:

🔑 One accept loop, one core. A single Node process's accept loop is fast, but it's one thread doing the accepting — it can saturate one CPU core, and a CPU-bound handler that blocks the loop stalls every connection at once. Real scale therefore isn't "make one process faster"; it's many processes/instances behind the reverse proxy, each with its own accept loop, traffic spread across them. The single process is the unit you understand; the fleet of identical processes is the unit you scale — which is exactly the statelessness idea you saw earlier paying off: because any instance can answer any request, you can run N of them.

The full mechanics — multiple processes per box, how the OS shares the accept load, why the fleet is the scaling unit — belong to Chapters 3 and 29. Here, hold the shape: the accept loop is your unit of understanding, not your unit of scale.


9. Interview lens & exercises​

Interview questions​

Backend interviews at this layer separate people who recite "the framework handles it" from people who can narrate the floor.

"Step by step, what happens when a request hits a server listening on port 3000?"

  • Junior answer: "the framework receives it and calls my route handler." True, and it reveals you've never looked under the framework.
  • Senior answer: names the listening socket vs. connection socket distinction, the kernel completing the handshake into the accept queue (sized by backlog), accept() returning a new per-connection socket, the byte stream being framed into an HTTP message via the request line / headers / \r\n\r\n / Content-Length, and the response written back as raw bytes. Narrates the floor, not the decoration.

"How can thousands of clients connect to the same server port at once?"

  • Junior: "the server opens many ports" — the giveaway that the 5-tuple is missing.
  • Senior: "one listening socket bound to (IP, port), but each connection is identified by the full 5-tuple (protocol, src IP, src port, dst IP, dst port). Every client brings a distinct source IP/port, so every connection is unique and the kernel demultiplexes by the whole tuple. A single client can even open many connections using different ephemeral source ports."

"How does the server know where the HTTP body ends?"

  • Junior: "it reads until the connection closes."
  • Senior: "from Content-Length or Transfer-Encoding: chunked — never guessed. The body length must be known before reading it, because the next byte is the next request on a kept-alive connection. If both length signals are present and conflict, that's ambiguous framing — a request-smuggling vector — so a correct server rejects it rather than guessing."

"Where would you terminate TLS, and why?"

  • Junior: "in the app, with HTTPS enabled."
  • Senior: "at the reverse proxy — centralized cert management and rotation, CPU offload of the handshake, a simpler app with no private keys in its blast radius, and uniform policy at the edge. The tradeoff is a plaintext hop inside the trust boundary, which I'd reverse with mTLS in a zero-trust environment — and with PHI on the wire, that's a live consideration." (That's ADR-002, reasoned, not memorized.)

"Your service restarts and won't bind — EADDRINUSE. What's going on?"

  • Junior: "change the port."
  • Senior: "the previous socket is still bound or lingering in TIME_WAIT, so the kernel won't let me re-bind. The real fix is graceful shutdown on SIGTERM so the port frees cleanly; SO_REUSEADDR lets me re-bind through the transient close state. I'd also check it's truly stale socket state and not a second process actually holding the port."

Exercises & the Pulsely increment​

Build these in order; each is a rung. The goal is fluency at the floor.

  1. Raw TCP echo server. Using net.createServer, accept connections and echo received bytes straight back. Attach 'data', 'end', 'error', and 'close' handlers, and log every accept and close. This is the floor beneath HTTP — prove to yourself that "a server" is just accept-read-write before you add any protocol.

  2. Hand-parse one HTTP/1.1 request. Read from the socket, accumulate into a buffer, split head from body on \r\n\r\n, parse the request line and headers (case-insensitive names), and read exactly Content-Length bytes of body. Print the parsed structure. Feed it a request split across multiple 'data' events (use nc and type slowly) to prove your buffering is correct.

  3. Pulsely v0. Extend the parser into a server that answers with hand-written JSON — correct status line, Content-Type: application/json, byte-accurate Content-Length, and Connection: keep-alive so a second request on the same socket is served correctly. Verify with curl -v http://localhost:3000/ (inspect the response framing), then send two pipelined requests on one connection and confirm both get correct, in-order answers.

  4. Break it on purpose, then reason about it. Send (a) a request with a Content-Length larger than the body, (b) a slowloris-style trickle via nc/telnet that never completes the head, and (c) a body containing an accented patient name (e.g. José Muñoz) while computing Content-Length from string.length. Observe each failure — the hang, the desync, the truncation — and write down the mechanism for each from the framing invariants. Then add a maximum body-size cap and a header-read timeout, and re-test. Finally, write ADR-002 in your own words: why you'd terminate TLS at the proxy, and the one condition under which you'd reverse the decision.


Key takeaways​

  • A server is a process that owns one listening socket the kernel has marked passive, sitting in an accept loop that pulls new connection sockets off the kernel's accept queue. The listening socket is one and passive; connection sockets are many and carry the bytes — conflating them is the #1 beginner error.
  • A port is a scarce, kernel-managed resource; bind() claims one (EADDRINUSE if taken). Connections are identified by the 5-tuple, which is why thousands of clients share one listening port without collision.
  • The socket comes alive through socket() → bind() → listen(backlog) → accept(). Listening ≠ accepting — a process can be reachable yet too wedged to service requests, which is why a health check can pass while users get 502s.
  • HTTP is a byte format, not something the socket gives you. You receive a river of bytes and must frame it yourself: request line, headers, \r\n\r\n, then a body whose length comes from Content-Length or chunked encoding — never guessed. Ambiguous framing is rejected, not best-effort parsed (the smuggling defense).
  • Content-Length is a count of bytes on the wire — derive it from the encoded Buffer, never string.length, or non-ASCII bodies (an accented patient name is corrupt PHI) truncate and keep-alive desyncs.
  • Keep-alive reuses one warm pipe for many conversations; it works only because framing is byte-exact and responses come back in request order.
  • In production you don't run raw HTTP — you run a hardened server behind a reverse proxy that terminates TLS (ADR-002). But the socket hygiene is yours: bind 0.0.0.0 in containers, never run as root for :80, set explicit timeouts, watch your FD count, and shut down gracefully.
  • The accept loop is your unit of understanding, not your unit of scale — one loop saturates one core, so real scale is many identical processes behind the proxy. The slow-client/exhaustion hazards introduced here are real; their defenses arrive in Chapter 4.

← Previous: Ch 1 — What a Backend Is · Up: Part I overview · Master TOC · Next: Ch 3 — OS & Runtime Fundamentals →