Performancelatencyrttspeed of lightcross-regionn+1

Latency: Same Machine to Cross-Continent

Round-trip time spans five orders of magnitude from loopback to cross-continent, every request costs at least one of them and a cold HTTPS request three or four, so a chatty pattern that is invisible in one data centre is a multi-second disaster across an ocean.

SimulatedConceptual
▶ InteractiveInterview question
Progress

You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.

The problem

The same endpoint, the same code, the same query plan: 8 ms when the service and database are in one rack, 4.2 s when the database moved to another region. Nothing got slower. The distance between two machines is a fixed cost paid per round trip — and the code makes 40 of them.

Five rungs of distance

Simulated

The interactive uses illustrative values chosen to be typical; real numbers depend on hardware, provider, path and load, and the only way to know yours is to measure. With that said, the ladder is remarkably stable across environments because each rung is set by a different physical fact: loopback by kernel stack cost, in-DC by switch hops and cable length, in-region by the distance between availability zones, cross-region and cross-continent by the great-circle distance in fibre.

What matters is not the values but the ratios: each rung is roughly 5–50× the previous. A design that tolerates a thousand round trips at 50 µs (50 ms total) tolerates forty at 1 ms (40 ms) and two at 150 ms. Distance does not make individual requests slower in a way you can optimise; it multiplies the number of round trips by a constant you cannot change.

Illustrative RTTs (simulated — measure your own)
BetweenTypical RTTSet byRound trips in a 100 ms budget
Same machine (loopback)~20–50 µskernel stack, no NIC~2,000–5,000
Same data centre / AZ~0.1–0.5 msswitch hops, tens to hundreds of metres~200–1,000
Same region (AZ ↔ AZ)~1–2 mstens of km of fibre~50–100
Cross region (e.g. US East ↔ US West)~30–80 msthousands of km~1–3
Cross continent / ocean~100–250 msten thousand+ km, cable routes0–1

The physics, and why the floor is real

Light in fibre travels at about 200,000 km/s, two thirds of c, because of the glass’s refractive index. A round trip over d kilometres of fibre therefore takes at least 2d/200,000 seconds: 10 µs per kilometre, round trip. New York to London is ~5,600 km on the map, giving a floor of ~56 ms; real cables are longer and add amplifiers and routers, so ~70–75 ms is what you see. Frankfurt to Sydney: ~16,500 km, a floor of 165 ms, ~250 ms in practice through Singapore.

Each rung also adds equipment delay — a switch forwards in a few microseconds, a router in tens, and a queue in front of a congested link in milliseconds (Where the Time Goes: The Request Timeline) — but at continental distance propagation dominates everything. This is a lower bound: no faster server, no better protocol, no more bandwidth reduces the time a photon needs to cross the Atlantic. Faster is only possible by being closer, which is the entire reason a CDN exists (CDNs: The Networking View).

The RTT multiplier

Simulated

No request costs less than one RTT: the bytes go there and an answer comes back. A cold HTTPS request costs more: a DNS lookup (often cached, otherwise ≥ 1 RTT to the resolver), one RTT for the TCP handshake (The Three-Way Handshake), one for TLS 1.3 (The TLS Handshake; two for TLS 1.2), then one for the request and response — three to four RTTs before the first byte. A warm request over a pooled keep-alive connection (Keep-Alive and Connection Reuse, Connection Pooling) costs one. Across an ocean that is the difference between ~180 ms and ~700 ms for the same call, which is why connection reuse matters more the further away the peer is.

Larger responses add round trips of their own: TCP slow start begins at ~10 segments (~14 kB) and doubles every RTT (Congestion Control: Protecting the Network), so a 1 MB response over a fresh connection needs about seven RTTs of ramp-up regardless of bandwidth — 700 ms at 100 ms RTT, 7 ms at 1 ms. Bandwidth vs Latency works the arithmetic.

The same cold HTTPS GET at two distances (simulated; TLS 1.3, DNS cached)
                    same region (1 ms RTT)     cross continent (150 ms RTT)
TCP handshake                 1 ms                     150 ms
TLS 1.3 handshake             1 ms                     150 ms
request → first byte          1 ms + server            150 ms + server
                            ─────────                 ───────────
before first byte            ~3 ms + server            ~450 ms + server
warm (pooled) request        ~1 ms + server            ~150 ms + server

N+1 across regions: the classic disaster

The N+1 pattern — one query for a list, then one query per item — costs N+1 round trips. Against a database in the same rack at 0.2 ms, 40 items is 8 ms and nobody notices. Move the database to another region at 100 ms and the identical code takes 4.1 s. The ORM did not change; the SQL did not change; the round-trip count was always 41, and each one is now 500× more expensive. The Database domain treats this as a query-shape bug; from here it is a latency-multiplier bug, and the fix is the same: fewer round trips — one query with a join or an IN list, a batch API, a pipeline that sends several commands without waiting.

The same shape hides in microservice chains (service A calls B calls C, each in turn), in sequential API calls from a browser, in a Redis client that does not pipeline, and in any loop that awaits a remote call per iteration. Concurrency helps only when the calls are independent: 40 parallel calls cost ~1 RTT of wall-clock time plus queueing, 40 sequential ones cost 40. The rule that survives every environment is: count the sequential round trips in the critical path, multiply by the RTT of the farthest hop. That number is your floor, and it is usually the bill.

