Volume 1 Companion: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Companion: Foundations of Computing

V1·09

Networking

Companion to Volume 1, chapter 09: how addressing, transport and application protocols connect; new angles (India Post's PIN and house number as IP and port, a speed-of-light budget from Hyderabad to Frankfurt, a phone call against a stack of postcards for TCP against UDP, a notary for certificates); what the chapter simplifies, from the JVM ignoring DNS TTLs for 30 seconds to connections that succeed when nobody's listening and writes that succeed to a peer that's gone; the theory behind it (the bandwidth-delay product, the Two Generals problem, the robustness principle and its critics); the JDK's DNS cache policy and its built-in HTTP server's limits; four debugging drills; interview questions with how to approach each.

6 sections · ~18 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 09 has three strands. Addressing and routing get a packet from one machine to another, hop by hop. Transport turns unreliable packets into either datagrams (UDP) or a reliable byte stream between two programs (TCP). Names, security and applications sit on top: DNS finds the address, TLS makes the stream private and authenticated, and HTTP gives it meaning.

addressing and routing transport names, security, apps layers envelopes inside envelopes Ethernet, MAC one hop IP, CIDR addresses · subnets routing hop by hop NAT many hosts, one address ARP, ICMP, DHCP the helpers ports, sockets which program UDP datagrams, no promises TCP reliable byte stream retransmission seq numbers · ACKs flow, congestion control pace receiver · network teardown, TIME_WAIT FIN · RST DNS names → addresses TLS encrypt · authenticate certificates chains of trust HTTP requests over a stream sockets API connect · accept · read timeouts, fallacies the network is unreliable bottom carries by rewritten at or or by paced by ends with then verified by written with needs under goes deeper: ch8 sockets are file descriptors · Volume 3 ch 37: HTTP clients and servers in Spring exercises: P1–P12 build a subnet calculator, servers, a DNS client and a CA, and watch TCP on the wire
Concept map of chapter 09: addressing and routing (layers and encapsulation, Ethernet and MAC addresses, IP addresses and CIDR, routing and NAT, ARP, ICMP and DHCP), transport (ports and sockets, UDP, TCP's handshake, sequence numbers, retransmission, flow and congestion control, teardown and TIME_WAIT) and names, security and applications (DNS, TLS and certificates, HTTP, the sockets API, timeouts and the fallacies of distributed computing), with links such as DNS turning names into the addresses IP routes and TLS running on top of TCP's byte stream.

The links worth remembering:

  • Each layer only trusts the one below for one thing. IP promises "best effort delivery to an address"; TCP adds order and retransmission; TLS adds secrecy and identity; HTTP adds requests and responses. Every bug in this chapter's drills is one layer assuming a promise the layer below never made.
  • Most of what makes a request slow happens before your code runs. A DNS lookup, a TCP handshake (one round trip) and a TLS handshake (one more in TLS 1.3) all precede the first byte of HTTP. That's why connection reuse matters so much (Chapter Exercises P9 measures it).
  • The sockets API hides the network as a file. read and write look like file I/O (the Companion to chapter 08's descriptors), but a network "file" can stall, reset or vanish, so every network call needs a timeout and a plan for failure.

Explain it differently

1. IP and ports are a PIN code and a flat number. India Post routes a letter to PIN 500039 (Uppal, Hyderabad) without knowing anything about who lives there: that's IP routing, hop by hop, by address prefix. The flat number and name on the envelope pick the person in the building: that's the port picking the program on the machine. A subnet is everyone sharing the first digits of the PIN; NAT is a gated community's front desk that receives everything at one address and hands it to the right flat.

2. The speed of light sets a floor nobody can optimise. Light in fibre travels about 200,000 km/s. Hyderabad to Frankfurt is about 7,100 km in a straight line (computed from coordinates; real cables are longer). So:

Leg Minimum time
one way 7,100 ÷ 200,000 ≈ 36 ms
round trip 71 ms
TCP + TLS 1.3 setup (2 round trips) plus one request (1 round trip) 213 ms before any server work

No framework, cache or faster CPU can beat those 213 ms for a fresh connection; only fewer round trips (reused connections, TLS session resumption, a server in Mumbai) can. Chapter Exercises C3 diagnoses "slow from India" with exactly this arithmetic.

3. TCP is a phone call; UDP is a stack of postcards. A call is set up first (the handshake), words arrive in order, and if a word is garbled the other side says "pardon?" (retransmission). If the line goes quiet you can't tell whether they hung up, are thinking, or the line died (Gaps 3). Postcards need no setup and each is independent, but some never arrive and they can arrive out of order. Live video and DNS queries prefer postcards; orders and payments need the call.

4. Flow control is a waiter who watches your plate. A good waiter doesn't bring the next dish until you've made room. TCP's receive window is the receiver announcing how much room is left; a slow reader shrinks it to zero and the sender stops. Congestion control is different: it's the kitchen slowing down because the corridor to the dining room is jammed, not because you're full. One protects the receiver, the other protects the network.

5. A certificate is a notarised ID card. A stranger shows an ID card saying "I am api.tiffinbox.in". You don't know them, but the card is stamped by a notary (an intermediate CA), whose own licence is stamped by an authority your phone already trusts (a root CA). TLS checks the chain of stamps, that the card hasn't expired, and, critically, that the name on the card matches who you meant to call. Skipping the last check is accepting any valid ID from anyone.

6. DNS is a phone book that everyone photocopies. Looking up a number at the source every time would be slow, so resolvers, operating systems and programs all keep copies, each for as long as the entry's TTL says. Changing a number means waiting for every copy to expire, and some copies (like the JVM's, Gaps 1) follow their own rules about how long to keep them.

7. A socket's buffers are a letterbox, not the recipient's hands. write() returning means your letter is in your own outbox (the kernel's send buffer), not that anyone read it. The kernel delivers it later, and if the recipient has moved away, you learn on your next letter (Gaps 3). Only an application-level reply ("got it, order 42 saved") tells you the other program actually processed what you sent.

8. Timeouts are the only way to tell "slow" from "dead". On a network, silence is ambiguous: the server may be working, overloaded, partitioned or gone. A timeout is a decision to stop waiting, not a fact about the server. Choosing it is a business decision (how long will a user wait?), and the chapter's fallacies of distributed computing are reminders that the silence will happen.

Gaps and misconceptions

What the chapter oversimplifies

1. "Resolvers cache records for their TTL": the JVM uses its own clock. The chapter explains TTLs. Java has its own DNS cache in InetAddress, and by default it keeps successful lookups for 30 seconds, whatever the record's TTL. Real output: a name in /etc/hosts changed from 10.0.0.1 to 10.0.0.2 after 5 seconds, looked up every 5 seconds by one JVM:

Terminal
t= 0s  /etc/hosts says 10.0.0.1  JVM resolves 10.0.0.1
t= 5s  /etc/hosts says 10.0.0.1  JVM resolves 10.0.0.1
t=10s  /etc/hosts says 10.0.0.2  JVM resolves 10.0.0.1
t=15s  /etc/hosts says 10.0.0.2  JVM resolves 10.0.0.1
t=20s  /etc/hosts says 10.0.0.2  JVM resolves 10.0.0.1
t=25s  /etc/hosts says 10.0.0.2  JVM resolves 10.0.0.1
t=30s  /etc/hosts says 10.0.0.2  JVM resolves 10.0.0.2

For 20 seconds after the change, the JVM kept using the old address. With a real DNS record whose TTL is 5 seconds (as many failover setups use), the JVM still waits up to 30. Older JVMs running with a security manager cached forever. Failed lookups are cached too, for 10 seconds by default (networkaddress.cache.negative.ttl=10 in java.security). And on top of the JVM, connection pools keep connections to the old address open regardless of DNS (drill D1).

2. "connect() succeeds when the server accepts the connection": the kernel accepts it, not your code. The chapter's handshake happens in the kernel. A server socket's backlog queue holds completed connections until the program calls accept(), so clients can connect to a program that's frozen, deadlocked or overloaded. Real output, a server that binds but never calls accept():

Terminal
1. connect() to a server that never calls accept(): succeeded in 4.13 ms
   write() of the request: succeeded
   read() of the reply: java.net.SocketTimeoutException: Read timed out

Connect and write both succeeded; only the read timed out. So a "TCP port is open" health check proves the kernel is alive, not the application (drill D2). The backlog also explains why clients of an overloaded server see slow responses before they see refused connections: the queue absorbs them first.

3. "TCP is reliable": it delivers to the peer's kernel, and tells you about failures late. Writing to a peer that has already closed its socket, real output:

Terminal
3. write #1 to a closed peer: succeeded
3. write #2 to a closed peer: java.net.SocketException: Broken pipe
3. write #3 to a closed peer: java.net.SocketException: Broken pipe

The first write succeeded: the bytes went into the local send buffer and out to a peer that answered with a reset. Only the next write discovered the reset. So "my write succeeded" never means "the other program received it", let alone processed it. Reliable delivery is TCP's promise between kernels while the connection lives; delivery to the application needs an application-level acknowledgement (drill D4, and theoretical gap 2).

4. "HTTP is request, then response": servers can answer before you've finished asking. A server can reject a request from its headers alone (too large, unauthorised) and close the connection while the client is still sending the body. Real output, a client sending a 2 MB body to a server that reads 64 bytes, answers 413 and closes:

Terminal
2. client, while still sending the body: java.net.SocketException: Broken pipe
   client read the reply: HTTP/1.1 413 Payload Too Large

The client hit an exception while writing, though the server's real answer (413) was sitting in its receive buffer, readable. Clients that treat a write error as the final outcome report "connection error" instead of "too large", and servers that close abruptly with unread data can make the kernel send a reset that destroys the reply before the client reads it. Well-behaved servers drain some of the unread body before closing (the JDK's own HTTP server drains up to 64 KB, Code walkthrough), and well-behaved clients try to read a response even after a write fails (drill D3).

Common misconceptions

Misconception What's actually true Where it's shown
"Lowering the DNS TTL makes failover fast." Only for clients that honour it; the JVM caches for 30 s, and pools keep old connections. Gaps 1; drill D1
"The port answers, so the service is healthy." The kernel completes handshakes into the backlog without the program. Gaps 2; drill D2
"write() succeeded, so they got it." It reached your send buffer; failure shows up on a later call. Gaps 3; drill D4
"A write error means the request failed." The server may have answered (413, 401) and closed early. Gaps 4; drill D3
"HTTPS means the server is who I think it is." Only if the hostname is verified against the certificate; raw SSLSockets don't by default. Explain it differently 5; theoretical gap 4
"Bandwidth decides how fast a transfer is." For one TCP connection over a long path, the window and the round-trip time decide. theoretical gap 1

Theoretical gaps: the ideas behind the chapter

1. The bandwidth-delay product: why a fat pipe can be slow. A TCP sender can have at most one window of unacknowledged data in flight, and acknowledgements take a round trip to come back. So one connection's throughput is at most window ÷ RTT. With a 64 KB window and Hyderabad–Frankfurt's 71 ms floor (Explain it differently 2), that's 64 KB ÷ 0.071 s ≈ 0.92 MB/s, about 7.4 Mbit/s, on a 1 Gbit/s link. To fill the link, the window must be at least bandwidth × RTT: 1 Gbit/s × 71 ms ≈ 8.9 MB. Modern stacks scale windows automatically (window scaling, autotuning), but proxies, small buffers and packet loss bring the limit back: with loss rate p, the Mathis formula puts throughput near (MSS ÷ RTT) × 1.22 ÷ √p. Long, lossy paths are slow per connection, whatever the bandwidth.

2. The Two Generals problem: you can't be sure the other side knows. Two generals must attack together, communicating by messengers who may be captured. Every "I agree" needs an acknowledgement, which needs an acknowledgement… No finite exchange makes both certain. It's a proof that no protocol over an unreliable channel guarantees common knowledge, and it's the deep reason "exactly-once delivery" doesn't exist on networks. What systems build instead is at-least-once delivery plus idempotent processing (the TiffinBox build's stages 5 and 8): retry until acknowledged, and make repeats harmless.

3. The robustness principle, and why it's now questioned. Postel's rule, "be conservative in what you send, be liberal in what you accept", helped early internet protocols interoperate. Decades later, RFC 9413 (2023) argues that liberal acceptance causes harm: implementations come to depend on each other's bugs, protocols can't evolve because tolerated quirks become de facto standards (ossification), and lenient parsers disagree with strict ones about where a message ends, which is how request smuggling attacks work (a proxy and a server parse one byte stream as different requests). The modern stance matches stage 6's decoder: precise parsing, explicit errors, and extension points designed in.

4. Authentication is a separate check from encryption. TLS can encrypt a connection to anyone; it's only secure if the client checks that the certificate names the host it meant to reach. Libraries split these: Java's HttpClient and HttpsURLConnection verify hostnames, but a raw SSLSocket checks only that the chain is trusted, unless you set SSLParameters.setEndpointIdentificationAlgorithm("HTTPS"). Disabling verification "temporarily" for a test environment is one of the most common ways production code ends up accepting any certificate (Volume 7).

5. Layering is a trade-off, and sometimes the layers collapse. Strict layering makes protocols replaceable, but it hides information that would help: TCP doesn't know HTTP's message boundaries, so one lost packet stalls every request multiplexed on that connection (HTTP/2's head-of-line blocking, Chapter Exercises leaves-out). QUIC (under HTTP/3) merges transport, encryption and multiplexing into one layer over UDP to fix exactly that. Layers are an engineering choice, revisited when the costs show.

6. Latency, not bandwidth, dominates interactive systems. Bandwidth has grown by orders of magnitude over decades; latency within a continent hasn't, because it's bounded by light and routing. For web apps and APIs, the number of round trips (DNS, TCP, TLS, redirects, sequential API calls) is usually the biggest lever, which is why connection reuse, batching endpoints and moving servers closer matter more than faster links.

Applying it

Code walkthrough

Two pieces of the JDK show networking policies the chapter only implies. Excerpts from jdk-21-ga.

InetAddressCachePolicy: how long the JVM trusts a DNS answer

sun/net/InetAddressCachePolicy.java:

Java
    public static final int FOREVER = -1;
    public static final int NEVER = 0;

    /* default value for positive lookups */
    public static final int DEFAULT_POSITIVE = 30;
Java
    static {
        Integer tmp = getProperty(cachePolicyProp, cachePolicyPropFallback);
        if (tmp != null) {
            cachePolicy = tmp < 0 ? FOREVER : tmp;
            propertySet = true;
        } else {
            /* No properties defined for positive caching. If there is no
             * security manager then use the default positive cache value.
             */
            if (System.getSecurityManager() == null) {
                cachePolicy = DEFAULT_POSITIVE;
            }
        }
        tmp = getProperty(negativeCachePolicyProp,
                          negativeCachePolicyPropFallback);

        if (tmp != null) {
            negativeCachePolicy = tmp < 0 ? FOREVER : tmp;
            propertyNegativeSet = true;
        }
        if (cachePolicy > 0) {
            tmp = getProperty(cacheStalePolicyProp,
                              cacheStalePolicyPropFallback);
            if (tmp != null) {
                staleCachePolicy = tmp;
            }
        }
    }

Read it with Gaps 1:

  • The record's TTL appears nowhere. The JVM's resolver API returns addresses, not TTLs, so the cache uses one fixed duration for every name: the networkaddress.cache.ttl security property if set, otherwise 30 seconds.
  • FOREVER was the default with a security manager, for a security reason: caching forever prevents DNS rebinding tricks against applets. In an era of cloud failover, it caused outages instead. (Security managers are deprecated for removal since JDK 17, so this branch matters only for old setups.)
  • Negative answers use networkaddress.cache.negative.ttl, which the shipped java.security file sets to 10 seconds: a name that failed to resolve keeps failing for 10 seconds even after it's fixed.
  • stale.ttl (new in JDK 21) lets the JVM keep serving an expired answer for a while if the DNS server is unreachable, trading freshness for availability during a DNS outage.

Set it with -Dsun.net.inetaddr.ttl=… or the security property networkaddress.cache.ttl, early in startup, deliberately.

ServerConfig: the built-in HTTP server's defaults

The JDK ships a small HTTP server (com.sun.net.httpserver). Its limits, in sun/net/httpserver/ServerConfig.java:

Java
    private static final int DEFAULT_IDLE_TIMER_SCHEDULE_MILLIS = 10000 ; // 10 sec.
    private static final long DEFAULT_IDLE_INTERVAL_IN_SECS = 30;
    private static final int DEFAULT_MAX_CONNECTIONS = -1 ; // no limit on maximum connections
    private static final int DEFAULT_MAX_IDLE_CONNECTIONS = 200 ;
    private static final long DEFAULT_MAX_REQ_TIME = -1; // default: forever
    private static final long DEFAULT_MAX_RSP_TIME = -1; // default: forever
    private static final int  DEFAULT_MAX_REQ_HEADERS = 200;
    private static final long DEFAULT_DRAIN_AMOUNT = 64 * 1024;

And what happens to an unread request body when a handler closes its input, in LeftOverInputStream:

Java
    public void close () throws IOException {
        if (closed) {
            return;
        }
        closed = true;
        if (!eof) {
            eof = drain (ServerConfig.getDrainAmount());
        }
    }

What the defaults tell you:

  • Draining up to 64 KB is the fix for Gaps 4: before the server answers and closes, it reads (and discards) up to 64 KB of whatever the client is still sending, so small leftovers don't trigger a reset that would destroy the response. Larger leftovers aren't worth reading; the connection is closed instead.
  • No limit on connections, and requests may take forever (-1). A client that sends one header byte every few seconds (a "slowloris" attack) holds a connection indefinitely. The server is fine for tools and tests, but production servers need request deadlines, connection limits and header-size limits.
  • At most 200 request headers bounds one dimension of parsing, the same principle as stage 6's bounded decoder.

The TiffinBox build's stage 9 writes its own server and has to choose every one of these numbers.

Read it yourself

  1. Why can't the JVM simply use each DNS record's TTL?
  2. Why is draining capped at 64 KB rather than reading the whole unread body?

Debugging drills

D1. Failover took two minutes instead of ten seconds

The kitchen API's DNS record has a 10-second TTL, so operations expected failover to the standby to take about 10 seconds. The order service (Java, Apache HttpClient with a connection pool) kept calling the dead primary for about two minutes. A JVM-only reproduction:

Terminal
t=10s  /etc/hosts says 10.0.0.2  JVM resolves 10.0.0.1
...
t=30s  /etc/hosts says 10.0.0.2  JVM resolves 10.0.0.2

List every layer that kept the old address, and fix each.

D2. The health check is green, the service is down

The load balancer's health check opens a TCP connection to port 8080 and marks the instance healthy if it connects. During an incident, one instance was deadlocked (no request threads free), yet stayed "healthy" and kept receiving a third of the traffic, all of which timed out. A reproduction:

Terminal
1. connect() to a server that never calls accept(): succeeded in 4.13 ms
   write() of the request: succeeded
   read() of the reply: java.net.SocketTimeoutException: Read timed out

Explain, and design a better health check.

D3. Large uploads report "connection reset" instead of "file too large"

The bulk-order upload endpoint rejects files over 1 MB with 413. Users uploading 5 MB files see "Network error: broken pipe" or "connection reset" in the app, never the friendly message. A reproduction:

Terminal
2. client, while still sending the body: java.net.SocketException: Broken pipe
   client read the reply: HTTP/1.1 413 Payload Too Large

Explain what the server and the client each did, and fix both sides.

D4. Notifications "sent" but never received

A notifier keeps a long-lived TCP connection to a partner's gateway and writes one line per notification. The partner restarted their gateway at 14:02; the notifier logged notifications at 14:03 as "sent", and only at 14:03:01 did it see an error and reconnect. The partner never received the 14:03 notifications. A reproduction:

Terminal
3. write #1 to a closed peer: succeeded
3. write #2 to a closed peer: java.net.SocketException: Broken pipe

Explain, and redesign the notifier so nothing is lost.

Career-oriented

Interview prep

Mid level

Q1. Walk through everything that happens, at each layer, when the TiffinBox app calls https://api.tiffinbox.in/menu for the first time.

How to get there. Go in time order and name the layer each time: DNS, TCP, TLS, HTTP, then the response and connection reuse. Give round-trip counts, and say what's cached afterwards. Interviewers look for order, completeness and the cost of each step.

Q2. A teammate's code reads a JSON request from a socket with in.read(buffer) and parses whatever it gets. It works locally and fails randomly in production. Why?

How to get there. TCP is a byte stream, not a message stream. Say what read returns, why it differs between localhost and real networks, and what a correct reader does (framing).

Senior level

Q3. Your API's p99 latency for users in Europe is 900 ms, while the server-side p99 is 80 ms. Where does the rest go, and what would you do?

How to get there. Compute the physical floor (distance, RTT) and count round trips per request, then look for multiplication factors (fresh connections, sequential calls, redirects, large payloads on slow links). Propose fixes in order of leverage, with measurement.

Q4. Design how the order service calls the kitchen's tablet gateway reliably, given that networks drop, gateways restart, and orders must reach the kitchen exactly once in effect.

How to get there. Accept that exactly-once delivery is impossible (Two Generals), and design for at-least-once delivery plus idempotent processing, with timeouts, retries, backoff and a durable outbox. Cover what happens in each failure.

Staff level

Q5. Over a year, your services accumulated five different HTTP client configurations with different timeouts, retries, DNS settings and TLS settings, and incidents keep coming from them. How do you fix this across the organisation?

How to get there. Standardise the defaults in a shared client library or a service mesh, make deviations explicit and reviewed, and measure. Cover the specific settings (timeouts, retry budgets, connection lifetime, DNS TTL, TLS verification) and how you'd roll it out.

Q6. Leadership wants to serve customers in the Gulf and Southeast Asia from the Hyderabad region only, to save costs. How do you evaluate it?

How to get there. Quantify the latency cost (distance, round trips per user action), its business impact (conversion, app experience), then options between "one region" and "full multi-region" (CDN, edge, read replicas), with costs and risks.