Chapter 06 / 10 · Foundations

One request across the network

The handler takes 40 µs and the reader waits 800 ms. Where the rest goes, and what the network loses without telling anyone.

This chapter lets you account for the time between a reader’s browser and hitcount’s handler, and name each thing that can go missing on the way. The network is the bottom of the latency ladder and the first place where failure is partial: a packet can simply fail to arrive, and nobody is obliged to tell you.

A reader in Mumbai finishes a post. hitcount runs on one server in the eastern United States. The browser’s developer tools show the hit request taking about 800 ms. hitcount’s own log says the handler took 40 µs. The difference is twenty thousand times the work, and all of it is spent before or after our code runs.

A name becomes an address

The page’s script sends its request to hitcount.example.com. Before anything else, the browser needs an IP address. It asks the operating system, which asks a recursive resolver, usually run by the reader’s ISP or a public service. If the resolver has the answer cached, it replies at once. If not, it asks a root server which servers handle .com, asks those which servers are authoritative for example.com, and asks those for the address. Each answer comes with a TTL, the number of seconds it may be cached.

The TTL is the first cache you configure, and it sets a trade-off you will meet again. We once moved hitcount to a new server by changing its DNS record, which had a TTL of 3,600 seconds. For the next hour, resolvers that had cached the old address kept sending readers to the old server, and some resolvers ignore TTLs and hold answers longer. Any hit sent there was lost, because the old server had been switched off. The fix for next time: lower the TTL to 60 seconds a day before a move, so that every cache has expired the long TTL before the change, and keep the old server running, forwarding hits to the new one, until its traffic falls to zero. The cost of a short TTL is more lookups, so more readers pay a full resolution on their first request. We raise it again once the move is done.

A connection costs round trips before it carries anything

IP, the protocol that carries packets between machines, promises nothing: packets can be lost, duplicated or reordered. TCP builds a reliable, ordered stream of bytes on top of it. Before any data flows, the two ends exchange three packets to agree on starting sequence numbers: SYN, SYN-ACK, ACK. That is one full round trip. Then TLS 1.3 spends one more round trip agreeing on keys and proving the server’s identity. Only then can the browser send the request and wait one further round trip for the response.

browserhitcountDNS lookup0–1 RTTTCP handshake1 RTTTLS 1.3 handshake1 RTTRequest + response1 RTTat 200 ms per round trip: ~800 ms before the handler’s 40 µs of work
Fig 1 · A fresh HTTPS request pays for DNS, TCP and TLS before the request itself crosses the wire

The round-trip time (RTT) between Mumbai and the eastern US is set mostly by physics. Light in optical fibre travels at about two-thirds of its speed in a vacuum, roughly 200,000 km a second. The great-circle distance is about 13,000 km, and real cable routes are longer. So one way takes at least 65 ms and a round trip at least 130 ms; in practice it is around 200 ms. No amount of bandwidth changes that number.

Predict first

The reader’s browser has no open connection to hitcount and its resolver has the address cached. Using an RTT of 200 ms, how long until the first hit is answered? The reader then opens a second post and leaves it a minute later. How long does that hit take?

Show the worked answer

First hit: DNS is answered from the nearby resolver’s cache, a few milliseconds. Then TCP’s handshake (200 ms), TLS 1.3 (200 ms) and the request itself (200 ms). About 600 ms, plus the 40 µs of real work. If the resolver had to go to the authoritative servers, add up to another round trip or more, which gets us to the 800 ms in the developer tools.

Second hit: if the browser kept the connection open (HTTP keep-alive), only the request crosses the ocean, so about 200 ms. If the connection was closed in between, the whole 600 ms is paid again.

Two improvements follow. Reuse connections wherever possible, which is what keep-alive and connection pools do. And move the handshakes closer to the reader: a proxy at the edge of the network near Mumbai terminates TCP and TLS 20 ms away and forwards the hit to hitcount over a connection it keeps open permanently. The reader’s first hit then costs a few short round trips plus one long one. Because the blog sends hits with navigator.sendBeacon, which does not hold up the page, readers never feel any of this; it matters for /top, which the sidebar waits for.

Written out as a budget, the three cases look like this. The edge column assumes a proxy about 10 ms from the reader that keeps a warm connection open to hitcount.

