Specialization DepthVol. 17 · Part XVII
0 / 0

Trails / Specialization Depth

SD·194D

Networking, Distributed Systems and System Design at L5/L6

Depth in the three topics that decide how systems behave between machines: ladders for each; TCP, TLS, HTTP/2 and HTTP/3 internals and the L4 toolkit (ss, tcpdump, curl timings, dig, mtr); the classic Nagle-plus-delayed-ACK stall reproduced on loopback (43 ms per request to 0.07 ms with TCP_NODELAY); timeouts and keep-alive across Java, Go, Rust, Python and C; production network failures (port exhaustion, conntrack, MTU black holes); distributed-systems fundamentals at L3 (failure models, FLP, CAP and PACELC, consistency models, clocks, consensus); a quorum simulation showing why R + W > N matters; L4/L5/L6 work in distributed systems (partial failure, idempotency, sagas, metastable failures, Jepsen-style testing); and what L5/L6 system design looks like: the method, the design document, a review rubric, and the habits that separate a design that survives from one that only looks good on a whiteboard.

19 topics · ~20 min read · 31-question quiz
Updated Suggest a correction

Start here: what L5/L6 networking, distributed systems and system design look like

At L2 you can call an API, put a service behind a load balancer and use a managed database. At L4 you can explain a timeout spike from TCP retransmissions, or a split-brain from a misconfigured failover. At L5/L6 you design systems that keep working when the network misbehaves, and you know what each guarantee costs.

One example: what consensus buys and costs

etcd (the database behind Kubernetes) keeps several copies of its data in agreement using the Raft consensus protocol: one member is the leader, and a write counts only once a majority (a quorum) has stored it. The lab ran real etcd clusters on one machine:

Cluster Write latency (median) Leader killed Two of three members killed
1 member 1.26 ms (no failover possible) —
3 members 1.72 ms writes paused ~1.5 s, then a new leader took over writes and up-to-date reads stopped; possibly stale reads still worked
5 members 2.03 ms writes paused ~1.5 s (would survive 2 failures)

