Chapter 25: The AI Gateway
An LLM gateway is the one front door to every model server. Authentication, rate limits, usage policy, caching, routing, and metering all live there, so the engines behind it can stay simple and keyless. Put that way, a gateway sounds like any reverse proxy with a middleware chain, and structurally it is. What makes it its own subject is that its payload is a stream. Every feature it gains is a step in front of, or around, one operation: copy the engine’s response to the client, chunk by chunk, without delaying the first token.
Concepts from other sections (18)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- usage policy: an ordered list of rules that allow or deny inference requests by model, tenant, token cap, or classifier score. Read more: 25.6 Usage policy enforcement
- reverse proxy: a server that receives a client’s request, makes a new request to an upstream server, and relays the response. Read more: 25.1 The tracer gateway
- hop-by-hop header: a header that describes one connection only and is not forwarded across a proxy. Read more: 25.1 The tracer gateway
- server-sent events (SSE): a
text/event-streamresponse ofdata: ...\n\nevents over one long HTTP response. Read more: 25.1 The tracer gateway - graceful shutdown: stop accepting, let in-flight work finish within a bound, then exit 0. Read more: 1.9 Async Rust and tokio: futures, tasks, channels, cancellation, hyper in Programming and Algorithms
- disaggregated serving: prefill on one worker, decode on another, connected by a KV transfer. Read more: 25.4 Routing, cascades, and failover
- usage ledger: the durable per-request record of tenant, key, model, status, tokens, and latency. Read more: 25.5 The usage ledger and admin API
- Request id: a caller-chosen id that makes a signal idempotent; stored in run state rebuilt from history. Read more: 7.8 Signals, cancellation, and sagas in Systems Engineering
- composition root: the one place (here
main) where independent components are constructed and wired together. Read more: 25.2 The server skeleton - time to first token (TTFT): the time until the first body byte of an answer is ready to send to the client. Read more: 25.3 The SSE streaming proxy
- commitment boundary: the point (the status line) after which a proxy can no longer retry a request elsewhere. Read more: 25.3 The SSE streaming proxy
- Provider selection: the routing decision of which endpoint serves an already chosen model, usually made by a gateway on price, availability, or latency; pinning a model name does not pin the provider. Read more: 24.5 Routing implementations and selection
- Prompt caching: a provider feature that bills previously seen prompt-prefix tokens at a reduced rate; caches are per model and usually per provider, so switching models discards them. Read more: 24.5 Routing implementations and selection
- API key: a credential
tl_<id>_<secret>whose public id locates a record and whose secret proves possession. Read more: 10.1 API Keys, Scopes, Model Allowlists, and Tenants in Software Engineering - bounded loads: a consistent-hashing variant that skips a key’s owner once its load exceeds . Read more: 25.4 Routing, cascades, and failover
- canary split: a weighted division of one public model’s traffic across served model versions. Read more: 25.4 Routing, cascades, and failover
- linear head: a classifier followed by softmax, applied to a normalized embedding. Read more: 25.6 Usage policy enforcement
- Audit event: a record of a decision holding identifiers only, never prompt text, completions, or embeddings. Read more: 37.1 Usage policy at the gateway
That one constraint shapes everything in this chapter. Bytes are forwarded and flushed as they arrive, never parsed and re-emitted. Each request is two HTTP exchanges, client to gateway and gateway to engine, so hop-by-hop headers stay on their hop and the gateway’s own key never travels further. Before the first byte of a response the gateway can still choose a status (401, 429, 503) or try another worker; after it, the only honest signal of failure is an SSE error event. And the gateway continues the caller’s trace with its own span, so one request is one trace from client to engine.
The chapter builds the gateway in the order the request meets it. It starts with a tracer gateway that is the core operation plus a key check and trace propagation, then gives it a skeleton: an ordered middleware chain, requestid -> otel -> recover -> authn -> policy -> ratelimit -> cache -> route -> proxy -> meter, a shared request record, graceful shutdown, and configuration. The streaming proxy learns to observe a stream without touching it, the router spreads requests over a fleet of engines with failover, cascades, and disaggregated serving, the usage ledger records who used what and assembles the whole chain, and the policy stage enforces usage restrictions. Two stages of the chain, authentication and rate limiting, are built in Authorization and access control, and the response cache in Distributed data and caching. Each section extends the same go/gateway/ packages behind the same OpenAI-compatible surface.
Learning objectives
- Build a streaming reverse proxy that checks keys in constant time, fails closed, flushes every chunk, and propagates W3C trace context and request ids.
- Compose gateway stages in a contractual order through a composition root, and shut the server down without cutting streams.
- Observe SSE streams for time to first token and usage without changing a byte, and draw the commitment boundary that decides what may be retried.
- Route requests across a live fleet with heartbeats, load-aware and cache-aware policies, canaries, cascades, failover, and disaggregated prefill and decode.
- Meter every request durably in SQLite, serve a fail-closed admin API, and enforce an auditable usage policy.
Before you begin
Section titled “Before you begin”You should be comfortable reading Go; Go: packages, interfaces, goroutines, channels, context, net/http, testing in Programming and Algorithms covers what the chapter uses. The wire format the gateway forwards is the subject of Streaming and SSE. The engine the gateway fronts, and its API, comes from Your first endpoint in AI Engineering. The routing section draws on Model routing and cascades for the ideas behind cascades, and the gateway’s spans and metrics feed Observability in Systems Engineering.
For routing across provider APIs, see Designing a model router across APIs, caches, and applications. It separates application task and tool decisions from provider selection, adapters, prompt caching, and worker scheduling; this chapter implements routing behind one compatible gateway surface.
The full solution code for every section lives in course/solutions/go/gateway/.
In this chapter
Section titled “In this chapter”- The tracer gateway. The thinnest gateway that closes the engine’s open port: a static API key checked in constant time and failing closed, SSE pass-through with a flush per chunk, the before-and-after-first-byte failure rules, and
traceparentandX-Request-Idpropagation. - The server skeleton. The ordered middleware chain and why each stage sits where it does, the composition root that lets the server be built before its stages, the request-scoped
Exchange, a drain that Kubernetes rollouts cannot cut, and one configuration loader for every Go service. - The SSE streaming proxy. Relaying a stream byte for byte while a splitter observes its events, first byte, and usage on the side, and the commitment boundary that tells the router which failures it may retry.
- Routing, cascades, and failover. A heartbeat registry with exact eviction, three routing policies including prefix affinity with bounded loads, canary splits, failover before the first byte, cascades with a cost and accuracy curve, and disaggregated prefill and decode.
- The usage ledger and admin API. A meter that writes one durable SQLite row per request, including stream usage the client never asked for; half-open usage queries; a fail-closed admin front door; and the assembly of every stage into the chain.
- Usage policy enforcement. An ordered, first-match policy of model, tenant, token-cap, and classifier rules, with a numerically stable linear head, fail-closed 503s, 451 denials with stable rule ids, and redacted audit events.
Key terms
Section titled “Key terms”- AI gateway / LLM gateway: the single front door to a fleet of model servers, where authentication, rate limits, usage policy, caching, routing, and metering live, so the engines behind it stay simple and keyless; its defining constraint is forwarding a token stream without delaying the first token.
Further reading
Section titled “Further reading”- RFC 9110 HTTP Semantics (free)
- W3C Trace Context (free)
- OpenAI API reference (free)
- Envoy AI Gateway (free)
- LiteLLM proxy (free)
net/http/httputil.ReverseProxy(free)