StepFresh connection to hitcountReused connectionFresh connection to a nearby edge
DNS0–200 ms00–20 ms
TCP handshake200 ms020 ms
TLS 1.3 handshake200 ms020 ms
Request and response200 ms200 ms20 ms + 200 ms on the warm edge-to-origin link
hitcount’s handler0.04 ms0.04 ms0.04 ms
Total600–800 ms~200 ms~260–280 ms

The edge removes the handshakes from the long path but not the ocean. The last 200 ms can only go if the request stops crossing it, and for hits there is a way to arrange that. The edge can answer the browser with 204 No Content immediately and forward hits to hitcount in batches every second. The reader’s request then completes in 60 to 80 ms. The cost is a new failure: if an edge machine crashes while holding a second’s worth of hits, they are gone, and the browser was already told they had been received. For a page view counter we accept that. For anything that represents money or a user’s action, the acknowledgement would have to wait until the data was stored somewhere durable, and the round trip would come back.

What TCP does when packets go missing

TCP numbers every byte. The receiver acknowledges what has arrived, and the sender retransmits anything that is not acknowledged in time, or sooner if repeated acknowledgements show a gap. It also paces itself. Flow control stops the sender from overrunning the receiver’s buffer. Congestion control stops it from overrunning the network: a new connection starts with a small window, typically ten packets or about 14 KB in flight, and doubles it every round trip until loss signals that the path is full. This is called slow start.

Slow start explains a number that otherwise looks wrong. hitcount’s /top response is about 2 KB and fits in the first window, so it arrives one round trip after the request. The platform’s CSV export of a blog’s counts is about 1 MB. On a fresh connection the window grows 14 KB, 28, 56, 112 and so on; the total sent after k round trips is about 14 KB × (2ᵏ − 1), so 1 MB needs about seven round trips. At 200 ms that is 1.4 seconds, even on a link that could carry the whole file in a few milliseconds. Reusing a warm connection avoids most of it.

Because TCP delivers bytes strictly in order, one lost packet holds up everything sent after it until the retransmission arrives. This head-of-line blocking shaped the last decade of HTTP:

VersionTransportRequests per connectionWhere one lost packet hurts
HTTP/1.1TCPone at a timethat request; browsers open ~6 connections to work around it
HTTP/2TCPmany interleaved streamsevery stream on the connection waits
HTTP/3QUIC over UDPmany independent streamsonly the stream that lost the packet; handshake also combined

The queue in front of accept

One more piece of TCP machinery explains a latency pattern that looks like a clue once you know it. The first chapter’s trace showed hitcount calling listen(3, 4096). The second argument sizes a queue inside the kernel. When a browser’s SYN arrives, the kernel completes the handshake on hitcount’s behalf, without waking the program, and puts the finished connection on that queue. Only when hitcount calls accept does the connection leave the queue and become a file descriptor.

Go’s HTTP server accepts on a goroutine of its own and starts a new goroutine per connection, so it keeps accepting even when every handler is stuck; that is why the performance chapter will find a pile of waiting goroutines rather than a full queue. A server with a fixed pool of worker threads behaves differently. The team’s early Python prototype of hitcount ran sixteen threads, and when all sixteen were blocked on the same slow lock, nothing called accept and the queue filled. Once it is full, Linux by default quietly drops new SYNs instead of refusing them, so the client hears nothing and, after its retransmission timer expires, sends the SYN again. That timer starts at one second and doubles on each retry. The result is a distinctive histogram: most connections take a round trip to establish, and then there are clusters at about one second and about three seconds, with almost nothing in between. Latencies that bunch at those values are worth reading as “the server’s accept queue was full”, and the kernel counts the drops (netstat -s reports listen queue overflows) so the suspicion can be confirmed.

A bigger queue is not the fix. It only lets more connections wait longer. The fix is whatever stopped the program accepting, and the queue size is a reminder that the network stack has buffers between every pair of layers, each of which hides a stall for a while and then turns it into timeouts somewhere else.

Bytes, not messages

Version 3 of hitcount added a second way to receive hits, to count readers whose browsers block the script. The blog’s web server streams its access log to hitcount over a plain TCP connection, one page path per line. The first implementation of the receiving end looked like this:

