Topic: protocols

Reading: 34 min, plus 7 in closed details. How the bytes of one LLM request travel and who is allowed to send them: a map of DNS, TCP and QUIC, TLS and SSH, HTTP, streaming, service APIs, auth and the agent protocols (MCP, A2A), with the running request recorded on the wire and broken on purpose. Data as of October 2026.

The idea

A protocol is an agreement about bytes, and one LLM request crosses about eight of them, stacked so that each solves one problem, costs round trips or guarantees, and fails in its own recognisable way.

One running example. A user types "What colour is the sky?" and the app sends one streaming request to an LLM API: a POST /v1/messages with a 117-byte JSON body, answered by five tokens streamed back one by one. To record every byte, the request goes to a local stand-in for an LLM API that answers in the event format of Anthropic's Messages API, trimmed (the On the wire tab built it, 5 October 2026, Apple M1 Pro, Python 3.13.16 with OpenSSL 3.5.9, curl 8.7.1). Fig. 1 stacks its journey as glass plates, top to bottom in the order the request meets them; each plate names the page that owns it. The request (orange dots) goes down, the answer (green) comes back up.

Fig. 1 · One request's journey: every step is a different protocol, and each has its own page

  1. Find the server: DNS turns api.anthropic.com into 160.79.104.10. Free when cached (2.4 ms inside curl), one round trip to a resolver when not (212 to 451 ms for an uncached name, measured in the On the wire tab). Caching is DNS's whole failure surface: a "does not exist" answer is cached too, and nothing can push a change. Owner: DNS: resolution, caching and the failure modes.
  2. Open a connection: TCP opens a reliable, ordered byte stream with SYN, SYN-ACK, ACK: one round trip before the request can leave. IP underneath only does best effort; every guarantee is added above it. A silent drop (a firewall), a reset (nothing listening) and a connection a NAT forgot while idle are the three ways this step fails. Owner: Networking foundations: IP, TCP, UDP and QUIC.
  3. Make it private: TLS 1.3 proves the server is who it claims and encrypts everything after. One more round trip and about 3.5 KB of handshake on this request (measured); the client offered a hybrid post-quantum key share and the server took it. A certificate the client cannot verify stops the request here. Owner: TLS and certificates: the handshake, PKI, mTLS and post-quantum.
  4. Ask: HTTP carries the meaning: method, path, headers, status code. Over HTTP/1.1 the request is 277 bytes of text, one TLS record of 299 bytes on the wire; over HTTP/2 the same request is a compressed HEADERS frame and a DATA frame on stream 1. Every proxy on the path has its own timeouts, and the smallest one wins. Owner: HTTP: semantics, 1.1 vs 2 vs 3, proxies and timeouts for LLM APIs.
  5. Prove who is calling: the API decides whether this caller may do this. The request carries x-api-key; a 401 means the credential did not prove who you are, a 403 that it did and you are not allowed. Users and agents get scoped, short-lived OAuth tokens instead of keys. Owner: Auth: API keys, OAuth 2.1, OIDC, JWTs, mTLS and agent-era auth.
  6. Route inside the provider: behind the front door the API calls its own services (rate limiting, a router, the inference servers), typically over gRPC with a deadline on every call, so that all of them give up together when the user leaves. A balancer that pins long-lived HTTP/2 connections sends one client's traffic to one replica. Owner: Service APIs: REST, gRPC, GraphQL and load balancing.
  7. Stream the answer: it comes back as Server-Sent Events inside one HTTP response that does not end until the last token: status 200 first, then one event per token. On the wire each token was one TLS record of 146 to 148 bytes, about 51 ms apart. An error after the 200 can only arrive as an event, and a buffering proxy turns the stream into one burst. Owner: Streaming and real-time: SSE, WebSockets, webhooks, long polling.
  8. Use a tool or another agent: if the model asks for a tool, the host calls an MCP server (a JSON-RPC tools/call); to hand a whole task to someone else's agent it opens an A2A task. Either way the result comes back as text the model reads (purple dots), so a tool's output is untrusted input. Owners: MCP: building servers and clients, transports, auth and security and Agent-to-agent and beyond: A2A, agent commerce, agents driving devices.
  9. The whole path. Before the first token can arrive, the client pays for a name lookup (cached, or one round trip to a resolver), a TCP connection (one round trip), a TLS 1.3 handshake (one round trip) and the request itself (one round trip): about four round trips before the server even starts, which is why clients reuse connections and why HTTP/3 merges the TCP and TLS round trips (section 2).

Numbers measured on this page's running request (On the wire tab and src/read/code/); the IP address of api.anthropic.com was read through this machine's resolver on 5 October 2026. The round-trip count on the figure assumes an uncached name. The plates are the order the request meets the protocols, not a layer model (section 1 has that). The engineer's own path to a GPU box is a ninth protocol, SSH (section 5).

The one idea to keep

Every protocol trades round trips (waiting for the other side) against guarantees (order, delivery, privacy, identity). Most "slow" or "stuck" bugs are a round trip or a guarantee you did not know you were paying for.

A problem shows in another layer

No layer reads the others' headers, so a problem is visible only to the layer that owns it: a bad certificate is invisible to TCP, and a TCP stall is invisible to your JSON parser, which just sees a read that never returns. Section 11 maps symptoms to layers.

Agents add one new risk

MCP made tools pluggable, and with them every tool's output became text the model reads as if it were instructions (section 10).

New terms (the Glossary at the end of this tab has the rest):

  • Round trip (RTT): the time for a message to reach the other side and a reply to come back. About 0.1 ms on one machine, 1 ms in a data centre, 80 to 150 ms across an ocean.
  • Handshake: messages exchanged before useful data can flow, to agree on parameters. Each costs at least one round trip.
  • Header and payload: the few bytes of addressing and control a layer puts in front of the data it carries, and that data.
  • Stream: an ordered sequence of bytes or messages inside a connection; HTTP/2 and QUIC carry many in one connection.
  • Head-of-line blocking: one slow or lost item holding up everything queued behind it.
  • Bearer credential: a secret that works for whoever presents it, like cash (API keys, most access tokens).