Same data, 41 round trips vs 1 — at 100 ms RTT that is 4.1 s vs 0.1 s
1// N+1: one list query, then one query per row — 41 sequential round trips
2const orders = await db.query('SELECT id, user_id FROM orders WHERE day = $1', [day]);
3for (const o of orders) {
4 o.user = await db.query('SELECT * FROM users WHERE id = $1', [o.user_id]); // 1 RTT each
5}
6
7// one round trip: let the database do the join
8const rows = await db.query(
9 'SELECT o.id, u.* FROM orders o JOIN users u ON u.id = o.user_id WHERE o.day = $1',
10 [day],
11);
12
13// independent calls: parallel costs ~1 RTT, not N
14const [profile, cart, recs] = await Promise.all([getProfile(id), getCart(id), getRecs(id)]);

Key points

  • RTT spans ~20 µs (loopback) to ~250 ms (cross continent); the simulator’s values are illustrative — measure yours.
  • Light in fibre is ~200,000 km/s: ~10 µs per km round trip; a cross-ocean RTT is a physical floor.
  • Every request costs ≥ 1 RTT; a cold HTTPS request costs 3–4; a large response adds slow-start round trips.
  • Connection reuse (keep-alive, pooling) matters more the farther the peer.
  • N+1 and sequential call chains multiply the RTT; the fix is fewer sequential round trips, not faster servers.
  • Count sequential round trips on the critical path × RTT of the farthest hop: that is the floor.

Why does this exist?

Mechanisms are answers to constraints. Open each question before reading the answer.

▸Why can this not be fixed with more bandwidth?

Bandwidth is how many bytes fit in a second; latency is how long the first byte takes to arrive. A request that waits for an answer is bounded by the trip, and a wider pipe does not shorten the trip. See Bandwidth vs Latency.

▸Why do cold requests cost several RTTs?

TCP and TLS each need an exchange before any application byte can be sent; each exchange is a full trip. Warm connections have already paid for them.

▸Why is geographic distance a distributed-systems concern and not just a web one?

Every consensus round, every synchronous replication acknowledgement, every cross-region lock is a round trip too. A replica 100 ms away cannot acknowledge in less than 100 ms; the same floor bounds replication lag, commit latency and failover.

Latency by distance

Latency: where is the other machine?
Server time is held at zero so only the network shows. The pattern of requests matters more than any single one.
Peer location (illustrative RTT)
Request pattern
Simulated
Timeline
#160 ms
#260 ms
#360 ms
#460 ms
#560 ms
#660 ms
#760 ms
#860 ms
#960 ms
#1060 ms
RTT
60 ms · ~4,000 km of fibre plus a dozen routers
Arithmetic
10 × 60 ms = 600 ms
Total
600 ms
The N+1 pattern — one query per row, each waiting for the previous — pays the RTT ten times. Same code on loopback: 500 µs; cross-continent: 1.50 s. Nothing in the code changed, only where the database lives.
Physical floor: light in fibre
One way (min)
28 ms
RTT (min)
55 ms
speed of light in glass ≈ 200,000 km/s
5,500 km ÷ 200,000 km/s = 27.50 ms one way
× 2 = 55.0 ms round trip — before any router, queue or retransmission
Real paths are 20–50% longer than the great circle (cables follow coasts, routers add serialization and queuing), so measured RTTs run ~1.3–1.5× the floor: New York ↔ London ≈ 5,500 km → floor 55 ms, typical 70–80 ms. No amount of bandwidth or CPU changes this number; only moving the data closer does.

How it fails

What the failure looks like from inside real software.
Reference · show
  • Endpoint goes from 10 ms to 4 s after "moving the database to the managed service in another region": N+1 queries, each now paying a cross-region RTT.
  • p50 fine, p99 terrible from one geography: users far from the origin pay cold-connection RTTs; no CDN or regional endpoint; connection pooling absent on their path.
  • Microservice chain of six sequential calls at 2 ms each is fine in one region and 600 ms when one service is deployed elsewhere: the chain multiplies the slow hop.
  • Redis in another AZ "is slow": each command is a round trip; the client is not pipelining; 1–2 ms × thousands of commands.
  • Synchronous replication to a cross-region standby makes every commit take ≥ 1 RTT: not a tuning problem, a distance one.

