Pidoku

Networking Fundamentals

Module 9 Lesson 9.a 1h Difficulty 2/5

Prerequisites 3.e


Before you start: words you need#

WordPlain meaning
LatencyHow long one message takes to arrive, however small. Measured in µs or ms.
BandwidthHow many bytes per second a link can carry once data is flowing.
RTT (round-trip time)Latency there and back: send a message, get the reply.
Gb/s vs GB/sNetworks are quoted in gigabits per second, memory in gigabytes. Divide bits by 8: a 400 Gb/s link is 50 GB/s.
TCP / TLSTCP is the protocol that gives a reliable byte stream over the internet; TLS encrypts it. Each needs a handshake (one or more round trips) before data flows.
Proxy / middleboxAnything between client and server that handles the traffic: load balancer, CDN, firewall, service-mesh sidecar, API gateway.
File descriptorThe operating system’s handle for an open file or network connection. Each open connection uses one (3.i).
TTFTTime to first token: how long a user waits before the answer starts (2.c).

1. What is it?#

The network appears in inference in three roles, with very different requirements:

1. Client ↔ service        HTTP with streaming; ~10–200 ms RTT; small payloads
2. Service ↔ service       gateway → router → engine; ~0.1–1 ms; moderate payloads
3. GPU ↔ GPU               NVLink inside a rack; RDMA over InfiniBand or Ethernet between racks;
                           ~1–10 µs; huge bandwidth

This lesson covers the general rules that apply to all three, and roles 1 and 2 in detail. Role 3 is the rest of Module 9: the host link (9.b), GPU links (9.c), the data-center fabric (9.d), moving KV caches (9.e), collectives (9.f), their cost (9.g) and multi-node serving (9.h).


2. Why does it matter?#

Because a streaming, long-lived, high-token-rate workload stresses networks in ways ordinary request/response services do not, and because the most common “the model is slow” complaint turns out to be a proxy buffering the stream.

One rule underlies everything in this module:

time to send a message = latency + size ÷ bandwidth

Small messages are dominated by latency; large ones by bandwidth. Knowing which regime you are in tells you what to fix.


3. Simple analogy#

A phone call versus a letter. Ordinary HTTP is a letter: you write it, send it, get a reply. Streaming inference is a phone call: the connection stays open for minutes, information flows continuously, and anything in the middle that “helpfully” waits to hear the whole sentence before passing it on ruins the experience.

Most middleboxes were built for letters.

For latency against bandwidth, think of a motorway: latency is how long the drive takes; bandwidth is how many lanes there are. Adding lanes does not get one car there sooner.


4. Tiny example: the buffering proxy#

Engine:  emits a token every 20 ms, starting at t = 200 ms
Client:  should see the first token at ~t = 210 ms

With nginx's default proxy_buffering on:
  nginx collects the response until its buffer fills or the response ends.
  The client sees NOTHING until t = 4,000 ms, then the whole answer at once.

TTFT measured at the server:   200 ms    dashboards green
TTFT experienced by the user: 4,000 ms   users furious

The fix for nginx:

nginx
location /v1/ {
    proxy_pass http://engine;
    proxy_buffering off;            # the critical line
    proxy_cache off;
    proxy_read_timeout 3600s;       # long generations
    proxy_set_header Connection '';
    proxy_http_version 1.1;
    chunked_transfer_encoding on;
}

Always measure TTFT from a real client through the real ingress path. Server-side metrics cannot see this class of bug, and it is extremely common. The stream format itself (Server-Sent Events) and the full list of layers that can break it are in 12.p.


5. Technical explanation#

Latency: physics first#

Same rack                         0.05–0.2 ms
Same data center / zone           0.2–1 ms
Across zones in a region          0.5–2 ms
Across regions, same continent    10–40 ms
Across continents                 80–250 ms
TCP handshake                     1 RTT
TLS 1.3 handshake                 1 RTT (0 RTT on resumption)
DNS lookup, uncached              10–100 ms

Light in fibre covers about 200 km per millisecond. For a 300 ms TTFT budget, a client on another continent spends 150 ms or more of it on physics before the model starts. This is the case for multi-region inference (23.f): you cannot optimise your way past the speed of light.