How this tab marks numbers: measured comes from this page's runs; derived numbers show their formula. Every exchange was run for this page on 5 October 2026 or is quoted from its specification.

Protocols in one screen

Step on the wireProtocolThe problem it solvesWhat it costsHow it usually failsOwner
Find the serverDNSTurns the name into an address a packet can be sent toOne round trip to a resolver when the answer is not cached; stale answers until a timer runs outMissing or negatively cached name; 5 s stalls from a lost queryDNS
Open a connectionIP, TCP (or UDP and QUIC)Delivers bytes to the right program on the right machine, complete and in order, without flooding the networkOne round trip before any data; one lost packet stalls everything behind it; speed capped by window over round-trip timeRefused, hangs, or silently dead after an idle timeoutNetworking foundations
Make it privateTLS 1.3Proves the server is who it claims and hides the bytes from everyone in betweenOne more round trip and about 3.5 KB of handshake on this request (measured)A certificate the client cannot verify (expired, missing intermediate, wrong name)TLS and certificates
AskHTTP/1.1, 2 or 3A shared vocabulary for requests and answers: methods, status codes, headersHeader bytes on every request; every proxy on the path has its own timeoutsThe smallest timeout on the path; 502, 503, 504 from a hop in frontHTTP
Stream the answerServer-Sent EventsSends tokens as they are generated, inside one long HTTP responseA connection held open for the whole generationBuffering proxies; a stream cut with no final eventStreaming and real-time
Prove who is callingAPI keys, OAuth 2.1, JWTs, mTLSLets the API decide whether this caller may do thisSecrets to store, rotate and never leak401 (who are you?) against 403 (not allowed); a token for the wrong audienceAuth
Call internal servicesREST, gRPCTyped, fast calls between the API's own services, with deadlinesSchemas and code generation; long-lived connections that load balancers handle badlyNo deadline set; all traffic on one replicaService APIs
Let the model use toolsMCP, A2AOne standard way for any agent to reach any tool or other agentEvery tool result is untrusted text entering the model's contextInstructions hidden in a tool result; tokens passed throughMCP, Agent-to-agent
Reach the GPU boxSSHAn encrypted, authenticated shell and tunnels to a machine you administerKeys or certificates to manage; one more hop through a jump hostA changed host key; an idle session cutSSH
GPUs talk to each otherRDMA, NCCLMoves gradients and activations between GPUs without the operating system in the pathA special, near-lossless network fabricA job that hangs at start-up on the wrong network interfaceNetworking foundations (section 14)

The tabs go further without repeating this one: On the wire records the running request byte by byte on HTTP/1.1, HTTP/2 and HTTP/3; Failure lab breaks it on purpose and shows the symptom each failure produces; Protocol atlas compares every protocol on one set of axes with its specification and dates.

1. The map: layers, and how to see each one

Each protocol solves one problem and assumes the others are solved. On the way out every layer wraps the message it was handed in its own header and passes it down; on arrival every layer strips its own header and passes the rest up.

Layer (internet model)JobIn our requestUnit and address
ApplicationWhat the bytes meanHTTP carrying JSON and Server-Sent Eventsa message; named by a URL
Security (between the two)Privacy, integrity, identityTLS 1.3a TLS record
TransportRight program, complete, in order, not too fastTCP (or QUIC over UDP for HTTP/3)a segment (TCP) or datagram (UDP); a port number picks the program
InternetGet across many networks to the right machineIPv4 or IPv6a packet; an IP address picks the machine
LinkMove bits over one cable or radio hopEthernet, Wi-Fia frame; a MAC address picks the next device

The four-layer internet model is the one the protocols were built on (RFC 1122, section 1.1.3). Interviews and load-balancer docs use the numbers of the older seven-layer OSI model instead: "L4" means the transport layer (TCP, UDP) and "L7" the application layer (HTTP), so an "L4 load balancer" forwards connections without reading HTTP and an "L7" one reads every request. TLS has no clean place in either model; it sits between transport and application.

Wrapping is two thirds of the request's bytes, and nearly all of a streamed token's

For the request, wrapping is 252 of the 369 bytes on the cable (mostly HTTP headers); for a streamed token, 213 of 216. A few hundred bytes per token is nothing for any link; what streaming costs is a connection held open for the whole generation.

Where each size comes from

JSON, HTTP and TLS bytes measured on this page's run (the TLS record of the request is 299 bytes on the wire against 277 bytes of HTTP inside it: a 5-byte record header, 1 byte of inner content type and a 16-byte authentication tag, RFC 9846, section 5.2). TCP, IP and Ethernet sizes come from their specifications, because capturing packets needs administrator rights this build did not have: a TCP header is 20 bytes plus options (RFC 9293, section 3.1), here 12 bytes of the timestamps option that Linux and macOS send by default (RFC 7323, section 3); an IPv4 header is 20 bytes (RFC 791, section 3.1; IPv6 is 40); Ethernet adds a 14-byte header and a 4-byte checksum (IEEE 802.3).

Fig. 2 · The running request wrapped by each layer, to scale