Check yourself

Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.

  1. Requests to your API take 3 seconds at p99, but the server sits at 5% CPU and the handler itself measures 20 ms. Where can the other 2.98 seconds be, and how would you find them?

    Show a strong answer

    The handler’s 20 ms is measured from the moment the framework calls it — a request has a long life before and after that point, and none of it burns CPU. Lay out the timeline (Where the Time Goes: The Request Timeline): client DNS lookup → TCP handshake → TLS handshake → request bytes cross the network → the kernel’s accept queue → the application’s own queue (thread pool, event loop) → the handler → response bytes written to the socket buffer → transferred to the client → parsed. "Idle CPU plus slow requests" means the request is *waiting*, and each stage has a characteristic wait.

    Exact values are fingerprints. A p99 of ~1 s or ~3 s is the signature of a lost SYN: Linux retransmits at 1 s, then 3 s, then 7 s, so a handshake whose first SYN was dropped — by a full accept queue, a conntrack table at capacity, or a firewall — completes at exactly 1 or 3 s (The Three-Way Handshake, TCP Debugging: Reading the Handshake on the Wire). Check nstat -az TcpExtListenOverflows TcpExtListenDrops and ss -ltn for Recv-Q at the backlog limit. Steps of ~200 ms or multiples are retransmission timeouts on established connections (RTO_MIN, Packet Loss: Duplicate ACKs, Fast Retransmit and the RTO); ~40 ms per small write is the Nagle + delayed-ACK interaction; exactly 5 s is the glibc DNS resolver timeout — the first nameserver in resolv.conf is dead or drops UDP, or an AAAA lookup goes unanswered; 1–3 RTTs of extra latency on *every* request means no keep-alive, so each request re-runs the TCP and TLS handshakes (Keep-Alive and Connection Reuse).

    Queueing without CPU is the other big family. A thread pool of 32 workers all blocked on a downstream call with a 3 s timeout serves 20 ms handlers with a 3 s wait — the thread-pool queue length, not CPU, is the saturated resource (The Thread Pool Server). An event loop stalled on a synchronous call queues everything behind it. A slow client or a small socket buffer makes write() fast (it copies into the kernel) but the *transfer* slow, so server-side timing ends before the client has received anything; the LB then reports a long response time the app never saw (What Happens When the Receiver Is Slow). And on the client side, browsers queue requests beyond six per host — DevTools shows that as "Stalled" — and a proxy in between may buffer.

    Find it by measuring each hop, not the handler. From a client: curl -w "%{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer} %{time_total}" splits DNS, TCP, TLS and time-to-first-byte. At the balancer: ALB request_processing_time/target_processing_time/response_processing_time, or nginx $request_time versus $upstream_connect_time, $upstream_header_time, $upstream_response_time — the gap between request_time and upstream_response_time is client or network. On the server: ss -ti for retrans, rto and cwnd per connection, thread-pool and event-loop lag metrics, and a distributed-tracing span opened at the *ingress* rather than in the handler. Compare p50 to p99: a flat p50 with a spiky p99 at round values is a timer; a smeared p99 is a queue.

    Full interview question, with follow-ups and red flags →
  2. What does HTTP keep-alive do, what does it cost, and what goes wrong when a client and a server disagree about how long a connection stays open?

    Show a strong answer

    Without reuse every request pays a TCP handshake (1 RTT), a TLS handshake (1–2 RTT) and a fresh slow start in which the first response is throttled to ~14 kB per RTT. With persistent connections — the HTTP/1.1 default, Connection: keep-alive in 1.0 — the second request pays none of that: the socket is open, the keys exist, and the congestion window is already grown. On a 100 ms path that is 200–300 ms saved per request; for an API client making thousands of calls it is the difference between a busy pool of 20 connections and a stream of TIME_WAIT sockets and port exhaustion (Keep-Alive and Connection Reuse, Connection Pooling).

    The cost is state that outlives the request. Each idle connection holds a file descriptor, a kernel socket with its buffers, and on a TLS server tens of kilobytes of session state; a server holding 50 000 idle keep-alive connections must be sized for it (fd limits, memory) and its event loop or worker model must not tie a thread to an idle socket (The Event-Driven Server). So both ends impose an idle timeout: nginx defaults to 75 s toward clients, Node’s http.Server.keepAliveTimeout to 5 s, AWS ALB to 60 s, Go’s http.Server.IdleTimeout to whatever you set. HTTP/1.1’s Keep-Alive: timeout=5, max=100 header is only a hint.

    The race is the classic failure. The server decides an idle connection is dead at exactly the moment the client picks it from the pool and writes a request. The client’s bytes meet a closed socket: it gets ECONNRESET, EPIPE, "socket hang up" (Node) or "Connection reset by peer" for a request that was never processed — or, worse, was fully written and *may* have been processed before the close raced. A proxy between them turns the same event into a 502. The rule that avoids it: the client’s idle timeout must be shorter than the server’s, at every hop. The textbook incident is Node behind an ALB: ALB idle 60 s, Node default 5 s → intermittent 502s until Node is set to keepAliveTimeout = 65 000 (and headersTimeout above it).

    This is unrelated to TCP keepalive (SO_KEEPALIVE): kernel probes on an idle connection, by default only after 2 hours (tcp_keepalive_time=7200), whose purpose is to detect a dead peer and to keep NAT and firewall entries from expiring. It does nothing for HTTP request semantics, and its default timing is far too long to matter for the race above.

    Full interview question, with follow-ups and red flags →
  3. The p99 is exactly 1.02 s and p99.9 exactly 3.02 s. What is the 20 ms?

    Show a strong answer

    The handler. The 1 s and 3 s are SYN retransmit timers; the handshake is being dropped, most likely accept-queue overflow or conntrack.

    Full interview question, with follow-ups and red flags →