Bandwidth: rarely the issue for tokens#

Token stream:  ~4 bytes of text per token + ~80–100 bytes of SSE/JSON framing
5,000 tokens/s × ~100 bytes = 0.5 MB/s

Trivial. But:

  • Long prompts. A 100k-token prompt is about 400 KB of text. At 100 requests per second that is 40 MB/s inbound, plus JSON parsing on the CPU.
  • Multimodal. Images, audio and video are megabytes per request and can saturate links.
  • KV caches in disaggregated serving: gigabytes per request (9.e).

Protocols#

Public LLM APIs stream with SSE over HTTP (12.p); internal hops often use gRPC over HTTP/2, which multiplexes many streams over one connection. Lesson 20.b compares them; for this lesson what matters is that every protocol rides on TCP connections that stay open for the whole generation.

Connection management#

Streaming responses hold a connection for the entire generation:

1,000 concurrent users × 30 s average generation
= 1,000 connections open at once, each held for 30 s

Consequences:

  • File descriptor limits (ulimit -n) must be raised; 1,024 is a common and fatal default.
  • Load balancers with per-backend connection limits need tuning, and should balance on active requests, not connection counts (20.f).
  • Idle timeouts must exceed your longest generation, or connections die mid-stream.
  • Ephemeral ports between gateway and engines run out at high connection churn. Use connection pooling and keep-alive.

TCP details that bite#

  • Nagle’s algorithm holds back small writes to batch them, which can add up to about 40 ms when combined with delayed acknowledgements. Set TCP_NODELAY on streaming sockets. Most frameworks do; verify.
  • Slow start. A new TCP connection begins with a small window and ramps up. Large uploads on fresh connections are slower than the link allows; reused connections avoid it.
  • Compression buffers. gzip collects data before emitting it. Disable it for text/event-stream.

6. Under the hood#

The program applies latency + size ÷ bandwidth (one-way latency is half the RTT) to the payloads inference actually sends, over three paths. It ignores TCP slow start and protocol overhead.

Go
// netbasics.go — time = latency + size ÷ bandwidth, for the payloads inference sends.
package main

import "fmt"

type path struct {
	name    string
	rttMs   float64 // round-trip time
	gbitsPS float64 // usable bandwidth, gigabits per second
}

type payload struct {
	name  string
	bytes float64
}

func main() {
	paths := []path{
		{"same rack, 100 Gb/s", 0.1, 100},
		{"same region, 25 Gb/s", 1, 25},
		{"cross-continent, 1 Gb/s", 150, 1},
	}
	payloads := []payload{
		{"one streamed token (SSE)", 100},
		{"8k-token prompt (JSON)", 40e3},
		{"4 MB image", 4e6},
		{"8k-token KV cache (2.6 GB)", 2.6e9},
	}
	fmt.Printf("%-28s", "payload")
	for _, p := range paths {
		fmt.Printf(" %24s", p.name)
	}
	fmt.Println()
	for _, l := range payloads {
		fmt.Printf("%-28s", l.name)
		for _, p := range paths {
			oneWay := p.rttMs / 2
			wire := l.bytes * 8 / (p.gbitsPS * 1e9) * 1000 // ms
			share := 100 * oneWay / (oneWay + wire)
			fmt.Printf("   %10.2f ms (%3.0f%% lat)", oneWay+wire, share)
		}
		fmt.Println()
	}
}

Output:

payload                           same rack, 100 Gb/s     same region, 25 Gb/s  cross-continent, 1 Gb/s
one streamed token (SSE)             0.05 ms (100% lat)         0.50 ms (100% lat)        75.00 ms (100% lat)
8k-token prompt (JSON)               0.05 ms ( 94% lat)         0.51 ms ( 98% lat)        75.32 ms (100% lat)
4 MB image                           0.37 ms ( 14% lat)         1.78 ms ( 28% lat)       107.00 ms ( 70% lat)
8k-token KV cache (2.6 GB)         208.05 ms (  0% lat)       832.50 ms (  0% lat)     20875.00 ms (  0% lat)