The same 117-byte JSON body, handed down layer by layer and then unwrapped on arrival. Switch to one streamed token to see what the answer costs.

  1. The app hands over its data: 117 B. The 117-byte JSON body: model, max_tokens, stream: true, and the user message.
  2. + HTTP head (160 B). HTTP/1.1 adds the request line and headers (POST /v1/messages, Host, content-type, x-api-key, content-length): 160 bytes, more than the body.
  3. + TLS (22 B). TLS encrypts the 277 bytes into one record: a 5-byte record header in front, 1 byte of inner content type and a 16-byte authentication tag behind. 299 bytes, unreadable to anyone on the path.
  4. + TCP (32 B). TCP adds 20 bytes (source and destination port, sequence and acknowledgement numbers, window, flags, checksum) plus 12 bytes of timestamps option.
  5. + IP (20 B). IPv4 adds 20 bytes: source and destination address, time to live, the protocol number of TCP (6).
  6. + Ethernet (18 B). Ethernet adds a 14-byte header (the next device's hardware address) and a 4-byte checksum. This frame is what crosses the cable.
  7. One frame on the cable: 369 bytes. Every router on the path reads only the IP header; every switch only the Ethernet header. Nobody in between can read the HTTP or the JSON, because TLS encrypted them.
  8. The server unwraps. Each layer checks and removes its own header and passes the rest up; it never looks inside. TLS checks the authentication tag (any changed byte fails it) and decrypts: the HTTP is readable again, only here. The HTTP server parses the head and hands the body to the application, which now holds exactly the 117-byte JSON the app sent.

The toolbox: one command per layer

Each tool answers one question about one layer; learning which is most of network debugging. All of them were run against the local server for this page.

QuestionLayerCommandOwner page for the details
Does the name resolve, and for how long is it cached?DNSdig name, dig name SOADNS, section 12
Is the port reachable?TCPnc -vz host port: success means routing, firewalls and a listening program are all fineNetworking foundations, section 15
Which connections are open?Socketslsof -nP -iTCP on macOS, ss -tnp on Linux; ss -ti adds each connection's round-trip time, window and retransmission countNetworking foundations, section 15
Where do packets stop?IPtraceroute or mtr; tcpdump or Wireshark for the packets themselves (administrator rights)Networking foundations, section 15
Is TLS healthy?TLSopenssl s_client -connect host:443 -servername host: the chain, the version, the cipher, whether verification passedTLS and certificates, section 9
Where did the time go?Allcurl -w: a timer per phase (name lookup, TCP connect, TLS done, first byte, total)HTTP, section 12
What happened, in order?Allcurl -v: name resolution, TCP connect, the TLS handshake, the certificate check, ALPN, then the request (> lines) and response headers (< lines). The first thing to run on any HTTP problem.HTTP, section 12
The recorded outputs: nc, openssl s_client, curl -w, lsof and curl -v against the running request

nc -vz (TCP)


openssl s_client (TLS): the chain is two links, CN=api.llm.test issued by the throwaway Wire Lab Root CA that the client was told to trust (the depth=1 and depth=0 lines)


curl -w timing, seconds since the start


lsof -nP -iTCP: one streaming request in flight, the server's listening socket and the two ends of one connection, 127.0.0.1:49197 -> 127.0.0.1:9443: the client's ephemeral port 49197 talking to the server's port 9443 (the process owner is shown as dev)


curl -v, HTTP/1.1


2. Round trips: the cost every layer adds

Light in fibre covers about 200 km per millisecond, so distance sets a floor no protocol can beat (High Performance Browser Networking, chapter 1). Most LLM API calls are latency-bound, not bandwidth-bound, and the latency before the first token is mostly handshakes that each wait one round trip. Which handshakes you pay depends on choices made at three different layers: the HTTP version, the TLS version, and whether a connection is reused.

  • Reuse is the biggest lever. A connection pool (HTTP keep-alive) skips the TCP and TLS round trips on every later request; a client that opens a fresh connection per request pays them every time. The cost of reuse is an idle connection that a NAT or load balancer may silently forget (section 4).
  • TLS 1.3 halves TLS 1.2's cost because the client sends its key share in its very first message instead of waiting to be told which one to use. TLS 1.2 is now in feature freeze (RFC 9851).
  • HTTP/3 merges transport and encryption into one round trip because QUIC has TLS 1.3 built into its handshake (RFC 9001).
  • Resumption and 0-RTT: a resumed TLS session skips the certificate, and TLS 1.3 can even send data in the very first message, but that early data can be replayed by an attacker (RFC 9846, section 8), so it is only safe for requests that may run twice; a generation request or an agent's tool call is not one of them.

Bandwidth has a round-trip ceiling too. Once data flows, one connection carries at most one window of unacknowledged bytes per round trip: throughput ≤ window / RTT. That is why one checkpoint upload between regions uses a fraction of a fast link, and why every fix is parallel streams.

Go deeper. Windows, losses and per-flow caps: Networking foundations (sections 3, 5, 13). Resumption and the 0-RTT replay trap: TLS and certificates (section 3). Every phase timed, cold, resumed and reused: On the wire.

Round trips before the request can leave: the transport and TLS choices decide, and reuse removes them all

TCP handshakeTLS handshakeQUIC with TLS inside
TLS 1.2 over TCP
TCPTLS 1.2: 2
3 RTT
HTTP/1.1 or 2, TLS 1.3
TCPTLS 1.3
2 RTT
HTTP/3 (QUIC)
QUIC + TLS
1 RTT
Reused connection
0 RTT

Add one round trip for an uncached DNS answer before any of them, and one for the request itself after. measured on an emulated 50 ms path (On the wire tab, sections 5 and 6): a TLS 1.3 handshake took 53 ms against 107 ms for TLS 1.2, and the first byte came 108 ms after the start on a new connection against 54 ms on a reused one.

3. Names: DNS turns a name into an address

The Domain Name System (DNS) is a worldwide, distributed, cached lookup from names to records (RFC 1034, 1987). Your process asks a stub resolver (getaddrinfo in the C library), the stub asks one recursive resolver, and on a cache miss the resolver walks down from a root server through the .com servers to the zone's own authoritative servers. Each answer carries a TTL (time to live), the seconds a cache may keep it.

The one thing that crosses every other layer: caching is DNS's whole failure surface. There is no way to push a change or invalidate a cache; "propagation" is every cache's TTL running out. A "does not exist" answer is cached too, so a record created a minute after a failed lookup can stay invisible for as long as the zone says (30 minutes for anthropic.com, measured). DNS failures surface as connection errors in other layers: a 5-second stall on every new connection (a lost query and the C library's default retry timer), a pod flooding the cluster DNS (Kubernetes' ndots:5), a certificate error from a filter that answers DNS itself (section 5).

Where DNS meets agents. In DNS rebinding a name first resolves to the attacker's server, then to an internal address such as 127.0.0.1 or the cloud metadata address 169.254.169.254, so a check made on the first answer is bypassed by the second. Any service run on 0.0.0.0 without authentication (a notebook, a model server) is reachable this way from a browser on the same network, and the MCP specification names it among the attacks a client must guard against when it fetches URLs a server gave it.

Go deeper. DNS: resolution, caching and the failure modes: resolution step by step (section 2), caching (5), Kubernetes ndots (7), DNSSEC and the root key roll (9), rebinding (10), symptoms (12).

4. Transport: IP, TCP, UDP and QUIC

IP gives every machine an address (32 bits for IPv4, 128 for IPv6) and forwards a packet one hop at a time, best effort: packets may be lost, duplicated, delayed or reordered, and IP will not tell you (RFC 791, section 1.2). A port picks the program; protocol, source and destination address and port, the 5-tuple, name one connection. Every guarantee is added above IP, and the three transports add different ones:

TCP (RFC 9293)UDP (RFC 768)QUIC (RFC 9000)
GivesA reliable, ordered byte stream with flow and congestion controlIP plus ports and a checksum: an 8-byte header, nothing elseMany independent reliable streams, encrypted, in one connection
SetupOne round trip (SYN, SYN-ACK, ACK), then TLS on topNoneOne round trip including TLS 1.3
A lost packetStalls every byte behind it (head-of-line blocking)Is simply goneStalls only its own stream
RunsIn the kernelIn the kernel; the application adds any rulesIn user space, on UDP; more CPU per byte than kernel TCP, and blocked UDP on port 443 means every client needs a TCP fallback
CarriesHTTP/1.1, HTTP/2, gRPC, TLS, SSHDNS questions, voice, games, QUIC itselfHTTP/3

Two transport facts other layers keep running into. Head-of-line blocking is the thread through the HTTP versions (section 6). And a connection can die without either end knowing: a NAT or load balancer forgets a connection that was idle too long (350 seconds on an AWS NAT gateway), and TCP alone never notices a silent peer, so long-lived connections (streams, SSH sessions, connection pools, a training job's rendezvous) need keepalives or heartbeats shorter than the shortest idle timeout on the path.

Where the GPUs talk. Training traffic avoids this path for its data: GPU clusters use RDMA (the network card writes straight into the other machine's memory, no operating system in the path) over InfiniBand, RoCE or AWS's EFA, and NCCL picks NVLink, then RDMA, then plain TCP sockets. NCCL still bootstraps over ordinary TCP sockets, which is why a wrong network interface can hang a job at start-up even on an InfiniBand cluster.

Go deeper. Networking foundations: IP, TCP, UDP and QUIC: a connection's life (section 3), loss and head-of-line blocking (4), windows (5), NAT and idle timeouts (9), MTU hangs (10), QUIC (12), TCP in a GPU job (14). The collectives: Distributed Training and Cluster anatomy.

5. Security: TLS for every API, SSH for the GPU box

TLS (version 1.3, now RFC 9846, July 2026) gives three guarantees on top of a connection: confidentiality (nobody in between can read), integrity (any changed byte is detected) and authentication (the client knows it reached the real server). It is the "S" in HTTPS. In one round trip the two sides agree on a fresh secret in public (Diffie-Hellman key exchange, so stealing the server's key later does not unlock recorded traffic), the server sends its certificate and signs the handshake with the matching private key, and both send a keyed checksum of everything exchanged. The certificate chains up to a root in the client's trust store, through certificates signed by certificate authorities.

SSH, the protocol you use to reach a GPU box, solves the same problem with the same ideas and one different choice: whom to trust.

TLS (every API call)SSH (a shell on a machine you administer)
Server identityA certificate signed by a CA the client already trustsA host key, trusted the first time it is seen (the known_hosts prompt), or an SSH certificate signed by your own CA
Client identityUsually none at this layer (an API key or token rides inside HTTP); mutual TLS when a workload must prove itselfAlways: a user key, an agent, or a user certificate
Key exchange in 2026Hybrid post-quantum by default with OpenSSL 3.5 or later (the running request used X25519MLKEM768)Hybrid post-quantum mlkem768x25519-sha256 by default since OpenSSH 10.0
What a warning meansA certificate error: never "fixed" by turning verification off"Host key changed": never clicked through
Never "fix" a certificate error by turning verification off

verify=False, curl -k and InsecureSkipVerify keep the encryption and drop the authentication, which means encrypting to whoever answers, attacker included. The fixes are serving the full chain on the server, or adding the right CA to the client's trust store.

What TLS still leaks, and why that matters for token streams. An eavesdropper still sees the server name and protocol in the ClientHello (unless Encrypted Client Hello is used), the sizes of all records and their timing. In the streamed answer that meant one record per token, 146 to 148 bytes each, about 51 ms apart (measured): the rhythm of generation is visible though the text is not, and researchers reconstructed 29% of assistant responses from token lengths alone (Weiss et al., 2024). The defence lives in the streaming layer: pad records or group tokens.

Certificates now expire on a schedule built for automation (200 days since 15 March 2026, 47 days from 15 March 2029), so an expired certificate is the most common TLS outage and automated issuance (ACME) is mandatory in practice. Mutual TLS runs the proof in the other direction and is the strongest way for one service to prove itself to another (section 9).

Go deeper. TLS and certificates: the handshake, PKI, mTLS and post-quantum: the handshake decrypted (section 2), chains (4), the 47-day schedule (5), mTLS (7), post-quantum (8), the classic failures (9). SSH: keys, certificates, jump hosts and tunnels for cluster work: host keys (section 3), SSH certificates against X.509 (4), ProxyJump and agent forwarding (5, 6), cluster workflows (13).

6. HTTP: one meaning, three wire formats

HTTP is the shared vocabulary for requests and answers, and the key to its versions is that the meaning and the wire format are specified separately. Methods, status codes and headers are defined once in RFC 9110 (HTTP Semantics) and mean the same in every version; HTTP/1.1, HTTP/2 and HTTP/3 only change how those messages are cut into bytes. Your code almost never notices the version; your latency and your proxies do. Each version exists to remove a form of head-of-line blocking:

HTTP/1.1 (1997, RFC 9112)HTTP/2 (2015, RFC 9113)HTTP/3 (2022, RFC 9114)
FormatText linesBinary frames, compressed headers (HPACK)Binary frames, compressed headers (QPACK)
Requests per connection at onceOne; clients open several connections (browsers about 6 per host)Many, as independent streamsMany, as independent QUIC streams
Head-of-line blockingA slow response blocks the connectionFixed between requests, but one lost TCP packet still stalls every streamGone: a loss stalls only its own stream
Handshakes before the requestTCP + TLS: 2 round tripsTCP + TLS: 2 round tripsQUIC with TLS inside: 1 round trip
Where you meet itMany APIs and most server-to-server codegRPC; browsers to CDNs and APIsBrowsers and mobile apps to CDNs

For one long streaming request on a clean network all three behave alike. They differ when packets are lost: measured on the running request, one dropped TCP packet delayed all three concurrent HTTP/2 streams (by 68, 56 and 43 ms), while over HTTP/3 only the stream that lost a packet was delayed (by 66 ms). HTTP's Fig. 4 replays these runs (On the wire, section 4, has the summary).

Three HTTP facts that decide what other layers must do.

  • LLM generation is a POST, and POST is not idempotent. A safe method (GET, HEAD) only reads; an idempotent one (GET, PUT, DELETE) has the same effect run once or twice, so a client may retry it after a network error (RFC 9110, section 9.2). If the connection drops after a POST left, the client cannot know whether the server is already generating (and billing); APIs answer with an idempotency key, a design owned by Service APIs (section 4).
  • The status code is sent before the first token. A stream that begins with 200 cannot report a later failure in its status, so errors after that point arrive as events inside the stream (Anthropic's API may send overloaded_error that way, streaming docs). 401 against 403 is auth's distinction (section 9); 502, 503 and 504 come from a proxy or gateway reporting on the hop behind it.
  • The effective timeout is the smallest one on the path. Between the app and the model server sit a client library, perhaps a corporate proxy, a CDN, a load balancer, an ingress and the API server, each with its own idle timeout (nginx gives up on a silent upstream after 60 s, nginx docs) and sometimes a total one. Streaming defeats only idle timeouts; a total timeout counts the whole response even while tokens flow (Envoy's route default 15 s, API Gateway 29 s).
Go deeper. HTTP: semantics, 1.1 vs 2 vs 3, proxies and timeouts for LLM APIs: HTTP/2 frame by frame (section 6), proxies (8), the timeout chain hop by hop (9), retries at the protocol level (10), debugging (12). Retries as a system: Reliability engineering.

7. Streaming: tokens as they are generated

A model generates tokens over seconds or minutes; waiting for the whole answer makes the app feel dead, and a long silence invites every proxy on the path to cut the connection. Server-Sent Events (SSE) answer with content-type: text/event-stream and keep one HTTP response open, writing small text events (event: and data: lines ending in a blank line, WHATWG HTML, section 9.2). Because it is plain HTTP it passes every proxy, which is why every major LLM API and MCP's HTTP transport use it. The choice among the four ways to deliver a result depends on direction and on how long the work takes:

MechanismDirectionUse it forWhat it costs
SSEServer to client, inside one HTTP responseToken streams, progress updates; MCP's HTTP transportOne direction only; text only; buffering proxies break it
WebSockets (RFC 6455)Both ways at any time, after an HTTP upgradeVoice agents and realtime APIs where the user can interruptNot HTTP after the first exchange: you write heartbeats, reconnection and resume yourself; long-lived connections complicate load balancing; browsers do not apply the same-origin policy, so the server checks Origin
WebhooksProvider to your server, later, as a separate signed POST"Your batch job finished": fine-tunes, batch inference, evaluationsA public endpoint, so verify signatures; delivery is at least once, so handle duplicates
Long pollingClient asks, server holds the request until there is newsA fallback where nothing else gets throughA full request per batch of events; awkward timeouts

Where streaming breaks, and which layer owns the fix. Tokens arriving in one burst at the end mean a proxy buffered the response (HTTP's proxies). A stream that dies after exactly 60 s while the model is thinking is an idle timeout on one hop; heartbeat comments every 15 s or so are the HTML standard's own advice. A stream that ends without its final event (message_stop) failed, even with no error: retry it with an idempotency key.

Go deeper. Streaming and real-time: SSE, WebSockets, webhooks, long polling: SSE byte by byte (section 2), what LLM APIs send (4), cut, resume and cancel (5), WebSockets (6 to 8), webhooks (9). Webhooks as an API you design: Service APIs (section 6).

8. Service APIs: REST, gRPC, GraphQL behind the front door

Behind POST /v1/messages the API calls its own services thousands of times a second, between programs written by different teams in different languages. The style decides who writes the schema, how calls are encoded, and how they fail:

StyleShapeRight forCost
REST (JSON over HTTP)Resources with URLs, standard methods and status codes, stateless server (Fielding, 2000)Public APIs, including every major LLM API's external face; anyone with curl can call itLoose contracts unless you publish a schema (OpenAPI)
gRPCServices in a .proto file, generated clients, binary protobuf over HTTP/2, four call modesInternal calls where you own both ends; high call rates, streaming, deadlinesCode generation; long-lived HTTP/2 connections that L4 balancers handle badly
GraphQLOne endpoint and a typed schema; the client names the fields it wantsMany front ends reading overlapping dataHard to cache; one query can fan out into many backend calls
JSON-RPC 2.0A JSON object with method, params and id, answered by result or errorThe smallest call format; MCP and A2A use itNo schema or transport of its own

Two ideas that only show across services. A deadline is the time after which the caller no longer wants an answer, passed on by every hop, so that when the user closes the tab the router and the inference server stop too; by default gRPC sets none, so a client can wait effectively forever (gRPC docs). And L4 against L7 balancing: an L4 balancer picks a backend per connection, an L7 one per request. A gRPC client keeps one long-lived HTTP/2 connection, so behind an L4 balancer all its calls land on one replica while the others idle (gRPC blog); LLM serving adds routers that send a conversation back to the replica holding its KV cache, which only an L7 router can do.

Go deeper. Service APIs: REST, gRPC, GraphQL and load balancing: REST done properly (section 2), idempotency keys (4), LLM provider APIs (7), one gRPC call on the wire (9), deadlines (10), load balancing (13). Building a service: Building a backend API; capacity: Capacity planning and performance.

9. Auth: who is calling, and may they do this?

TLS proved the server's identity to the client; the API now needs the reverse. Two questions, often confused: authentication (who are you?) and authorization (what may you do?). A 401 means the first failed, a 403 the second. The credentials differ in what they prove, whether a thief can use them, and how long they live:

CredentialWhat it provesStolen copy usable?LifetimeRight for
API key (the running request's x-api-key)"This is account X"Yes: a bearer credential, checked by valueUntil revokedYour backend calling a provider, from a secrets manager
OAuth 2.1 access token"This user let this client do these things at this API"Yes, but only at its audience, within its scopesMinutesApps, CLIs and agents acting for a user (authorization code with PKCE)
OIDC ID token"This person logged in"Should never be sent to an APIMinutesThe app learning who the user is
JWTA token format, not a grant: signed claims a server verifies offlineYes, until it expires: it cannot be revoked earlyKept shortAccess tokens checked without a call to the issuer
mTLS certificate"This workload holds this key"No: bound to a private keyHours (rotated by a mesh or SPIFFE)Service to service inside a mesh
Signed request (AWS SigV4)"Whoever holds the role's temporary key signed exactly this request"No reusable secret crosses the wireTemporary credentialsCloud APIs from a role
SSH key or certificate"This user holds this key"Only with the private keyKeys: until removed; certificates: hoursShells on GPU boxes (section 5)

The agent-era twist. An agent holds credentials and decides what to do with them from text it reads, some written by strangers (section 10). Auth cannot stop an agent being talked into misusing a credential it legitimately holds; it can decide how much each credential is worth when that happens. Three rules follow: least privilege (read-only scopes unless it must write, separate scopes for destructive actions); audience binding (a token issued for one tool server must not work anywhere else); no token passthrough (a server that receives a token never forwards it upstream; it obtains its own, by token exchange). For actions that cannot be undone, a human approval outside the conversation, which text arriving through a tool cannot fake.

Go deeper. Auth: API keys, OAuth 2.1, OIDC, JWTs, mTLS and agent-era auth: OAuth 2.1 with PKCE (section 4), JWT validation (6), bound tokens and mTLS (7), token exchange (8), agent-era auth (9). MCP's own authorization profile: MCP (section 7). Keeping credentials out of the model's context: Agent security.

10. Agent protocols: MCP, A2A, and the trust boundary

A model on its own only produces text. Before 2024 every app wired every tool by hand, so N apps and M tools meant N × M integrations; agent protocols make it N + M: a tool or an agent is written once against a standard and any host can use it. Both main protocols speak JSON-RPC 2.0 (section 8), over HTTP with SSE for streaming (sections 6 and 7) and OAuth for remote callers (section 9): they are a new layer on the old stack, not a new stack.

MCP (Model Context Protocol)A2A (Agent2Agent)Commerce and payments (UCP, ACP, AP2, x402)
ConnectsAn agent's host to tool servers it controlsAn agent to someone else's opaque agentA shopping agent to a merchant, and to a way to pay
Unit of workA tool call (tools/call), a resource read, a promptA task with states (submitted, working, input required, auth required, completed, failed, canceled, rejected) and artifactsA checkout session; a signed mandate or a per-request payment
DiscoveryThe host is configured with servers; the server lists its toolsAn Agent Card at /.well-known/agent-card.jsonA profile at /.well-known/ucp, negotiated by intersection
Transportsstdio for a local child process; Streamable HTTP remotelyJSON-RPC, gRPC and HTTP+JSON bindingsREST, MCP, A2A; x402 rides on an HTTP 402
Who plans the stepsYour model, one tool call at a timeThe other side's agent; you send the goal and get the outcomeThe merchant's rules; "a person must finish this" is a state

MCP's current revision is 2026-07-28, which made the protocol stateless; A2A 1.0.0 is from March 2026. Both are governed by the Agentic AI Foundation under the Linux Foundation. The other agent protocols, with their dates and status, are on Agent-to-agent and beyond (section 11), the one dated table of the topic.

The trust boundary: tool output is untrusted input. Whatever a tool returns enters the model's context next to the user's request, and the model cannot tell from the text alone which words came from the user and which from a stranger's web page. Instructions hidden in a tool result are indirect prompt injection, and no protocol can prevent it: it is what any tool that returns outside text does. It becomes data theft when private data, untrusted content and a way to send data out meet in one agent, which Simon Willison called the lethal trifecta (16 June 2025); remove any one leg and the attack has nowhere to go. When the tool moves money or a robot arm, an injected instruction is no longer a leak but an irreversible action, so limits must live below the model: in scopes, in device-level limits, in a human approval the conversation cannot fake.

One real tool call carrying a hidden instruction into the model's context (recorded, step by step)
User and model
Host
MCP client
MCP server

measured 2026-07-28: src/read/code/r6_mcp/, a one-tool server (fetch_page, returning a fixed page; nothing is fetched) and a client in the same Python process acting as host, 5 October 2026. No model is called: the model's decision to use the tool is shown as the step it would be, and the host's next request to the model is built by the script in the Messages API shape, exactly as a host would send it. 2025-11-25: the recording from TypeScript: LLM apps and agents, section 8, its src/tl/outputs/g3_mcp_http.json (a count_tokens tool over Streamable HTTP; session IDs replaced by a placeholder there).

One tool call through host, client and server, recorded byte for byte through a logging proxy. The page the tool returned contained a hidden instruction (an HTML comment telling "AI assistants" to call a read_file tool on ~/.aws/credentials), and the host put it, unchanged, into the model's context next to the user's request. Switch to the 2025-11-25 revision to replay the same kind of call with the older handshake and session: the before and after of the stateless redesign.

    Go deeper. MCP: building servers and clients, transports, auth and security: the transports (section 4), the stateless revision (5), authorization (7), threats (8), building a server and a client (9, 10). Agent-to-agent and beyond: A2A, agent commerce, agents driving devices: tasks and states (sections 3, 4), A2A against MCP on one job (10), the protocols dated (11), commerce and payments (12, 13), the trust boundary for irreversible actions (15). The hosts: Topic: agentic-harnesses.

    11. Debugging and choosing

    From symptom to layer

    Start from what you see, find the layer, run the one command that confirms it. The order is roughly the order of the request: a failure early in the path hides everything after it. The Failure lab reproduces 39 of these failures on the running request, and each child page has its own symptom table.

    What you seeLayer, likely causeFirst command
    Name or service not known, getaddrinfo failedDNS: typo, missing record, negative cache, wrong resolver inside a containerdig name; dig name SOA; compare dig @8.8.8.8 name
    Every new connection takes about 5 s extraDNS: a lost query and the resolver's 5 s retrycurl -w '%{time_namelookup}\n' -o /dev/null -s URL
    Connection refused immediatelyTCP: nothing listening, or wrong portnc -vz host port; on the server ss -ltn
    Connect hangs, then times outNetwork: firewall or security group drops packetsnc -vz -w 3 host port; mtr host
    Small calls work, big uploads hangIP: MTU blackholeping -M do -s 1472 host (Linux)
    Transfer far below link speedTCP: window or loss limited, one streamss -ti; iperf3 -P 1 against -P 8
    Idle connection fails on next use (connection reset)NAT or load-balancer idle timeoutCorrelate with idle time; enable keepalives below the timeout
    certificate verify failed, unable to get local issuer certificateTLS: missing intermediate, proxy re-signing, stale CA bundleopenssl s_client -connect host:443 -servername host -showcerts
    certificate has expired / not yet validTLS: renewal failed / client clock wrongopenssl x509 -noout -dates; date -u
    401 vs 403Auth: not authenticated vs not allowed (scope, audience, role)Decode the token's claims; check aud, exp, scope
    429Rate limitRead retry-after and rate-limit headers in curl -i
    502 / 503 / 504 from a proxyHTTP hop behind it: upstream crashed or closed / no healthy upstream / upstream too slowThe proxy's own logs; curl -v straight to the upstream, skipping the proxy
    Stream arrives in one burst at the endHTTP proxy bufferingcurl -N -v through and around the proxy; check X-Accel-Buffering
    Stream cut at a round number of secondsIdle or read timeout on one hopTime several failures; find the hop whose timeout matches
    gRPC traffic all lands on one replicaL4 load balancing of long-lived HTTP/2 connectionsPer-replica request counts; switch to L7 or client-side balancing
    Distributed training hangs at start-upNCCL picked the wrong network interface, or a firewall blocks its portsNCCL_DEBUG=INFO; set NCCL_SOCKET_IFNAME
    An agent did something nobody asked forAgent: instructions arrived inside a tool resultRead the transcript's tool results; check what tools and scopes the agent held

    Which protocol when

    You need toUseBecause
    Serve a public API to arbitrary clientsHTTPS + JSON (REST style), SSE for streamingEvery language and proxy understands it
    Stream tokens to a browser or appSSEPlain HTTP, one direction, survives proxies when configured
    Let the user interrupt (voice, realtime)WebSockets (or WebRTC for audio from a device)Both directions at any time
    Tell another system that a long job finishedWebhook (signed, idempotent consumer), or a queue inside your own systemsNo connection held open for hours
    Call internal services at high rategRPC with deadlinesTyped, compact, streaming, cancellation across hops
    Move a big checkpoint over a long pathMany parallel TCP streams (multipart upload)One stream is capped by window over RTT and per-flow limits
    Move tensors between GPUsNCCL over NVLink and RDMANo kernel, no copies, microsecond latency
    Give an agent toolsMCP (stdio locally, Streamable HTTP remotely)Write a tool once, any host can use it
    Delegate a task to someone else's agentA2ADiscovery, task lifecycle and streaming between opaque agents
    Authenticate users / services / your backend to a providerOIDC with PKCE / mTLS or cloud IAM / an API key in a secrets managerSection 9
    Reach a GPU boxSSH with keys (or certificates), through a jump hostEncrypted, authenticated, multiplexes forwarded ports

    12. The child pages

    Each child takes one row of the one-screen table to full depth, with its own recordings. Read them in this order if the topic is new; each also stands alone. Times are the ones each page's header states.

    Networking foundations: IP, TCP, UDP and QUIC
    Addresses and the path, a connection's life, loss, windows and congestion control, Nagle and streamed tokens, NAT and idle timeouts, MTU hangs, QUIC, moving checkpoints, TCP in a GPU job.Reading: 49 min, plus 17 in closed details.
    DNS: resolution, caching and the failure modes
    Delegation and resolution on a private DNS tree, records, caching with negative and stale answers, glibc and musl, Kubernetes ndots and headless Services, DNSSEC, encrypted DNS and rebinding.Reading: 45 min, plus 17 in closed details.
    TLS and certificates: the handshake, PKI, mTLS and post-quantum
    The TLS 1.3 handshake decrypted, resumption and 0-RTT, certificates and chains, ACME and lifetimes, revocation, mTLS and workload identity, post-quantum TLS, the classic failures.Reading: 45 min, plus 21 in closed details.
    HTTP: semantics, 1.1 vs 2 vs 3, proxies and timeouts for LLM APIs
    A message piece by piece, methods, status codes and caching, CORS and cookies, HTTP/1.1, HTTP/2 and HTTP/3 frame by frame, proxies, the timeout chain, retry safety.Reading: 45 min, plus 15 in closed details.
    Streaming and real-time: SSE, WebSockets, webhooks, long polling
    SSE byte by byte and what LLM APIs send, cut, resume and cancel, WebSocket frames and production, webhook delivery, WebRTC, gRPC streams and WebTransport.Reading: 38 min, plus 18 in closed details.
    Service APIs: REST, gRPC, GraphQL and load balancing
    REST done properly, OpenAPI, idempotency keys, rate limits, webhooks, LLM provider APIs as a design case, protobuf, one gRPC call on the wire, deadlines, load balancing, GraphQL, JSON-RPC.Reading: 52 min, plus 16 in closed details.
    Auth: API keys, OAuth 2.1, OIDC, JWTs, mTLS and agent-era auth
    401 against 403, API keys, sessions against tokens, OAuth 2.1 and OIDC, JWT validation, bound tokens, SigV4 and mTLS, token exchange, audience binding and no token passthrough for agents.Reading: 42 min, plus 10 in closed details.
    MCP: building servers and clients, transports, auth and security
    Roles, JSON-RPC messages, primitives, the two transports, the stateless revision, versions, MCP's authorization profile, protocol-level threats, building a server, a client and a host.Reading: 37 min, plus 14 in closed details.
    Agent-to-agent and beyond: A2A, agent commerce, agents driving devices
    The Agent Card, tasks and states, streaming and push, A2A against MCP, the agent protocols dated, UCP and ACP, AP2 and x402, the Model Hardware Standard, the trust boundary for irreversible actions.Reading: 39 min, plus 9 in closed details.
    SSH: keys, certificates, jump hosts and tunnels for cluster work
    One connection on the wire, keys and agents, host keys, SSH certificates, ProxyJump against agent forwarding, multiplexing, tunnels for notebooks, keepalives, moving files, cluster workflows.Reading: 42 min, plus 33 in closed details.
    Glossary: every term this tab and its children use, in a line each
    5-tuple: protocol, source and destination IP and port; names one connection.
    A2A: Agent2Agent, a protocol for delegating tasks between agents; discovery through an Agent Card.
    Authentication: proving who you are. Authorization: deciding what you may do.
    Bandwidth-delay product: link speed times round-trip time; the bytes that must be in flight to fill the link.
    Bearer credential: a secret that works for whoever presents it (API keys, most access tokens).
    Certificate authority: an organisation whose signature on a certificate clients trust.
    Certificate: a signed document binding a name to a public key.
    Congestion window: the sender's own limit on bytes in flight, its guess of what the network can carry.
    Datagram: one self-contained UDP message.
    Deadline: the time after which a caller no longer wants an answer; propagated through gRPC calls.
    Diffie-Hellman: two parties derive the same secret from exchanged public shares.
    DNS: the Domain Name System, which maps names to addresses and other records.
    Frame: the unit of a link layer (Ethernet); HTTP/2 and QUIC also call their units frames.
    Handshake: setup messages exchanged before data, each costing at least one round trip.
    Header: control information a layer puts in front of the payload it carries.
    Head-of-line blocking: one slow or lost item holding up everything queued behind it.
    HTTP: the request and response vocabulary of the web and of APIs; versions 1.1, 2 and 3.
    Indirect prompt injection: instructions hidden in content a model reads through a tool.
    IP address: the address of a machine's network interface (IPv4 32 bits, IPv6 128 bits); IP forwards packets to it.
    JSON-RPC 2.0: a request and response format of JSON objects with method, params and id; used by MCP and A2A.
    JWT: a signed token of base64url header, claims and signature, verifiable offline.
    Latency and bandwidth: time to the first byte, and bytes per second after that.
    MCP: Model Context Protocol, connecting hosts and their models to tool servers.
    Message: an application-level unit (an HTTP request, a JSON-RPC call).
    MTU: the largest packet a link carries (1,500 bytes on most Ethernet).
    NAT: a device that rewrites private addresses to public ones and tracks each connection.
    OAuth: delegated authorization: an app gets a scoped token to act for a user.
    Packet: the unit IP routes, with source and destination addresses.
    Port: a 16-bit number that picks the program on a machine.
    QUIC: an encrypted, multiplexed transport over UDP; carries HTTP/3.
    RDMA: remote direct memory access; network cards write into another machine's memory without the OS.
    Record: the unit TLS encrypts and authenticates.
    Receive window: how many bytes the receiver can buffer; the sender never exceeds it.
    Round trip (RTT): time for a message to reach the other side and a reply to come back.
    Segment: the unit of TCP.
    Server-Sent Events: a text event stream inside one long HTTP response.
    Stream: an ordered sequence of bytes or messages; HTTP/2 and QUIC carry many in one connection.
    TCP: the reliable, ordered byte stream over IP, with flow and congestion control.
    TLS: Transport Layer Security; confidentiality, integrity and server authentication over a connection.
    TTL: in DNS, the seconds a cache may keep an answer.
    UDP: IP plus ports and a checksum; no handshake, ordering or retransmission.

    Reading tab of Topic: protocols, written 5 October 2026 and rebuilt as a map on 24 October 2026. Recorded exchanges: src/read/code/ (run with run_all.sh); the earlier, longer Reading tab is kept in src/read/retired/parts/.