Chapter 5 — Networking I: IP, TCP/UDP, Sockets, DNS
Part I · Foundations | Prerequisites: Ch 2–Ch 4 | Builds: the wire-level model under every request hop
Earlier you built a process that owns a listening socket and reads bytes off it, and you saw why a single thread can wait on tens of thousands of those sockets at once. Both of those treated the network itself as a given — bytes go in, bytes come out, the wire just works. This chapter pries open that wire. By the end you'll be able to read a packet capture and say, line by line, what each layer is doing; explain why "a connection" is a fiction maintained by two state machines that have never physically touched; attribute a slow request to DNS, to the handshake, or to your own code; and recognize the network-stack failure modes — resets, port exhaustion, half-open connections, dropped SYNs — that masquerade as application bugs. Every later abstraction (your HTTP client, your database driver, gRPC, the load balancer in Chapter 6) is a thin shell over a socket over TCP over IP. When the shell leaks, it leaks here, and you need the vocabulary to see it.
This chapter sits squarely on the TCP box of the book's spine — and it reaches a little to the left, into DNS, and a little below, into IP. We stop exactly where TLS begins; that's Chapter 6's territory.
1. The problem: the network is not a wire
It's a Tuesday and Pulsely's eligibility checks start timing out. Not failing fast — timing out, at the full 30-second client deadline, for a fraction of requests that grows as traffic does. The on-call engineer pulls up dashboards. CPU is idle. Memory is flat. The database is bored. The application logs show two errors neither of them has a mental model for: ECONNRESET ("connection reset by peer") and, more alarmingly, EADDRNOTAVAIL ("cannot assign requested address") on the eligibility service's outbound calls to the insurance clearinghouse. Everything that measures the application says the application is fine. And yet patients are stacking up at the front desk, their coverage unverifiable.
The team's instinct is to scale up the app tier. It doesn't help, because the bottleneck was never the app — it's the network stack, the layer of machinery between your socket.write() and the bytes actually arriving somewhere. They have no vocabulary to name what's wrong, so they can't fix it. EADDRNOTAVAIL under load has a precise meaning we'll arrive at by §4: the eligibility service is opening and closing a fresh TCP connection to the clearinghouse on every request, and it has run out of ephemeral source ports because tens of thousands of recently-closed connections are still occupying them. No amount of CPU fixes that. The fix lives in understanding what a port is, what a connection is, and what happens to a connection after you think you've closed it.
Now a second pain, quieter and more common. A deploy "works on my machine," ships, and users in another region report 800ms time-to-first-byte on the very first request — every time the app has been idle for a few minutes. Is it DNS? The TCP handshake? TLS setup? The app itself? Nobody on the team can say, because nobody can decompose the latency. They argue for two days. The argument is unwinnable without a model that says: a request's latency is a sum of named buckets, and each bucket has a tool that measures it.
Both incidents are the same lesson wearing different clothes. The network is not a wire; it's a stack of protocols, each maintaining an illusion on top of a weaker guarantee below it, and the illusions break in specific, nameable ways. Why is it a stack at all? Because no single protocol can simultaneously address billions of hosts, route packets across wildly heterogeneous physical links (fiber, Wi-Fi, cellular, satellite), recover data the physics dropped, and model your application's semantics. That's too many jobs for one design. So the problem is decomposed: each layer solves exactly one thing and trusts the layer beneath it to have solved its own. IP addresses and routes. TCP recovers and orders. Your app gives the bytes meaning. The leaks you debug — timeouts, resets, half-open connections, port exhaustion — are precisely the seams between these layers showing through.
🧭 A useful distinction. "Reliability" and "a connection" are not physical objects you can point at. There is no copper wire that is "open" between Pulsely and a clinician's laptop. Reliability is an illusion TCP maintains — by numbering bytes, acknowledging them, and resending the lost ones — on top of an IP layer that will happily drop, duplicate, reorder, or corrupt your packets and feel no remorse. A connection is a pair of agreements, one held in your kernel and one held in theirs, about what byte comes next. Understanding exactly where these illusions are manufactured, and where they tear, is the entire game of this chapter.
2. The mental model: envelopes, the 5-tuple, and a name that must become an address
Hold three pictures. They'll carry you through everything mechanical that follows.
Nested envelopes
When Pulsely's server sends a chunk of chart-timeline JSON, that payload doesn't travel naked. Each layer of the stack wraps it in an envelope addressed to its own concern, then hands the whole bundle down:
┌──────────────────────────────────────────────────────────────┐
│ LINK frame [ dst MAC | src MAC | ... │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ IP packet [ src IP | dst IP | proto | TTL | ... │ │
│ │ ┌──────────────────────────────────────────────┐ │ │
│ │ │ TCP segment [ src port | dst port | seq | ack │ │ │
│ │ │ ┌──────────────────────────────────────┐ │ │ │
│ │ │ │ APPLICATION PAYLOAD (your bytes) │ │ │ │
│ │ │ └──────────────────────────────────────┘ │ │ │
│ │ └──────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
Each layer reads only its own envelope and hands the inside up (on receive) or wraps it and pushes down (on send). The link layer cares about the next physical hop and nothing else. IP reads source and destination addresses and decides where to forward. TCP reads ports and sequence numbers and reassembles a stream. Your handler reads only the payload. This is encapsulation as a literal byte layout, and it's why a router can move your packet without understanding HTTP, and your handler can parse HTTP without knowing which Wi-Fi channel carried it.
Two orthogonal jobs: "where" and "did it arrive?"
Collapse the stack to its two load-bearing layers and you get a clean division of labor:
- IP answers "where." Addressing plus a best-effort delivery attempt, hop by hop, across whatever links exist between here and there. IP makes no promises about arrival, order, or integrity. It tries.
- TCP answers "did it arrive, in order, intact?" Reliability and ordering, end to end, built entirely on top of IP's unreliable attempts. TCP is the layer that turns "tried to deliver" into "delivered exactly once, in order, or you'll be told it failed."
UDP keeps IP's "where" and adds almost nothing else — just port numbers (so packets find the right socket) and an optional checksum. UDP is "IP with ports." That's the whole pitch, and as we'll see in §7, sometimes that minimalism is exactly what you want.
The 5-tuple is the identity of a flow
You've already met this as the kernel's demultiplexing key. Promote it now to the spine of the whole chapter:
( protocol , src IP , src port , dst IP , dst port )
This single tuple is a connection's identity. It is what the kernel hashes to deliver an arriving packet to the right socket. It is what a load balancer hashes to keep a flow pinned to one backend. It is what NAT rewrites to share one public address among many private hosts. Whenever you're confused later — "why can two clients hit the same server port?", "why did this connection break when its source port got reused?" — return to the 5-tuple. Two flows are the same flow if and only if all five fields match.
A connection is a shared state machine, not a pipe
There is no open pipe. "Connected" means both endpoints independently hold a small state machine that currently reads ESTABLISHED, and both agree on which sequence number comes next. The connection lives in two kernels, as data, mirrored. When one side crashes without warning, the other side's state machine still says ESTABLISHED — it has no idea its partner is gone, which is exactly why "half-open" connections (§6) are a thing and why keepalives exist.
And before any of this: a name must become an address
The user types api.pulsely.health. IP can only route to numbers. So the very first thing — before a single SYN is sent — is a separate, prior phase: DNS turns a name into an address. This is not a function call into a local table; it's a distributed lookup, potentially several network round trips, served through a hierarchy of caches. It has its own latency and its own failure modes, and it happens before your "request" has even begun.
🧭 Mental model. A request's wall-clock time is a sum of named buckets, and your whole diagnostic skill is attributing a slow request to one bucket:
total ≈ DNS_resolve + TCP_handshake(1 RTT) + [TLS_setup] + app_processing + transferThe
[TLS_setup]bucket is bracketed because it's Chapter 6's. The rest are this chapter's. When a chart load is slow, the senior move is not "scale the app" — it's "which bucket?"digmeasures the first. A packet capture measures the second. Your traces measure the fourth. You spend latency in buckets; you debug by finding the heavy one.
3. Theory & invariants
A model tells you how to picture the network. Invariants tell you what each layer guarantees and — just as importantly — what it refuses to guarantee, so you know whose job it is to make up the difference.
The layered model: 4 that ships, 7 you'll hear in interviews
The Internet runs on a 4-layer model: link (Ethernet, Wi-Fi — the next physical hop), internet (IP — addressing and routing), transport (TCP/UDP — end-to-end delivery semantics), application (HTTP, DNS, your protocol). You'll also hear the 7-layer OSI model (physical, data-link, network, transport, session, presentation, application) in interviews and textbooks. OSI is a useful taxonomy and a terrible description of what actually ships — the session and presentation layers never materialized as distinct things on the real Internet. Know the OSI names so you can map them ("TCP is 'layer 4', HTTP is 'layer 7'" — that's where "L4 load balancer" vs "L7 load balancer" comes from, which matters next chapter), but reason in the 4-layer model, because that's the one running under your fingers.
🔑 IP is best-effort and nothing more. IP's contract is: connectionless (no setup, each packet routed independently), unordered (packets may arrive in any order), may drop (congested router discards it, no apology), may duplicate (a retransmission's twin arrives late), may corrupt (a bit flips), may fragment (a packet too big for a link gets chopped). IP guarantees one thing only: it will make a routing attempt toward the destination address. Every higher guarantee — reliability, order, integrity, the very notion of a "connection" — is constructed on top of this by TCP. Internalize this and TCP stops being magic and becomes obviously necessary.
IPv4 addressing and CIDR
An IPv4 address is 32 bits, written as a dotted quad: 10.20.5.130. An address splits into a network portion (which subnet) and a host portion (which machine on it). CIDR notation makes the split explicit: 10.20.4.0/22 means "the first 22 bits are the network; the remaining 10 bits identify hosts." In plain terms, a CIDR prefix works like the area code on a phone number: a fixed front chunk of the address labels the neighbourhood (the subnet), and the leftover digits pick the individual house (the host). So /22 says the first 22 of the 32 bits are the area code, leaving 10 bits to name houses. That /22 gives you 2³² ⁻ ²² = 2¹⁰ = 1024 addresses — how many houses 10 leftover bits can name — of which the first (10.20.4.0, the network address) and the last (10.20.7.255, the broadcast address) are reserved, leaving 1022 usable hosts. The range spans 10.20.4.0 through 10.20.7.255. Two addresses are on the same subnet — and can therefore talk directly over the link without routing — if and only if their network bits match (their area codes are identical). This subnet math is not academic: it's how you read a security-group rule, how you know whether two services route or bridge, and a guaranteed interview whiteboard question.
IPv6 widens the address to 128 bits, written in hex groups (2001:db8::1). The address space is so vast that the IPv4 conservation tricks below become unnecessary — IPv6's design ethos is end-to-end addressability with no NAT by default, every host globally reachable. The transition has taken decades; you'll run dual-stack for the foreseeable future.
Private ranges and why NAT must exist
Certain IPv4 ranges are reserved as private (RFC 1918) and are not routable on the public Internet: 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. Plus 127.0.0.0/8 for loopback (127.0.0.1 is "this machine") and 169.254.0.0/16 for link-local. Your laptop, your containers, your VPC instances almost all wear private addresses. But a private address can't appear as a source on the public Internet — no router out there knows how to route a reply back to 10.20.5.130, because millions of machines share that exact address. So something must translate.
NAT (Network Address Translation) is a 5-tuple rewriting machine. A NAT gateway lets many private hosts share one public IP by rewriting the source IP and source port of outbound packets to its own public IP plus a chosen port, and recording the mapping in a translation table. When the reply comes back to (public IP, chosen port), NAT looks up the table and rewrites the destination back to the original private host. Two consequences fall out and they bite people constantly. First: inbound connections don't work without explicit port-forwarding, because there's no table entry until the inside initiates — NAT is accidentally a firewall. Second: NAT table entries have idle timeouts. Leave a connection silent for longer than the gateway's timeout and it evicts the mapping; the next packet has nowhere to go and the connection breaks. This is the root cause of "my idle connection mysteriously died" — flag it now, fix it in §6.
🔑 The connection-identity invariant. A flow is uniquely identified by its 5-tuple, and the kernel, the load balancer, and NAT all key off it. This is why thousands of clients hit your one server port simultaneously without collision (each has a distinct source IP+port, so distinct 5-tuples), and why a single client can open many connections to you (the kernel hands each a different ephemeral source port). It's also why, when ephemeral ports run out, the machine literally cannot form a new distinct 5-tuple to a given destination — the
EADDRNOTAVAILfrom §1.
TCP's guarantees and the vocabulary that produces them
🔑 The TCP invariant: a reliable, ordered byte stream. TCP promises four things, each built from a specific mechanism:
- Reliable — every byte is acknowledged; unacknowledged bytes are retransmitted. Loss is invisible to your app.
- Ordered — every byte carries a sequence number; the receiver reassembles them in order regardless of arrival order.
- A byte stream, not a message stream — and this is the single biggest surprise for app developers. TCP has no message boundaries. It is a faucet of bytes. What you
write()as one logical message may arrive split across severalread()s, or glued together with the next message. TCP will never tell you where your message ends — that's your job (§6).- Flow-controlled — the receiver advertises how much buffer space it has (the receive window), and the sender never overruns it.
- Congestion-controlled — the sender infers network congestion from packet loss and voluntarily slows down to avoid collapsing the shared network.
The vocabulary you must own, because every tool and trace uses it: SYN (synchronize — open a connection), ACK (acknowledge — "I got bytes up to here"), FIN (finish — "I'm done sending"), RST (reset — "tear this down now, something's wrong"); sequence number and acknowledgment number (the byte counters in each direction); MSS (maximum segment size — the largest payload per segment); rwnd (receive window — flow control) and cwnd (congestion window — congestion control); RTT (round-trip time) and RTO (retransmission timeout — how long to wait before resending); cumulative ACK (acking byte N implicitly acks everything before it).
UDP's invariants
🔑 UDP is IP with ports and a checksum. Best-effort (may drop, may reorder, may duplicate — it inherits all of IP's non-guarantees), message-oriented (it preserves datagram boundaries — one
sendis onerecv, the exact opposite of TCP), no handshake (zero setup latency), no ordering, no flow control, no congestion control. Everything TCP gives you, UDP makes your problem. In exchange, it gives you no handshake latency and no head-of-line blocking. For DNS, telemetry, real-time media, and service discovery, that trade is often correct.
DNS's consistency model
🔑 DNS is hierarchical, cache-driven, and only eventually consistent. Names resolve through a delegation chain: the root servers know who runs each TLD (
.com), the TLD servers know who's authoritative forpulsely.health, and the authoritative server holds the actual records. A recursive resolver (your ISP's, or8.8.8.8) walks this chain on your behalf and caches the result. The only knob controlling how stale that cache may be is the record's TTL (time-to-live, in seconds). There is no cache-invalidation message in DNS — change a record and the old value lives on, in caches worldwide, until its TTL expires. TTL is the entire consistency story, and it's why DNS-based failover is slow (§5).
📎 Borrowed on credit: the slowloris hazard. Chapter 4 owns this — an attacker holds connections open while dribbling bytes, exhausting your pool of "things that can wait." We'll lean on it in §8 as the availability-attack lens for connection-state exhaustion, but we won't re-derive it; if the mechanism is fuzzy, that's Chapter 4's to refresh.
4. Under the hood: the handshake, the state machine, and the life of a connection
Let's make the abstractions mechanical. We'll follow one TCP connection — Pulsely's browser to api.pulsely.health — from birth to death, then resolve a name, with just enough detail to read a real trace.
The 3-way handshake
Before any HTTP byte flows, TCP performs a three-message dance to agree on starting sequence numbers and prove both directions work:
CLIENT SERVER
│ │
│ ─────── SYN, seq=x ──────────────────────────▶ │ "let's talk; my bytes start at x"
│ │
│ ◀────── SYN-ACK, seq=y, ack=x+1 ─────────────── │ "ok; mine start at y; got your x"
│ │
│ ─────── ACK, ack=y+1 ───────────────────────▶ │ "got your y; we're live"
│ │
│ ============== ESTABLISHED both sides =========== │
│ ─────── HTTP request bytes ... ───────────────▶ │
Why three messages and not two? Because both endpoints must independently (a) prove they can send and receive, and (b) synchronize sequence numbers in each direction. The client's SYN proves client→server works and announces the client's starting number x. The server's SYN-ACK proves server→client works, acknowledges x, and announces y. The client's final ACK confirms y. Two messages can't do it — you'd never confirm the second direction. This handshake costs one full round trip of pure setup before a single useful byte moves, which is why connection reuse matters so much (§5) and why cold requests feel slow.
The full state machine
That handshake is just the entrance to a larger state machine that both endpoints walk independently:
┌────────┐
│ CLOSED │
└───┬────┘
connect() │ listen()
┌─────────────────┤───────────────────────┐
▼ │ ▼
SYN_SENT │ LISTEN
│ recv SYN-ACK │ recv SYN, send SYN-ACK │
│ send ACK │ ▼
▼ │ SYN_RCVD
└──────────────▶ ESTABLISHED ◀───────────┘ recv ACK
│
── data flows both ways ──
│
active close │ passive close
(you send FIN) │ (peer sent FIN)
▼ │ ▼
FIN_WAIT_1 │ CLOSE_WAIT
│ recv ACK │ │ app calls close(), send FIN
▼ │ ▼
FIN_WAIT_2 │ LAST_ACK
│ recv FIN, send ACK│ │ recv ACK
▼ │ ▼
TIME_WAIT ── wait 2×MSL ──▶ CLOSED CLOSED
The half worth memorizing is the teardown, because it explains a production headache. Closing is a four-way exchange (each side sends its own FIN and ACKs the other's), and the two roles are asymmetric. The side that closes first — the active closer — ends up in TIME_WAIT. The side that closes second — the passive closer — passes through CLOSE_WAIT → LAST_ACK and is done quickly. You can watch all of this live:
ss -tan state time-wait # how many sockets are sitting in TIME_WAIT
ss -tan state established # currently active connections
ss -s # one-line summary of socket states
TIME_WAIT: the most misunderstood state
After closing, the active closer deliberately waits about 60 seconds before fully releasing the connection — on Linux that's a fixed compiled-in constant, TCP_TIMEWAIT_LEN. The RFC frames that same wait as 2×MSL: twice the Maximum Segment Lifetime, the longest time a stray packet could still be wandering the network before it's guaranteed dead. Linux doesn't actually compute that; it just hardcodes 60s. Why deliberately linger after you're done? Two reasons. First, the lost-final-ACK problem: if your last ACK to the peer's FIN gets dropped, the peer will retransmit its FIN, and you need to still exist to re-ACK it — otherwise the peer hangs in LAST_ACK. Second, stray old duplicates: a delayed packet from this connection could otherwise be misdelivered to a new connection that happens to reuse the same 5-tuple. TIME_WAIT holds the 5-tuple hostage long enough for any wandering old segments to die in transit.
Now the production sting. TIME_WAIT is held by the active closer, and it pins that 5-tuple — crucially, the ephemeral source port — for ~60 seconds. A busy outbound client or proxy that opens and closes thousands of short connections per second accumulates tens of thousands of TIME_WAIT sockets, each squatting on an ephemeral port. The ephemeral range is finite (often ~28,000 ports by default). Burn through it and the next connect() fails with EADDRNOTAVAIL — which is exactly Pulsely's eligibility incident from §1. The eligibility service was the active closer on every short-lived call to the clearinghouse.
Flow control: the receiver sets the pace
Every ACK the receiver sends also advertises its receive window (rwnd) — how many more bytes it can buffer right now. The sender must never have more unacknowledged bytes in flight than the window allows. If the receiver's application is slow to read (a stalled Pulsely chart-timeline reader that's not draining its socket), its buffer fills, the advertised window shrinks toward zero, and the sender stops — it waits for a window update before sending more. This is backpressure expressed at the TCP layer: a slow consumer mechanically throttles the producer, no application code required. (You'll see the application-level shadow of this in the Node section: socket.write() returning false.)
Congestion control: the sender backs off voluntarily
Flow control protects the receiver; congestion control protects the network. The sender keeps a second, separate limit — the congestion window (cwnd) — that it manages by inference, since the network never tells it directly how loaded it is. It starts small (slow start: cwnd ramps up roughly exponentially each RTT), and on the first sign of loss it backs off hard and switches to cautious linear growth (congestion avoidance). Packet loss is the congestion signal. Lose a segment and the sender assumes the network is full and slows down. Modern algorithms — CUBIC (Linux default) and BBR (Google's, which models bandwidth and RTT rather than treating loss as the only signal) — refine the ramp, but the shape holds.
Now the part with real production consequences — intuition first, term second. Picture the connection as a delivery van that must drive all the way to the receiver and back before you learn the load arrived. You can only have one van-load of unacknowledged bytes out on the road at a time — and that load is the window. On a far-away (high-RTT) link the round trip is long, so to keep bytes flowing you need a bigger van (a larger window), not a faster road. Only once you hold that picture does the formula land: throughput ≈ window / RTT. That relationship is the bandwidth-delay product, and its consequence is brutal for cross-region traffic — on a high-RTT link you need a large window to keep the pipe full, so distant transfers are window-bound, not bandwidth-bound. A 1 Gbps link from London to Sydney can crawl if the window is small: same road, van too small.
Retransmission, RTO, and head-of-line blocking
The sender continuously estimates RTT from the ACKs it sees and sets a retransmission timeout (RTO) a bit above it. If a segment isn't acked before the RTO fires, the sender resends it (it can also resend early via fast retransmit, triggered by duplicate ACKs, without waiting for the timer). Here's the subtle cost: because TCP delivers an ordered stream, a single lost segment blocks every byte behind it — the receiver has the later bytes buffered but cannot hand them to your app until the gap is filled. This is head-of-line (HoL) blocking at the TCP layer, and on a high-RTT lossy link, one dropped packet can stall the entire stream for a full retransmission cycle. (HTTP/2 and HTTP/3 have a lot to say about this — Chapter 6.)
The sockets API, mapped to the states
You've already built this; here's the mapping to the machine above. Server path: socket() → bind() → listen() (now in LISTEN) → accept() (returns a connection socket once a handshake completes into ESTABLISHED). Client path: socket() → connect() (sends the SYN, moves to SYN_SENT, returns when ESTABLISHED). Then send()/recv() move bytes over the established stream, and close() initiates the FIN teardown. Every API call you make is a transition on that state machine.
In Node: the socket events and a real, commonly-tripped DNS gotcha
import net from 'node:net';
const socket = net.connect({ host: 'api.pulsely.health', port: 443 });
socket.on('connect', () => { /* ESTABLISHED: handshake done */ });
socket.on('data', (chunk: Buffer) => { /* a SLICE of the byte stream — NOT a message */ });
socket.on('end', () => { /* peer sent FIN */ });
socket.on('error', (err) => { /* ECONNRESET, ETIMEDOUT, EADDRNOTAVAIL ... */ });
const ok = socket.write(payload); // false → kernel send buffer full (TCP flow control!)
if (!ok) socket.once('drain', () => { /* window opened; safe to write more */ });
Two things to burn in. First, 'data' is a stream slice, never a message — the §2 invariant made concrete; one logical request may span several 'data' events. Second, socket.write() returning false is libuv surfacing TCP backpressure to you — the receiver's window (or your local send buffer) is full. Ignore that false and keep writing, and you buffer unboundedly in your own process memory while a slow client refuses to drain — a memory-exhaustion bug we'll list in §6.
And the DNS gotcha that catches everyone: Node has two name-resolution paths that behave differently. dns.lookup() (what net.connect/http use by default) calls into the OS resolver via libuv's thread pool — it honors /etc/hosts, nsswitch.conf, and the OS's view, and it's synchronous-feeling but actually offloaded to threads. In plain terms, Node farms these OS lookups out to a small pool of just four background threads that it also shares with file I/O and crypto work — so if a DNS server hangs, all four threads can get stuck waiting on it, and suddenly unrelated file reads and password hashing elsewhere in your app go slow too, for no reason your own code can see. (That pool size is tunable via the UV_THREADPOOL_SIZE env var, which is one lever when this bites.) dns.resolve() performs a real DNS query over the network, bypassing the OS hosts file. They can return different answers. Reaching for dns.lookup and being surprised it ignores your DNS server's records, or that it ties up the thread pool, is a genuine, recurring production confusion.
Java/JVM contrast, where it teaches
The same kernel socket, wrapped two ways. Classic java.net.Socket/ServerSocket is blocking, thread-per-connection — accept() and read() park the calling thread, exactly the blocking model you dissected earlier. java.nio (SocketChannel + Selector) is the event-driven, readiness-based model — the same epoll-style "tell me which sockets are ready" mechanism libuv gives Node for free. The transferable principle: the OS socket is the identical kernel object in both languages; the concurrency model wrapped around it is the design choice, not a property of the network. (Worth knowing for §5: the JVM historically cached DNS resolutions forever by default via networkaddress.cache.ttl — a notorious failover footgun.)
DNS resolution, step by step
The lookup for api.pulsely.health, cold cache, top to bottom:
STUB RESOLVER (your app/OS)
│ "what is api.pulsely.health?" (UDP, port 53)
▼
RECURSIVE RESOLVER (ISP / 8.8.8.8) ── caches every answer by TTL
│ ── ask ROOT: "who handles .health?" ──▶ "the .health TLD servers"
│ ── ask .health TLD: "who handles pulsely.health?" ──▶ "ns1.pulsely.health (authoritative)"
│ ── ask AUTHORITATIVE: "A record for api.pulsely.health?" ──▶ 203.0.113.10 (TTL 60)
▼
answer returned to your app; cached at the resolver for 60s
Your stub resolver asks one question and expects one answer (a recursive query). The recursive resolver does the legwork, asking each level in turn (iterative queries) and caching as it goes. DNS rides UDP on port 53 by default (one small datagram each way — no handshake, perfect for UDP), falling back to TCP/53 when responses are too large for a single datagram (big record sets, DNSSEC signatures, anything past the EDNS0 size limit). Run dig +trace api.pulsely.health to watch this exact delegation walk happen live — it queries root, then TLD, then authoritative, printing each referral. Run dig +short and you get just the resolved address.
🛑 What we deliberately did not explain. How TLS wraps this TCP stream to make it private — the handshake-on-a-handshake — is Chapter 6, and we stop right at its doorstep. How HTTP/1.1 vs HTTP/2 vs HTTP/3 layer messages onto (or beside) TCP, and how HTTP/3 abandons TCP for QUIC-over-UDP specifically to dodge the head-of-line blocking we described — Chapter 6. How a load balancer uses the 5-tuple to pin or spread flows — Chapter 6. We've delivered an ordered, reliable byte stream to a known address. What you say over it, securely, is the next chapter.
5. In production: connection reuse, timeouts, and DNS that fails over
The mechanics are settled; here's what operating them actually demands.
Connection reuse is the single biggest performance win, full stop. Every new connection costs a handshake RTT (and, next chapter, a TLS handshake on top). The fix is to not open new connections — keep them alive and send many requests over each warm pipe. This is HTTP keep-alive on the inbound side and connection pooling on every outbound side. In Node, configure it deliberately:
import http from 'node:http';
const agent = new http.Agent({ keepAlive: true, maxSockets: 50, maxFreeSockets: 10 });
// reuse the warm pipe across requests instead of paying a handshake each time
The same principle governs your database connection pool (a fixed set of long-lived TCP connections to Postgres, borrowed per query and returned, never opened per request) and your outbound HTTP client's maxSockets. The eligibility incident in §1 was, at root, a missing pool: a fresh connection per eligibility call. Pool it and the TIME_WAIT pile-up — and the EADDRNOTAVAIL — simply vanish, because you stop being the active closer thousands of times a second.
Tuning for connection churn — and the order of operations that matters. When you genuinely have high connection turnover, the kernel knobs exist: SO_REUSEADDR/SO_REUSEPORT for binding, a widened ephemeral range (net.ipv4.ip_local_port_range), and tcp_tw_reuse to let the kernel safely reuse TIME_WAIT sockets for new outbound connections. But internalize the priority: the right fix is almost always "stop opening so many short-lived connections," not a sysctl. Kernel tuning buys headroom that masks an architectural smell. Reach for it only after the pooling is right and you still need more.
Timeouts at every layer, set explicitly, because the default is infinity. Distinguish three and set all three: the connect timeout (how long to wait for the handshake to complete — fires when a SYN gets no SYN-ACK), the socket/idle timeout (how long an established-but-silent connection may sit before you reap it), and the request timeout (an overall deadline for the whole operation). The classic bug is setting only one — a connect timeout but no read timeout — so the handshake succeeds and then the request hangs forever waiting for a response that never comes. Separately, distinguish TCP keepalive (a kernel-level "are you still there?" probe on idle connections) from application-level heartbeats (your protocol's own ping). You frequently want both, at different layers, because they detect different failures — TCP keepalive catches a dead peer; an app heartbeat catches a hung but alive peer.
DNS in production is a consistency-vs-agility dial called TTL. Short TTLs let you fail over fast (change the record, and caches expire it in seconds) at the cost of more resolver load and cache churn. Long TTLs are efficient and resilient against resolver hiccups but make changes glacial. Round-robin DNS — returning multiple A records and rotating their order — is the crudest "load balancing," and it's important to know its weakness: it's distribution, not balancing. Resolvers and clients cache and pin to one answer, there's no health awareness (a dead host stays in rotation until you manually pull it), and you get lumpy, unequal load. DNS-based failover (drop a dead A record, or pre-lower TTL before a migration) works but reacts slowly, bounded by every cache's TTL worldwide. Contrast this with a real load balancer (Chapter 6) doing sub-second health checks — which is exactly why DNS is the coarse first hop and a load balancer does the fine-grained work behind it.
🏭 Where DNS quietly bites you. Three recurring production failures, all the same root: something resolved a name once and never again. (1) A client library resolves the hostname at startup, caches the IP for the process lifetime, and keeps hammering a decommissioned host long after you've failed over — your DNS change had no effect because nobody re-queried. (2) The JVM historically cached DNS resolutions indefinitely (
networkaddress.cache.ttl), so a long-running Java service ignores failover entirely until restart. (3) Node'sdns.lookuphonors the OS resolver path (/etc/hosts,nsswitch), not your DNS server's TTLs, so what you see indigisn't necessarily what your app resolves. The fix is always one of: re-resolve on a TTL-aware schedule, use a resolving HTTP client, or front the targets with a stable VIP (a load balancer's fixed address) so the app resolves one unchanging name and the LB handles the churn behind it.
The on-call observability toolkit you'll actually reach for:
dig/dig +trace/dig +short— resolve names, watch the delegation chain, read TTLs counting down.tcpdump/ Wireshark — capture packets; "Follow TCP Stream" reassembles a connection's bytes; filter withtcp.port == 3000.ss -tan/ss -s— live socket states (count your ESTABLISHED, your TIME_WAIT) and a summary.mtr/traceroute— per-hop path latency, to find where on the route the delay lives.nc/telnet host port— the dumbest, fastest "is the port even open and listening?"
And the single most useful diagnostic distinction on the network: what happens when your SYN goes out. If you get an immediate RST back → "connection refused": the host is reachable but nothing is listening on that port (or it's actively refusing). If you get silence, then a timeout → "connection timed out": a firewall or security group silently dropped your SYN — the host may not even know you tried. Refused means "I'm here, no." Timed out means "the packet vanished." Reading a 30-second hang as a dropped SYN (go check your security groups and NACLs) rather than app slowness is a daily on-call skill that separates people who fix the incident from people who restart the app and hope.
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
Treating TCP as message-oriented. Signature: your parser reads half a JSON object, or two requests glued into one buffer, and chokes — intermittently, under load, never in a unit test. Fix: TCP is a byte stream with no message boundaries; you must frame messages yourself — a length prefix or a delimiter — and buffer until a full message has arrived. This is the framing discipline you met earlier, and it's a property of TCP, not a bug in your code.
Ephemeral port / TIME_WAIT exhaustion.
Signature: a busy outbound client or proxy starts failing with EADDRNOTAVAIL under load; ss -tan state time-wait | wc -l shows tens of thousands. Fix: stop being the active closer so often — pool and reuse connections (keep-alive). Only then, if still needed, widen the ephemeral port range and consider tcp_tw_reuse. The architecture, not the sysctl, is the real fix.
Idle connections silently dropped by NAT or a load balancer.
Signature: the first request after an idle period hangs and then resets (ECONNRESET); the connection looked fine and was never closed by either app. Fix: an intermediary's idle timeout evicted the flow's state while both endpoints still believed it ESTABLISHED — a half-open connection. Set TCP keepalive shorter than the NAT/LB idle timeout, or send app-level heartbeats, or validate pooled connections on borrow before using them.
DNS resolved once at boot. Signature: you fail over to a new IP and traffic keeps hammering the dead one for hours. Fix: re-resolve on a TTL-aware schedule, use a resolving HTTP client, or front the target with a stable VIP so the app resolves one fixed name and the LB handles the change. (The §5 trio in pitfall form.)
Assuming round-robin DNS load-balances evenly. Signature: one instance is on fire while its siblings idle. Fix: DNS round-robin is crude distribution with no health awareness and aggressive client/resolver caching — it pins. For actual balancing with health checks, put a real L4/L7 load balancer in front (Chapter 6).
Confusing connect timeout with read timeout. Signature: a request hangs forever even though "we set a timeout." Fix: you set one — the handshake completed within the connect timeout, then the response never came and no read timeout fired. Set all three: connect, read/idle, and an overall request deadline.
Ignoring socket.write()'s false return.
Signature: memory climbs without bound when a slow client connects; eventual OOM. Fix: false is TCP backpressure — the receiver's window is full. Respect it: pause the source and wait for 'drain' before writing more, so a slow reader throttles you instead of forcing you to buffer the world in process memory.
Reading a firewall drop as application slowness. Signature: a 30-second hang ending in timeout, no RST, app metrics clean. Fix: a dropped SYN, not slow code. Read it as "the packet was silently discarded" and go inspect security groups, NACLs, and firewall rules — the connection never reached your app at all.
7. Tradeoffs
Senior judgment here is naming the spectrum and saying why you stand where you stand.
TCP ↔ UDP. TCP buys you reliability, ordering, and congestion control — at the cost of a handshake RTT and head-of-line blocking. UDP buys you zero setup latency and no HoL blocking — at the cost of building any reliability you need yourself. Default to TCP for Pulsely's request/response APIs (you want exactly-once, ordered delivery and you can afford one RTT). Reach for UDP when the workload tolerates loss or rebuilds reliability its own way: DNS (one tiny query, retry if lost), metrics/telemetry (drop a sample, who cares), real-time media (a late video frame is useless — better to skip it than stall), and service discovery. The deciding questions: can you tolerate loss, do you need ordering, and is head-of-line blocking a latency killer for your data?
New connection per request ↔ pooled keep-alive. A fresh connection per request is simple and gives perfect isolation; pooling amortizes the handshake across many requests and keeps your socket and ephemeral-port count sane. For any service with real traffic, pool — the §1 incident is what "don't pool" costs. Reverse toward fresh connections only when connections are genuinely rare, or when strict per-request isolation outweighs the handshake cost.
Short ↔ long DNS TTL. Short TTL means fast failover and agility; long TTL means cache efficiency, lower resolver load, and resilience against resolver-cache thundering herds. Lower the TTL in the hours before a planned migration (so the cutover is fast), then raise it back for stable infrastructure. The TTL is a dial you turn for the moment, not a constant you set once.
DNS round-robin/failover ↔ a real load balancer. DNS-only costs zero infrastructure and works literally everywhere, but it has no health awareness and reacts at cache-TTL speed. A load balancer health-checks in sub-seconds and balances by real load — but it's another box to run (and another thing that can fail, Chapter 6). You accept DNS-only for a tiny service, or as the coarse geo/multi-region first hop, then put an LB behind each record for the fine-grained work.
NAT (IPv4 conservation) ↔ end-to-end addressability (IPv6). NAT is operationally familiar and conserves scarce IPv4 addresses, but it breaks inbound connectivity and its stateful translation table is a fragile, finite resource. IPv6 restores end-to-end addressability — every host directly reachable — at the cost of new operational habits. This stops being abstract the moment Pulsely needs inbound peer connections (clearinghouse result callbacks, telehealth WebRTC) or runs at a scale where the NAT table itself is the bottleneck.
Kernel tuning ↔ architectural fix. Twisting sysctl knobs buys real headroom — and masks the real problem, which is usually "too many short-lived connections." Tune after the architecture is right (pooling, keep-alive, sane timeouts), never as the first move. A server held together by exotic sysctl settings is a server one kernel upgrade away from an outage.
🚫 A framing this book rejects. "Private IPs and NAT mean we're safe — internal services don't need their own authentication." NAT is address conservation that accidentally blocks unsolicited inbound packets; it is not a security boundary. It's defense in depth at best, and it evaporates the instant an attacker is already inside the network (a compromised pod, a misconfigured peering, an SSRF that originates requests from inside). Treating "it's on a private address" as "it's protected" is how a single foothold becomes a full breach. Authenticate every service-to-service call regardless of which subnet it rides.
8. Security & scale notes
TCP's threat surface starts at the handshake. A SYN flood sends a torrent of SYNs and never completes the handshake, leaving the server's connection table full of half-open SYN_RCVD entries until it can accept nothing new — a connection-state exhaustion DoS. The defense is SYN cookies: the server encodes the connection state into the sequence number it sends and keeps no per-connection memory until the final ACK proves the client is real. Separately, off-path RST injection / spoofing — an attacker guessing a connection's 5-tuple and sequence number to forge a RST and kill it — is mitigated by hard-to-guess initial sequence numbers (randomized ISNs make the seq space too large to guess). And every ESTABLISHED and TIME_WAIT socket costs kernel memory, so connection-state exhaustion is a DoS vector in its own right — which connects straight to the slowloris hazard we borrowed on credit earlier: an attacker who holds connections open (or trickles bytes) is attacking your availability by exhausting a finite kernel resource, and the defenses are the same family — timeouts, max-connection caps, and a hardened front-line proxy.
DNS has its own threat model. Cache poisoning / spoofing — forging a UDP response to a resolver before the real one arrives, planting a malicious IP in its cache — is why source-port randomization and query-ID randomization matter (they widen the space an attacker must guess) and why DNSSEC (cryptographically signed records) exists. DNS is also abused as an exfiltration / command-and-control channel (data smuggled out as subdomain labels in lookups that egress firewalls often wave through). And the recursive resolver is a single point of failure and a chokepoint — for availability, for censorship, and for observability — which is why resolver redundancy and monitoring matter.
Scale is a concurrency-model story, not a raw-network one. The famous progression from C10K to C10M (ten thousand to ten million concurrent connections) is, as you saw earlier, about the model wrapped around the socket — event loops over readiness notification, not thread-per-connection — far more than about network bandwidth. The real ceiling for a single box is per-connection memory and the FD limit (ulimit -n), not link speed. And the bandwidth-delay product sets a hard throughput floor on long links: throughput ≈ window / RTT, so filling a fat, high-latency pipe requires a large window — cross-region throughput is window-bound, and you tune window sizes, not buy more bandwidth, to fix it.
Load degrades nonlinearly, and p99 moves first. Because TCP intentionally slows under loss (cwnd collapse on congestion), a saturating link doesn't fail cleanly — it degrades smoothly and then steeply. Worse, bufferbloat (oversized router queues) means latency spikes long before you see any packet loss or errors: the queue absorbs the overload by adding delay. The operational consequence for Pulsely: your p99 latency will climb well before your error rate does. Latency is the early-warning signal; by the time you're seeing connection errors, the network has been quietly suffering for a while.
🔑 Connection state is a finite, attackable resource. Every entry in your connection table — ESTABLISHED, TIME_WAIT, half-open SYN_RCVD — consumes kernel memory and, for outbound flows, an ephemeral port. Both raw load and deliberate attack saturate this the same way. This is why the senior reflexes are identical for performance and for security: reuse connections, cap concurrency, and set aggressive timeouts. The thing that makes you fast (not churning connections) is the thing that makes you hard to exhaust.
The scale endgame for "where do clients connect first." Anycast (advertising the same IP from many physically distant locations, so the network routes each client to the topologically nearest one) plus multi-region DNS is how global services answer the "first hop" question — getting the user onto a nearby front door before the request even reaches a load balancer. We name it here and set it up; the machinery is later chapters.
9. Interview lens & exercises
Interview questions
The same question separates levels by the quality of the reasoning, not the recall.
"Walk me through everything that happens when Pulsely's browser requests api.pulsely.health/chart."
- Junior answer: "It sends an HTTP request to the server." Jumps straight to the app, skipping every network layer.
- Senior answer: narrates the buckets and attributes latency to each — "DNS resolve first (often cached at several layers, so frequently near-free; cold, it's a round trip or more through the resolver hierarchy); then a TCP handshake, one RTT of pure setup, which is why keep-alive matters; then the request and response over the established stream; and on a warm pooled connection the handshake is skipped entirely." Same path, every hop annotated with cost and whether reuse eliminates it.
"You see thousands of TIME_WAIT sockets. Is it a problem?"
- Junior: "Set
tcp_tw_reuse." - Senior: "TIME_WAIT is held by the active closer for ~2×MSL — it protects against lost final ACKs and stray old duplicates, so it's correct behavior, not a bug. It becomes a problem only when a busy outbound client exhausts ephemeral ports and starts getting
EADDRNOTAVAIL. The real fix is connection reuse so you stop closing thousands of connections a second;tcp_tw_reuseis a last-resort patch over the architecture."
"TCP or UDP for this service, and why?"
- Junior: "TCP, because it's reliable."
- Senior: reasons per use case — "TCP for request/response where I need ordered, exactly-once delivery and can afford a handshake RTT. UDP where setup latency or head-of-line blocking dominate and I can tolerate or rebuild reliability myself: DNS, telemetry, real-time media. And I'd note you can build reliability on UDP — QUIC does exactly that." Names the deciding axes: loss tolerance, ordering need, HoL sensitivity.
"DNS failover changed the record ten minutes ago but traffic still hits the dead host. Why?"
- Junior: "DNS is broken."
- Senior: "TTL plus caching. Every resolver and client caches the old answer until its TTL expires, and many clients resolve once at startup and never re-query — the JVM historically cached forever, Node's
dns.lookupfollows the OS resolver path. The change is correct; it's propagating at cache speed. The durable fix is a stable VIP so the app resolves one unchanging name and a load balancer handles the cutover."
"What's the difference between connection refused, connection timed out, and connection reset?"
- Junior: treats them as interchangeable "the connection didn't work" errors.
- Senior: maps each to a mechanism — "refused = a RST came back because nothing is listening on that port; timed out = the SYN was silently dropped, almost always a firewall or security group; reset = a RST arrived mid-stream, the peer tore the connection down or crashed. Refused and timed out are connect-time and point at different causes — refused means the host is up and saying no; timed out means the packet vanished."
Exercises & the Pulsely increment
Pen and paper first, then the terminal. Fluency, not perfection.
-
Capture a real connection. Run Pulsely locally (client → Express API → Postgres). Start
tcpdump -i lo port 3000 -w chart.pcap, hit the chart endpoint once, stop the capture, and open it in Wireshark. Annotate: find and label the SYN / SYN-ACK / ACK handshake, the HTTP request bytes and response bytes ("Follow TCP Stream"), and the FIN/ACK teardown. Then identify the active closer (who sent the first FIN) and find its socket sitting in TIME_WAIT viass -tan state time-wait. You will never again think of a connection as magic. -
Watch DNS resolve and rotate. Run
dig +trace api.pulsely.health(against a mock zone) and read the delegation walk: root →.comTLD → authoritative. Then resolve a name with multiple A records and rundig +shortseveral times in a row to observe round-robin rotation, and watch the TTL count down on repeated queries to a recursive resolver. Now you've seen both the hierarchy and the caching. -
Do subnet math by hand. Given
10.20.0.0/22: state the full address range, the usable host count, the network address, and the broadcast address. Then, given three arbitrary IPs, decide which share that subnet (and would therefore talk directly over the link) versus which would have to route. If you can't do this without a calculator, reread §3 — it's a guaranteed whiteboard question and a daily skill for reading firewall rules. -
Force TCP backpressure, then break it. Write a tiny Node
netecho client/server. Have the sender write faster than the receiver reads, and observesocket.write()returningfalseand the'drain'event firing when the window reopens. Then deliberately ignore thefalseand keep writing — watch process memory climb without bound as you buffer everything a slow peer can't drain. You've just reproduced both the correct backpressure handling and the §6 memory-exhaustion pitfall, from the I/O model up.
Key takeaways
- The network is a stack of layers, each maintaining an illusion atop a weaker guarantee below: IP answers "where" (best-effort, connectionless, may drop/reorder/duplicate); TCP answers "did it arrive, in order, intact?" — reliability is something TCP manufactures, not something the wire provides.
- The 5-tuple
(protocol, src IP, src port, dst IP, dst port)is a flow's identity — what the kernel demuxes on, what NAT rewrites, what a load balancer hashes. A connection is a state machine held in two kernels, not a physical pipe. - TCP is a byte stream with no message boundaries — you must frame messages yourself. The handshake costs one RTT (so reuse connections); the active closer pays TIME_WAIT, which exhausts ephemeral ports under churn (
EADDRNOTAVAIL). - Flow control (receiver window) and congestion control (cwnd, loss-as-signal, throughput ≈ window/RTT) explain backpressure and why cross-region transfers are window-bound.
socket.write()returningfalseis TCP backpressure surfacing to your code. - DNS turns a name into an address through a cache hierarchy whose only consistency knob is TTL — which is why failover is slow and "resolved once at boot" is a recurring outage.
- Diagnose by bucket: DNS vs handshake vs app vs transfer. Read
refused(RST, nothing listening) vstimed out(dropped SYN, firewall) vsreset(mid-stream RST) as different failures —dig,tcpdump, andssare the tools. - Connection state is finite and attackable — the reflexes for performance (pool, cap, timeout) are the reflexes for security (SYN floods, slowloris, state exhaustion).
← Previous: Ch 4 — I/O & Concurrency Models · Up: Part I overview · Master TOC · Next: Ch 6 — Networking II: TLS, HTTP, Proxies →