How to read it:

  • Tokens and prompts are pure latency. Even an 8k-token prompt is mostly latency on every path. A faster link changes nothing; a closer server changes everything.
  • Images sit in the middle. On a slow link the bandwidth term starts to matter.
  • KV caches are pure bandwidth. Latency is irrelevant; only a much faster link (RDMA at 400–800 Gb/s, 9.c) makes moving them practical.

Commands for finding where time goes on a real system:

Shell
# Connection states: look for TIME_WAIT build-up and listen-queue drops
ss -s
ss -tan state established | wc -l

# Retransmissions and drops
nstat -az | grep -iE 'retrans|drop|overflow'

# Per-connection RTT, congestion window and retransmits
ss -tin | head -20

# Client-side timing breakdown for one request, streaming (-N)
curl -N -o /dev/null -s -w 'dns %{time_namelookup}  tcp %{time_connect}  tls %{time_appconnect}  first-byte %{time_starttransfer}  total %{time_total}\n' \
  -H 'Content-Type: application/json' -d @request.json https://your-endpoint/v1/chat/completions

time_starttransfer from curl is a client-measured TTFT including every network and proxy effect. Compare it with the server’s TTFT metric; the difference is your ingress tax.


7. Performance implications#

  • TTFT is the metric the network can ruin. Inter-token latency is usually safe because tokens are small and frequent, but one buffering middlebox turns a streaming API into a batch one.
  • Handshakes matter for short calls. Agents that make many short requests save tens of milliseconds per call by reusing connections.
  • Distance dominates for far-away users. Regional placement beats any server-side optimisation for them.
  • Large payloads need bandwidth, small ones need proximity. Do the arithmetic before buying either.

8. Production implications#

  • Disable buffering at every layer: CDN, WAF, ingress controller, service-mesh sidecar, application framework. Each is a separate place the bug hides (12.p).
  • Use two kinds of timeout: a generous total read timeout (longer than the longest generation) and a short stall timeout (no token for 30 s means something is wrong; end it) (20.e).
  • Raise fd limits and tune the listen backlog.
  • Terminate TLS at the edge, reuse connections internally.
  • Place inference close to users where TTFT matters.
  • Keep health checks cheap. A probe that runs a real generation every few seconds wastes GPU capacity (20.b).

9. Common mistakes#

  1. Not testing through the real ingress. The most common streaming bug.
  2. An idle timeout shorter than the generation. Connections dropped at exactly 60 seconds is the classic signature.
  3. The default ulimit -n of 1,024. Fails at about 1,000 concurrent streams.
  4. No keep-alive between gateway and engine. A handshake per request adds latency and burns ephemeral ports.
  5. Compressing the SSE stream. gzip buffers by design and defeats streaming.
  6. Confusing Gb/s with GB/s. An 8x error in every estimate.
  7. Buying bandwidth for a latency problem. A token stream will not go faster on a bigger pipe.

10. Hands-on exercise#

  1. Run netbasics.go. Add a “same region, 400 Gb/s RDMA” path with 0.01 ms RTT. Which payloads change, and which do not?
  2. Reproduce the buffering bug. Put nginx in front of a streaming endpoint with default settings. Measure client TTFT with the curl command above. Then set proxy_buffering off and measure again.
  3. Map your latency budget. From your own location, measure DNS, TCP, TLS and first byte to an endpoint you use. What fraction of TTFT is network?
  4. Find the connection limit. Write a client that opens N concurrent streaming requests. Increase N until something breaks. What broke: file descriptors, backlog, memory, the load balancer? Fix it and repeat.

11. Interview questions#

  1. Why does a buffering proxy destroy an LLM API, and how would you detect it?
  2. Users report the response arrives all at once after 5 seconds, but server TTFT is 200 ms. Diagnose.
  3. When is a transfer latency-bound and when is it bandwidth-bound? Give an inference example of each.
  4. How do long-lived streaming connections change load balancer configuration?
  5. What is a sensible timeout policy for an LLM API? Name at least two different timeouts.
  6. Why can no amount of server optimisation fix TTFT for a user on another continent?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in