buf := make([]byte, 4096)
for {
    n, err := conn.Read(buf)
    if err != nil {
        return
    }
    for _, path := range strings.Split(string(buf[:n]), "\n") {
        if path != "" {
            s.hit(path)
        }
    }
}

It passed every test, because on a laptop each line the sender wrote arrived as one read. In production it miscounted, and here is the sequence. TCP delivers a stream of bytes and keeps no record of where the sender’s writes began or ended. Under load the sender’s lines are packed into packets and the packets arrive in bursts, so a read returns whatever is in the buffer at that moment. One read returned /posts/unicode\n/posts/ca, the next che-design\n. The loop counted a page called /posts/ca and a page called che-design, and the real post lost a view. At thousands of lines a second, that produced thousands of junk keys, which is the unbounded-map problem from the operating system chapter arriving by a new route.

The fix is to keep the partial line until the rest arrives. In Go, bufio.Scanner does exactly that, splitting on newlines across reads. The cost is a decision about limits: the scanner refuses lines longer than its buffer (64 KB by default), so a sender that never sends a newline cannot make us buffer forever. Every protocol over TCP must define where one message ends, with a delimiter as here, a length prefix, or a header that states the length, as HTTP’s Content-Length does.

The network does not say no; it goes quiet

The most damaging line in hitcount is fetchTitle. The first version called the content system with Go’s default HTTP client, which has no timeout. On a normal day the content system answers in about 20 ms, at worst 150 ms.

One evening the content system’s database stalled. Its web server still accepted connections, so there was no error, just silence. Step by step: the next hit for a page hitcount had not seen before called fetchTitle and waited. In version 2 that call happened while holding s.mu, because it sat inside the code that inserts a new page. Every other hit now queued for the lock. Goroutines piled up, one per incoming request, each holding its connection and a few kilobytes of memory. hitcount, a service whose job does not require titles at all, stopped counting because a dependency that only provides titles went quiet.

The fix had three parts. A client with a timeout: http.Client{Timeout: 2 * time.Second}, chosen as a comfortable multiple of the content system’s normal worst case. The call moved out from under the lock: a new page is inserted with its path as a provisional title, and a background goroutine fetches the real title and fills it in later. And a failed fetch is retried a few minutes later rather than immediately. The cost is visible: during an outage of the content system, new posts appear in the sidebar under their paths for a while. We chose that over an outage of our own.

Choosing the number deserves more care than it usually gets. A timeout far above the dependency’s normal worst case, say 30 seconds, protects nothing: by the time it fires, thousands of requests have queued behind it, as Little’s law in the performance chapter will show. A timeout at or below its normal p99 fails requests that would have succeeded, one in a hundred on an ordinary day. A small multiple of the normal p99 sits between the two. Retries need the same discipline. If every caller retries a timed-out request three times, a dependency that slows down receives up to four times its usual load at the moment it can least handle it. So hitcount retries title fetches at most once, minutes later, and the Distributed Systems pathway covers the general forms: retry budgets, jittered backoff and deadlines passed from caller to callee.

A timeout leaves a harder question, and it belongs to the next pathway. When a request times out, we do not know whether the other side did the work. If the content system had been a billing service rather than a source of titles, a timed-out request might have charged the customer, and a retry might charge them twice. On one machine an operation either happened or did not. Across a network there is a third answer, “unknown”, and the Distributed Systems pathway is largely about designing for it.

When not to go lower than HTTP

The raw TCP log feed cost us a framing bug that HTTP would have prevented, because HTTP already defines where each request begins and ends. Most services should speak HTTP or gRPC to each other and leave sockets to the libraries. Write your own protocol over TCP only when you need something the standard ones cannot give you, such as very low per-message overhead at very high rates, and then define the framing first.

Revisit the network design when the numbers move. If most readers are far from the server, terminate connections at the edge. If hit volume grows by orders of magnitude, batch: one request carrying a hundred hits pays the round trip once instead of a hundred times. If a dependency sits on the request path, give every call to it a timeout and decide in advance what the request does when the timeout fires.

We can now price every part of one request: instructions, memory, system calls, round trips. The next chapter, Reasoning about cost, turns those prices into estimates made before building, and uses them to decide whether one machine can run hitcount for the whole platform.