Consensus costs latency on every write (more so across real networks, where it's at least one round trip to a majority), buys survival of minority failures, and refuses to answer rather than give a wrong answer when a majority is gone. That trade-off (consistency over availability during a partition) is the CAP theorem in practice, and choosing it deliberately is L5 work.

How deep to go in networking, distributed systems and system design

Volume 17 defines six mastery levels; for this chapter's topics they look like this:

Level You can…
L1 explain TCP/IP, DNS, HTTP, replication, consensus and CAP in plain words
L2 build services that call each other with timeouts, retries and idempotency
L3 explain congestion control, TLS, Raft, quorums, clocks and consistency models
L4 debug packet loss, retransmits, split brain, clock skew and stale reads with tools
L5 design systems with explicit consistency, partitioning, replication and failure behaviour
L6 run distributed systems at scale: multi-region operations, incidents and capacity

Networking: the ladder

Level Observable behaviour
L1 Knows the layers, IP, TCP vs UDP, DNS, HTTP, TLS as terms
L2 Configures clients and servers correctly: timeouts, keep-alive, TLS, proxies; reads HTTP traffic in browser dev tools; uses curl and dig
L3 Explains TCP's handshake, sequence numbers, flow control, congestion control (slow start, CUBIC, BBR), Nagle and delayed ACK, TIME_WAIT; TLS 1.3 handshake; HTTP/2 multiplexing and its head-of-line blocking; QUIC/HTTP/3; DNS resolution and caching; NAT and load balancing
L4 Diagnoses with ss, tcpdump/Wireshark, curl -w timings, mtr, dig +trace; finds retransmissions, window limits, handshake latency, DNS problems, connection churn
L5 Chooses protocols (REST, gRPC, WebSockets, SSE, message queues), connection management (pooling, multiplexing), timeout and retry strategy, edge architecture (CDN, anycast), service-to-service security (mTLS)
L6 Operates networks of services: port exhaustion, conntrack tables, MTU problems, certificate rotation, DNS outages, cross-region latency budgets, egress cost

Networking internals for L3

  • TCP connection setup: SYN, SYN-ACK, ACK: one round trip before data. With TLS 1.3, one more round trip (TLS 1.2: two). Over a 50 ms link, a fresh HTTPS request costs ≥ 100 ms before the first byte of the request is sent; hence connection reuse, keep-alive, and TLS session resumption.
  • Flow control: the receiver advertises a window (how much it can buffer); a sender can't have more unacknowledged data in flight. Throughput ≤ window / RTT: a 64 KB window over a 100 ms path caps at about 5 Mbit/s regardless of bandwidth (window scaling fixes this).
  • Congestion control: the sender also limits itself to a congestion window, growing it (slow start, then additive increase) until loss or delay signals congestion. CUBIC (Linux default) reacts to loss; BBR models bottleneck bandwidth and RTT and performs better on lossy, long paths.
  • Nagle's algorithm (sender) buffers small writes while unacknowledged data is outstanding; delayed ACK (receiver) waits up to ~40 ms to piggyback an ACK. Together they stall request patterns that write twice then read.
  • Connection teardown: the side that closes first enters TIME_WAIT for 2×MSL (60 s on Linux), holding the 4-tuple. Many short connections from one client to one server can exhaust ephemeral ports.
  • HTTP/1.1 keeps connections alive but serves one request at a time per connection (browsers open ~6 per host). HTTP/2 multiplexes streams over one TCP connection with header compression, but a lost packet stalls all streams (TCP head-of-line blocking). HTTP/3 runs over QUIC (UDP), which has per-stream loss recovery, a combined transport+TLS handshake (1-RTT, 0-RTT on resumption), and connection migration across networks (Wi-Fi to cellular).
  • DNS: stub resolver → recursive resolver (caches by TTL) → root → TLD → authoritative. Most "the network is slow" reports at application start are DNS or TLS, not bandwidth.

Nagle and delayed ACK, reproduced

A client sends a 10-byte header and a 100-byte body as two writes, then waits for a reply. On loopback:

Python
# Nagle's algorithm + delayed ACK: a write-write-read request pattern on loopback, with and without TCP_NODELAY
for _ in range(n):
    c.sendall(b"H" * 10)                   # write 1: header
    c.sendall(b"B" * 100)                  # write 2: body — Nagle holds it until write 1 is ACKed
    c.recv(2)                              # read the response
Text
TCP_NODELAY=off:  43.13 ms per request
TCP_NODELAY=on :   0.07 ms per request

A 600× slowdown on a link with microsecond latency. The causal chain: the first write goes out immediately; Nagle holds the second (there's unacknowledged data); the server reads the header and waits for the body before replying, so it has nothing to piggyback an ACK on, and its delayed-ACK timer runs ~40 ms; only then does the ACK arrive and Nagle releases the body. Fixes: TCP_NODELAY (most HTTP clients and RPC frameworks set it by default), or coalesce writes into one buffer (better: fewer packets too). The L4 signature: latencies clustered suspiciously near 40 ms (or 200 ms on some systems).

The L4 toolkit

Shell
# Where does the time go in one HTTPS request?
curl -s -o /dev/null -w 'dns=%{time_namelookup}s connect=%{time_connect}s tls=%{time_appconnect}s ttfb=%{time_starttransfer}s total=%{time_total}s\n' https://example.com/

ss -tanp state established '( dport = :5432 )' | wc -l   # connections to Postgres
ss -tan state time-wait | wc -l                           # TIME_WAIT pile-up (port exhaustion risk)
ss -ti dst 10.0.3.12                                      # per-connection RTT, cwnd, retransmits
sudo tcpdump -i any -nn 'tcp port 8080 and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0)'   # SYNs and RSTs only
dig +trace api.tiffinbox.in                               # follow resolution from the root
mtr -rwc 50 api.payments.example                          # path loss and latency per hop

Timeouts and keep-alive, per language

Defaults are dangerous: several standard clients have no request timeout by default.

// Java 11+ HttpClient: connect timeout on the client, request timeout per request; HTTP/2 when available
var client = java.net.http.HttpClient.newBuilder()
        .connectTimeout(java.time.Duration.ofSeconds(1))
        .version(java.net.http.HttpClient.Version.HTTP_2)
        .build();
var req = java.net.http.HttpRequest.newBuilder(java.net.URI.create("https://api.payments.example/v1/charges"))
        .timeout(java.time.Duration.ofSeconds(2))          // without this, no overall timeout
        .POST(java.net.http.HttpRequest.BodyPublishers.ofString("{}"))
        .build();

Networking at L6

  • Ephemeral port exhaustion: a client opening and closing many short connections to one destination runs out of source ports (TIME_WAIT holds them 60 s). Symptoms: EADDRNOTAVAIL/"cannot assign requested address". Fix: connection pooling and keep-alive; more destination IPs; tcp_tw_reuse for outbound.
  • conntrack table full: NAT and Kubernetes' kube-proxy (iptables mode) track every connection; a full table drops new connections silently (nf_conntrack: table full, dropping packet in kernel logs).
  • MTU black holes: tunnels and VPNs reduce MTU; if ICMP "fragmentation needed" is blocked, large packets vanish: small requests work, large responses hang. Fix MSS clamping, allow ICMP, or set MTU explicitly.
  • DNS: resolver overload in Kubernetes (ndots:5 turns one lookup into several), negative caching of failures, JVM DNS caching (networkaddress.cache.ttl) defeating failover.
  • Cross-region and egress: inter-region RTT (Mumbai–Singapore ~60 ms) sets the floor for synchronous designs; cloud egress costs money per GB, which shapes architecture at scale.
  • Certificates: expiry and rotation (Volume 16, ch. 188), mTLS identity in service meshes.

Distributed systems: the ladder

Level Observable behaviour
L1 Knows terms: replication, partitioning, consensus, CAP, eventual consistency
L2 Uses distributed building blocks correctly: idempotent consumers, retries with backoff, distributed caches, managed databases with replicas
L3 Explains failure models, FLP impossibility, CAP and PACELC precisely, consistency models (linearizable → eventual), logical and hybrid clocks, Raft/Paxos, quorums, CRDTs
L4 Diagnoses partial failures, split brain, clock-skew bugs, duplicate processing, retry storms, replication lag anomalies, using traces and logs across services
L5 Chooses consistency per operation, replication and partitioning schemes, saga vs 2PC vs outbox, idempotency strategy, coordination services; designs to avoid distribution when possible
L6 Operates distributed systems: metastable failures, rebalancing, cluster upgrades, verification (Jepsen-style), chaos experiments, cost of coordination

Distributed-systems fundamentals for L3

  • Failure models: crash-stop, crash-recovery, omission (lost messages), Byzantine (arbitrary/malicious). Most business systems assume crash-recovery with an asynchronous network: messages can be delayed, lost, duplicated or reordered, and you can't distinguish a slow node from a dead one.
  • FLP impossibility (1985): in an asynchronous system with even one crash failure, no deterministic algorithm guarantees consensus terminates. Practical systems escape it with timeouts (partial synchrony): Raft and Paxos are always safe and are live when the network behaves well enough.
  • CAP: during a network partition, a system must choose between consistency (linearizability) and availability (every non-failed node answers). PACELC adds: else (no partition), choose between latency and consistency. The everyday trade-off is the ELC part.
  • Consistency models, strongest to weakest: linearizable (single up-to-date copy; real-time order) → sequential → causal (causally related operations seen in order by everyone) → read-your-writes / monotonic reads (session guarantees) → eventual (replicas converge if writes stop).
  • Clocks: physical clocks drift and jump (NTP corrections); never order events across machines by wall-clock time alone. Lamport clocks give an order consistent with causality; vector clocks detect concurrency; hybrid logical clocks combine physical time with logical counters (CockroachDB, MongoDB); Google Spanner's TrueTime exposes clock uncertainty bounds and waits them out.
  • Consensus: Raft elects a leader per term, replicates a log, commits entries once a majority has them; a minority partition can't make progress (CP). Used in etcd (Kubernetes), Consul, CockroachDB, TiKV, Kafka's KRaft.
  • Quorums: with N replicas, writes acknowledged by W and reads querying R, if R + W > N every read set overlaps every write set, so a read sees the latest acknowledged write (absent sloppy quorums and concurrent writes).
Python
# Quorum replication: with N replicas, writes acknowledged by W and reads from R, is a read guaranteed to see the latest write?
import random
random.seed(3)
def trial(N, W, R, trials=20000):
    stale = 0
    for _ in range(trials):
        versions = [1] * N                       # every replica has version 1
        for i in random.sample(range(N), W):     # write v2 reaches only W replicas before acknowledging
            versions[i] = 2
        read = random.sample(range(N), R)        # a later read contacts R random replicas
        if max(versions[i] for i in read) < 2:   # newest version among those read
            stale += 1
    return stale / trials

for N, W, R in ((3, 1, 1), (3, 2, 1), (3, 1, 2), (3, 2, 2), (5, 3, 3), (5, 2, 2)):
    rule = "R+W>N" if R + W > N else "R+W≤N"
    print(f"N={N} W={W} R={R} ({rule}): stale reads {trial(N, W, R):6.1%}")
Text
N=3 W=1 R=1 (R+W≤N): stale reads  66.6%
N=3 W=2 R=1 (R+W≤N): stale reads  33.3%
N=3 W=1 R=2 (R+W≤N): stale reads  33.1%
N=3 W=2 R=2 (R+W>N): stale reads   0.0%
N=5 W=3 R=3 (R+W>N): stale reads   0.0%
N=5 W=2 R=2 (R+W≤N): stale reads  30.2%

The simulation ignores background repair (read repair, anti-entropy), which in real Dynamo-style stores (Cassandra, Riak, DynamoDB internally) shrinks the stale window over time. The design knob is visible: Cassandra's QUORUM reads and writes on N=3 give R=W=2; ONE/ONE is faster and more available but can return stale data.

Distributed systems at L4–L6

L4 failure signatures:

Symptom Likely cause Evidence
Duplicate charges or emails Retries after timeouts where the first attempt succeeded; at-least-once delivery without idempotent consumers Same idempotency key or message id processed twice in logs
Data "goes back in time" Read from a lagging replica after a write Replica lag metrics; trace showing write to primary, read from replica
Two leaders Split brain: lease expired on one side of a partition but the old leader kept acting Overlapping leader terms in logs; missing fencing tokens
Events processed out of order Partitioning key wrong; consumer parallelism across a key Partition assignment, offsets
Outage persists after the trigger is fixed Metastable failure: retries/queues keep load above capacity Throughput flat at max while goodput is near zero
Timestamps disagree with causality Clock skew between hosts NTP offsets; events ordered by wall clock

L5 decisions:

  • Avoid distribution where possible: a single PostgreSQL primary handles more than most systems need; every network hop adds failure modes. Distribute for a reason (scale, isolation, availability, team autonomy) and know which.
  • Consistency per operation: the credit ledger needs linearizable writes (one primary); the menu can be eventually consistent through a CDN; a user's own writes need read-your-writes.
  • Cross-service workflows: sagas (a sequence of local transactions with compensations; orchestration or choreography) over two-phase commit (blocking, coordinator failure stalls participants; rarely available across services anyway). Outbox for reliable event publication.
  • Idempotency everywhere a retry can happen: idempotency keys on APIs, dedupe tables on consumers, natural idempotence (SET status = 'skipped' rather than toggling). "Exactly-once" in practice means at-least-once delivery plus idempotent processing.
  • Fencing tokens for leases and locks: a monotonically increasing number checked by the resource, so a paused old leader's writes are rejected.

L6 concerns:

  • Metastable failures (Bronson et al., 2021): a system that's stable at a load can be pushed by a trigger (a cache flush, a brief outage) into a state where a sustaining effect (retries, cold caches, queue backlogs) keeps it overloaded after the trigger is gone. Defences: retry budgets, load shedding, admission control, circuit breakers, and capacity headroom.
  • Verification: Jepsen (Kyle Kingsbury's analyses) has found consistency violations in many databases' claims; run partition and clock-skew tests for systems whose guarantees matter, and use deterministic simulation testing where available (FoundationDB pioneered it; TigerBeetle and others follow).
  • Upgrades and rebalancing: rolling upgrades of consensus clusters one node at a time maintaining quorum; partition rebalancing that saturates networks; version skew between nodes.
  • Coordination cost: cross-region consensus adds RTT to every write; designs partition by geography or tenant to keep coordination local.

System design: the ladder

Level Observable behaviour
L1 Knows the vocabulary: load balancer, cache, queue, sharding, replication, CDN
L2 Can sketch a standard design for a known problem (URL shortener, chat) from patterns
L3 Explains why each component behaves as it does and what it costs (latency, consistency, operations)
L4 Can find the bottleneck or failure point in an existing design; can explain why a production system failed in architectural terms
L5 Designs from requirements: clarifies them, estimates load, considers alternatives, chooses with explicit trade-offs, plans evolution and failure handling; designs are proportionate to the problem
L6 Has designs that ran in production for years; knows how designs fail over time (scale shifts, team changes, cost); designs for operability, migration and decommissioning

Volume 12 covers system design in depth. What distinguishes L5/L6 in practice:

The method (Volume 12's, condensed): (1) clarify functional requirements and non-functional ones with numbers (latency, availability, consistency, data volume, growth); (2) estimate (QPS, storage, bandwidth, memory) to know which problems are real; (3) define APIs and data model; (4) high-level design; (5) deep-dive the hardest parts (the parts the estimates say matter); (6) failure modes, security, observability, cost; (7) evolution: what changes at 10× and 100×, what you'd build first.

The design document: context and goals; non-goals; requirements and estimates; proposed design; alternatives considered and why not; risks and mitigations; rollout and migration plan; operational plan (SLOs, dashboards, runbooks); cost; open questions. The "alternatives considered" and "non-goals" sections are where L5 shows.

A review rubric (use it on your own designs before others do):

Dimension Weak Strong
Requirements Vague ("fast", "scalable") Quantified NFRs tied to user journeys
Proportionality Microservices and Kafka for 50 requests/s Simplest design meeting the numbers, with a path to grow
Trade-offs Options listed, choice asserted Choice justified against requirements; costs stated; review triggers
Data Storage picked by fashion Access patterns drive data model and store; consistency per operation
Failure Happy path only Each dependency's failure considered; degradation defined; blast radius limited
Operability Absent SLOs, observability, deploy and rollback, runbooks, on-call
Security "Add auth" Threat model; authz model; data classification
Cost Ignored Unit cost estimate; biggest cost drivers named
Evolution Static picture Migration path, versioning, what breaks at 10×

L6 habits: design for change (the design will be wrong in ways you can't see yet: keep boundaries clean and decisions reversible where cheap); design migrations as first-class (every system eventually moves); write down why (ADRs outlive the people who made the decisions); revisit designs with production data; and design for decommissioning too.

Lab: Raft in practice with etcd

Setup. etcd 3.6.5 on the lab machine, clusters of 1, 3 and 5 members, each on its own loopback address (127.0.0.1–5) with fresh data directories and default timeouts (heartbeat 100 ms, election 1,000 ms). A Python client writes through etcd's JSON gateway (/v3/kv/put) to a follower, so each write is forwarded to the leader and replicated. Scope: one machine, so network latency is near zero; the experiments show consensus mechanics, and real deployments add network round trips to every number.

Experiment 1: the cost of agreement

500 sequential writes per cluster:

Members Majority needed p50 p99
1 1 1.26 ms 2.99 ms
3 2 1.72 ms 4.13 ms
5 3 2.03 ms 3.28 ms

Each write is persisted (fsync) on a majority before it's acknowledged, so adding members adds work even with zero network distance. Across zones (~1 ms RTT) a 3-member write gains roughly a round trip; across regions, tens to hundreds of milliseconds. That's why consensus clusters are kept small (3 or 5) and their members close together, and why systems put only coordination data (leases, configuration, locks) in them, not bulk data.

Experiment 2: losing the leader

Continuous writes through a follower; the leader was killed with SIGKILL 2 s into the run (client timeout 0.5 s):

Members Writes OK Writes failed Longest gap between successful writes
3 4,065 3 1,506 ms, starting at the kill
5 3,166 3 1,510 ms, starting at the kill

The followers waited for the election timeout (≈ 1 s, randomised) without heartbeats, held an election, and a new leader (member 1 and member 5 respectively) resumed service. No acknowledged write was lost. The unavailability window is a tunable trade-off: shorter election timeouts fail over faster but risk needless elections on a slow network or a GC-paused leader.

Experiment 3: losing the majority

3-member cluster Write Linearizable read Serializable read
all up 200 OK — —
1 member down 200 OK — —
2 members down timeout timeout 200 OK (possibly stale)

With no majority, etcd refused writes and up-to-date reads instead of risking divergent histories: the "C" side of CAP. A serializable read answered from the surviving member's local copy, explicitly allowed to be stale. Clients that need availability over freshness can choose it per request; Kubernetes, for example, lets watches and some reads proceed on cached data while the control plane can't make changes.

Try it yourself

  1. Lower --election-timeout to 300 ms and --heartbeat-interval to 50 ms; remeasure the failover gap.
  2. Freeze the leader with kill -STOP for 2 s (like a long GC pause) and observe what happens when it resumes.
  3. Write through the leader instead of a follower and compare latency.
  4. Use Toxiproxy (Volume 11) to add 20 ms between members and remeasure Experiment 1.

Revision sheet: networking, distributed systems and system design at L5/L6

Key ideas

  • Networking for L3: TCP handshake, flow and congestion control, retransmission timeouts, head-of-line blocking, TLS 1.3, HTTP/2 and HTTP/3, DNS caching and TTLs, load-balancer behaviour.
  • Distributed fundamentals: partial failure, unbounded delays, clocks (physical, logical, hybrid), idempotency, retries and deduplication.
  • Replication and consensus: leader-based, multi-leader, leaderless; quorums; Raft/Paxos; leases and fencing tokens.
  • Consistency models: linearizable, sequential, causal, eventual; CAP and PACELC.
  • L4–L6: debugging with packet captures, metrics and traces; split brain; multi-region designs; operating coordination services.
  • System design: requirements and numbers first, then data model, partitioning, replication, caching, async boundaries and failure handling with explicit trade-offs.

Numbers to remember

  • Lab (one machine): etcd write p50 1.26 / 1.72 / 2.03 ms for 1 / 3 / 5 members.
  • Lab: leader loss → ~1.5 s write gap (election timeout ≈ 1 s).
  • Majority of n members = ⌊n/2⌋ + 1; tolerates ⌊(n−1)/2⌋ failures.

Pitfalls

  • Even-sized consensus clusters (4 tolerates no more failures than 3).
  • Spreading consensus members across far regions without measuring write latency.
  • Storing bulk data in coordination services.
  • Using stale reads where correctness needs linearizable ones.
  • Failover without fencing.

Glossary

  • Quorum: the majority required to commit.
  • Election timeout: time without heartbeats before followers start an election.
  • Linearizability: operations appear to happen atomically in real-time order.
  • Fencing token: a monotonically increasing number that rejects stale leaders.
  • PACELC: if partitioned, choose A or C; else choose latency or consistency.