Part 6 · Real networks: infrastructure, security and operations

Network performance for programmers: latency, retries, throughput

lesson 18 / 1910 min1 labpublished updated
Course contents
On this page
  1. Numbers you should have a feel for
  2. What a new request costs
  3. The golden rules
  4. Timeouts, retries and backoff
  5. Throughput and buffers
  6. The server side: hidden limits

Most of the slowness users feel comes not from the CPU but from network round trips. This lesson covers what a programmer needs to know about network performance to build systems that are fast and resilient.

Numbers you should have a feel for

OperationApproximate time
Round trip inside one data center0.2 to 0.5 ms
Between two AZs in the same region1 to 2 ms
Between continents (for example, Europe to the US)70 to 150 ms
To the other side of the planet200 to 300 ms
Home Wi-Fi (first hop only)2 to 20 ms, with jitter
4G and 5G20 to 80 ms
GEO satelliteAbout 600 ms

What a new request costs

Take a request to a distant server with an RTT of 100 ms, and no existing connection:

StepRTTs
DNS (if not cached)1 or more
TCP handshake1
TLS 1.3 handshake1 (TLS 1.2: 2)
HTTP request and response1
TotalAbout 4 RTTs, or 400 ms, before a single byte gets processed

With HTTP/3, the TCP and TLS handshakes merge into one (one RTT less), and with 0-RTT on a repeat connection the request goes out in the very first message. With connection reuse, you pay all the handshake costs only once.

The golden rules

  1. Reuse connections: connection pools in your HTTP and database clients, keep-alive, and one shared client for the whole program (not one per request). A fresh connection pays for both the handshake and slow start.
  2. Cut the number of round trips: batch work, design coarser-grained APIs, avoid the N+1 pattern over the network, and run independent requests in parallel.
  3. Get close to the user: CDNs, the edge, a nearby region. No amount of code optimization makes up for the speed of light.
  4. Send less: compression (Brotli, gzip, zstd), compact formats, caching with Cache-Control and ETag, and pagination.
  5. Use HTTP/2 or HTTP/3: multiplexing and header compression. HTTP/1.1-era tricks (domain sharding, sprites) are no longer needed and can even hurt.
  6. Cache DNS, but respect the TTL.

Timeouts, retries and backoff

  • Always set timeouts: a connect timeout (short, say 1 to 3 seconds) and a read timeout (suited to the operation). An infinite timeout means threads and connections that get stuck forever.
  • Propagate deadlines down the chain of services (as gRPC does). If the user gave up after 2 seconds, the third service in the chain shouldn’t still be working on the request.
  • Retry only on transient errors (connection reset, 503, timeout), and only for idempotent operations or requests that carry an idempotency key.
  • Exponential backoff with jitter: each wait is double the previous one, plus a random amount. Without jitter, every client retries at the same moment and knocks a recovering server straight back down (the thundering herd).
  • Retry budgets and circuit breakers: when the error rate is high, stop retrying and fail fast, so the downstream system can breathe. Retries at several layers (client, gateway, mesh) multiply each other.
import random, time

def call_with_retry(fn, attempts=5, base=0.2, cap=5.0):
    for i in range(attempts):
        try:
            return fn()
        except (ConnectionError, TimeoutError):
            if i == attempts - 1:
                raise
            time.sleep(random.uniform(0, min(cap, base * 2 ** i)))   # "full jitter"

Throughput and buffers

  • Remember the BDP: on a high-RTT link, the throughput of a single TCP connection is at most Window ÷ RTT. A 64KB window over a 100 ms RTT means at most about 5 Mbps, even on a 10 Gbps link. Modern kernels grow buffers automatically, but old settings, proxies, and programs that manually shrink SO_RCVBUF break this.
  • Packet loss is expensive for TCP. By the Mathis approximation, throughput is proportional to MSS ÷ (RTT × √loss), so 1% loss on a high-RTT path drags throughput down to a few Mbps. BBR does much better than CUBIC under these conditions.
  • For large transfers, use several parallel connections or QUIC, and check the result with iperf3.

The server side: hidden limits

  • File descriptors: every socket is an FD, so raise ulimit -n on servers.
  • Ephemeral port exhaustion: a proxy or client that opens thousands of short connections to one destination (one IP and port) has only about 28,000 ports to use, and TIME_WAIT holds each one for 60 seconds. The fix: connection pooling, several source or destination IPs, and a larger ip_local_port_range.
  • The backlog and net.core.somaxconn, and accepting connections quickly in the event loop.
  • The conntrack table fills up on firewalls and Kubernetes nodes (nf_conntrack: table full, dropping packet); monitor its size.
  • Nagle and delayed ACK: for small request/response protocols, set TCP_NODELAY (see the TCP lesson).
  • Have Happy Eyeballs in your own clients (most modern libraries do) so that a broken IPv6 path doesn’t cause a 20-second delay.