25.2 The server skeleton
The tracer gateway is one handler with everything inside it: the key check, the trace, the forward. The rest of this book adds real keys (API keys and scopes), rate limits (Rate limiting), a streaming observer (The SSE streaming proxy), routing across engines (Routing, cascades, and failover), a response cache (The response cache), and a usage ledger (The usage ledger and admin API). Bolted into one function, each of them would have to know about the others, the order in which they run would be an accident of whoever edited last, and a panic in any of them would take the process down mid-stream.
Concepts from other sections (13)
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 ledger: the durable per-request record of tenant, key, model, status, tokens, and latency. Read more: 25.5 The usage ledger and admin API
- 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
- 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
- KV cache: per-layer storage of past keys and values, so each decode step processes only the new token. Read more: 21.2 The KV cache, incremental decoding, and generate
- goroutine: a function running concurrently, scheduled by the Go runtime. Read more: 1.6 Go: packages, interfaces, goroutines, channels, context, net/http, testing in Programming and Algorithms
- unknown fields: records a reader does not recognize, kept by generated code and written back on re-encode. Read more: 1.10 Protocol Buffers and gRPC: schema evolution, unary and streaming RPCs, stubs in Programming and Algorithms
- readiness probe / liveness probe: checks that, on failure, remove a Pod from its Service or restart its container, respectively. Read more: 10.1 Tracer deploy: images, a kind cluster, two Helm charts, and Jaeger in Systems Engineering
- Load balancer: a component that spreads traffic across instances of a service by round-robin, least connections, or consistent hashing, at layer 4 (TCP) or layer 7 (HTTP). Read more: Chapter 1: System Design in Systems Engineering
- server-sent events (SSE): a
text/event-streamresponse ofdata: ...\n\nevents over one long HTTP response. Read more: 25.1 The tracer gateway - KV handle: the id under which a decode worker holds KV blocks pushed by a prefill worker. Read more: 25.4 Routing, cascades, and failover
- SIGKILL: an uncatchable signal that ends a process between two instructions, leaving only what is on disk. Read more: 12.3 The durable server is SIGKILLed in a loop during a corpus build in Systems Engineering
- Request for Comments (RFC): in a team design process, a proposal that invites feedback on a change before a decision is made. Read more: Chapter 13: Engineering Acronyms in Software Engineering
- OpenTelemetry (OTel): the vendor-neutral standard for traces, metrics, and logs, made of an SDK, a collector, and exporters. Read more: Chapter 11: Observability in Systems Engineering
Operations add their own pressure. When Helm charts for the gateway and the engine (in Systems Engineering) rolls the gateway on Kubernetes, the pod receives SIGTERM and has 30 s. A gateway that exits at once cuts every user’s stream, and one that keeps answering /readyz with 200 keeps receiving new requests while it shuts down.
This section builds the skeleton the rest plug into: an ordered chain, a shared request record, a health port that tells the truth, a drain that finishes what it started, and one configuration loader for every Go service. It assumes you can read Go (Go: packages, interfaces, goroutines, channels, context, net/http, testing in Programming and Algorithms) and that you have read the tracer gateway. The solution lives in go/gateway/server/chain.go (the chain in its contractual order, the Exchange, WriteError, ParseRequest), go/gateway/server/server.go (New, Deps, Config, the health port, Shutdown, Run), go/config/config.go (runtime.toml with TL_<SECTION>__<KEY> overrides), and the composition root entry/go/cmd/gateway/compose.go, which is the gateway --config <runtime.toml> form of the role. go/config uses github.com/BurntSushi/toml, which is allowed in contracts/allowed-deps.toml.
The contracts are course/contracts/config/runtime.schema.json (the file and the override rule), the gateway role’s --config form in course/contracts/spec/cli-roles.md, and the health and error rules of course/contracts/openapi/openai-subset.v1.yaml.
Learning objectives
- State the gateway’s middleware order and justify the position of every stage.
- Explain how a composition root lets the server be built before any of its stages exist.
- Use a request-scoped
Exchangeto pass data between stages, reading the body exactly once.- Sequence a graceful shutdown so a Kubernetes rollout never cuts a stream or refuses a connection it routed.
- Load configuration with one precedence (environment over file over defaults) that rejects typos at start-up.
The chain and its order
Section titled “The chain and its order”A middleware is a function from handler to handler, func(next http.Handler) http.Handler. It can act before calling next, after it returns, or instead of calling it (rejecting the request). Name the pieces:
| Symbol | Meaning | Type |
|---|---|---|
| the handler at the end of the chain (the proxy) | http.Handler | |
| the -th middleware, outermost first | server.Middleware | |
| the number of middlewares | integer |
Composing middlewares around gives : sees the request first and the response last. This is the decorator pattern (see Coding and design patterns). The gateway’s order, outermost first, is a contract, and each position has a reason:
| Stage | Built in | Why here |
|---|---|---|
requestid | this section | everything after it, including error answers, can quote the id |
otel | this section (spans from Tracing for the serving path) | the server span covers every later stage, rejections included |
recover | this section | inside otel, so a panic still ends the span with status 500 |
authn | API keys and scopes | nothing below may act for an unknown caller |
policy | Usage policy enforcement | a blocked prompt never spends rate limit or reaches the cache |
ratelimit | Rate limiting | before the cache, so a cache hit still counts as a request |
cache | The response cache | a hit skips routing and the engine entirely |
route | Routing, cascades, and failover | picks the worker the proxy sends to |
proxy | the tracer gateway, then the SSE streaming proxy | the handler at the end: forward and stream |
meter | The usage ledger and admin API | wraps the proxy, so it is the first to see the finished exchange |
Put in one line: requestid -> otel -> recover -> authn -> policy -> ratelimit -> cache -> route -> proxy -> meter. A request is named, traced, and protected from panics before anything can reject it, authenticated before anything reads its key, and limited before the cache can answer it. The final proxy -> meter orders when stages finish their work: the meter wraps the proxy and records after it returns. Every stage is optional except the proxy: a nil slot is skipped, and a missing proxy answers 503 no_capacity.
The recover stage needs a closer look, because Go already has an answer to panics and it is the wrong one here. Go’s net/http recovers a handler panic by closing the connection, which a client sees as a network error. The recover stage instead answers 500 with {"error": {..., "type": "server_error", "code": "internal_error"}} and logs the stack with the request id, so the process keeps serving. If the response already started (a stream is half sent), the status line is gone, so the stage writes nothing more. A handler that panics with http.ErrAbortHandler is asking for the connection to be dropped, so that one is re-panicked.
Request id and internal headers
Section titled “Request id and internal headers”The first stage keeps a caller’s X-Request-Id when it is printable ASCII (0x21 to 0x7E) of at most 128 bytes (the tracer gateway’s rule), and otherwise makes one. It sets the id in three places: the response, the request (so the proxy forwards it), and the Exchange.
It also deletes every X-TL-* header the client sent, except the public X-TL-API-Version. X-TL-Priority and X-TL-KV-Handle are set by the gateway toward engines (by the auth and routing stages). A client that could set them would jump the engine’s queue or resume someone else’s KV cache, which is what the contract’s priority.internal rule forbids.
The Exchange
Section titled “The Exchange”Stages need to tell each other things without importing each other. The limiter needs the usage the proxy saw, so it can settle; the meter needs the status, the worker, and the usage; the trace needs whatever attributes stages recorded. The Exchange is that record. It is created by requestid and reached from any stage with server.ExchangeFrom(r.Context()). Its mutable fields are behind a lock, because the proxy writes the usage from the goroutine that reads the stream.
The body is read once. ex.Request(r) reads at most 4 MiB (the same cap as every gRPC message), parses the fields stages need (model, stream, the token limit with max_completion_tokens winning over max_tokens, temperature, seed), caches the result, and puts an identical reader back on r.Body so the proxy forwards the bytes unchanged. Unknown fields are ignored, as the contract says; a body that is not one JSON object is an error that the calling stage answers with 400.
Health, readiness, and draining
Section titled “Health, readiness, and draining”A server that is part of a fleet has to tell the fleet the truth about itself. The health port (:9464 in Kubernetes, {health_port} locally) answers three paths:
| Path | Means | Answer |
|---|---|---|
/healthz | the process is alive (restart me if not) | always 200 |
/readyz | send me traffic | 503 while draining or while Deps.Ready fails (for the router: no routable worker), else 200 |
/metrics | Prometheus exposition | Deps.Metrics (from Tracing for the serving path), else 404 |
A Kubernetes rollout sends SIGTERM, removes the pod from its Service only after the readiness probe fails, and kills the pod after terminationGracePeriodSeconds. That fixes the order of Shutdown(ctx):
- Mark draining:
/readyzanswers 503 from now on, so the load balancer stops sending new work. - Call
http.Server.Shutdown(ctx): close the listener (new connections are refused), close idle connections, and wait for active requests, SSE streams included, to finish. - If
ctxexpires first, cancel the base context every request context descends from (so each handler and its upstream call to the engine stops) and close the connections; returncontext.DeadlineExceeded. - Close the health server last, so probes see 503 for the whole drain.
Run(ctx, api, health) serves until ctx is done, then shuts down with drain_deadline_s. The entry point builds that ctx with signal.NotifyContext(ctx, syscall.SIGTERM, os.Interrupt).
Configuration
Section titled “Configuration”The last piece of the skeleton is shared by every Go service: they all read one runtime.toml (config/runtime.schema.json). There is exactly one precedence, highest first:
| Source | Example | Wins over |
|---|---|---|
environment TL_<SECTION>__<KEY> | TL_GATEWAY__CACHE_ENTRIES=50 | file, defaults |
| the file | [gateway] cache_entries = 100 | defaults |
| schema defaults | cache_entries = 4096 | nothing |
Keys contain single underscores (kv_blocks, cache_entries), so only the double underscore separates section from key: TL_ENGINE__KV_BLOCKS is engine.kv_blocks. A variable without __ (TL_API_KEY, TL_GATEWAY_PEPPER) is not an override at all; those are secrets the services read by name. An override is parsed as its key’s type (integer, number, boolean, string); tables and arrays (engine.speculative, gateway.routes) are not overridable.
Unknown keys are errors everywhere except under [ext], which is free-form. Without that rule a typo such as cache_entires = 5 would leave the default in force without a word. Validation (enumerations such as route_policy, ranges such as key_cache_ttl_s in 0 to 5) runs after the overrides, because an environment variable can be as wrong as a file.
Working it by hand
Section titled “Working it by hand”Three small experiments make these rules concrete: one request through the chain, one configuration load, and one drain.
For the chain, put a recording middleware in every Deps slot (each logs enter X, calls next, logs leave X), a fake tracer that logs enter otel when it starts a span, and a proxy that logs proxy. One request produces:
enter otelenter authn, enter policy, enter ratelimit, enter cache, enter routeenter meterproxyleave meterleave route, leave cache, leave ratelimit, leave policy, leave authnrequestid and recover are the server’s own and log nothing; meter sits directly around the proxy.
For the configuration, the defaults say cache_entries = 4096, and the file says
[gateway]listen = ":8081"cache_entries = 100route_policy = "least_outstanding"while the environment holds TL_GATEWAY__CACHE_ENTRIES=50, TL_API_KEY=tl_x_y, and HOME=/home/me. Loading gives cache_entries = 50 (environment beats file), listen = ":8081" (file beats default), and health_listen = ":9464" and key_cache_ttl_s = 5 (defaults). It ignores TL_API_KEY (no __) and HOME.
For the drain, a client is reading an SSE stream, and the gateway receives SIGTERM at with drain_deadline_s = 30. Here is what each party sees:
| Event | /readyz | New connection | The stream | |
|---|---|---|---|---|
| 0 s | Shutdown starts, draining marked | 503 | refused | running |
| 4 s | the engine sends [DONE] | 503 | refused | complete |
| 4 s | no request left: Shutdown returns nil | closed | refused | done |
Had the stream still been running at 30 s, its context would have been cancelled (the engine stops generating), its connection closed, and Shutdown would have returned context.DeadlineExceeded.
The interface
Section titled “The interface”The server and configuration packages expose this surface:
package server // import "tinyllm/gateway/server"
type Middleware func(next http.Handler) http.Handlertype Clock interface{ Now() time.Time } // a fake clock satisfies it in teststype Tracer interface { Start(ctx context.Context, name string) (context.Context, Span) }type Span interface { SetAttribute(key string, value any); End() }
var Order []Stage // requestid otel recover authn policy ratelimit cache route proxy meter
type Deps struct { Keys, Policy, Limiter, Cache, Router Middleware // authn, policy, ratelimit, cache, route Proxy http.Handler // required Ledger Middleware // meter, wraps Proxy Clock Clock; Tracer Tracer Ready func(ctx context.Context) error // readiness beyond "not draining" Metrics http.Handler // GET /metrics on the health port}type Config struct { Listen, HealthListen string; DrainDeadline time.Duration; MaxBodyBytes int64 }func FromRuntime(g config.Gateway) Config
func New(cfg Config, d Deps) *Serverfunc (s *Server) Handler() http.Handler // the API chainfunc (s *Server) HealthHandler() http.Handler // /healthz, /readyz, /metricsfunc (s *Server) Serve(api, health net.Listener) errorfunc (s *Server) Shutdown(ctx context.Context) errorfunc (s *Server) Run(ctx context.Context, api, health net.Listener) errorfunc (s *Server) Draining() bool
type Usage struct { PromptTokens, CompletionTokens, TotalTokens int }type Request struct { Model string; Stream bool; MaxTokens int; Temperature *float64; Seed *int64; Body []byte }func ParseRequest(body []byte) (Request, error)func ExchangeFrom(ctx context.Context) *Exchangefunc (e *Exchange) Request(r *http.Request) (*Request, error)func (e *Exchange) SetUsage(Usage); func (e *Exchange) MarkFirstByte(); func (e *Exchange) SetWorker(string)func (e *Exchange) SetAttr(key string, v any); func (e *Exchange) Snapshot() ExchangeStatefunc WriteError(w http.ResponseWriter, status int, typ, code, param, msg string) // "" param or code is null
package config // import "tinyllm/config"func Default() Configfunc Parse(data []byte, env []string) (Config, error)func Load(path string, env []string) (Config, error)func ApplyEnv(c *Config, env []string) errorfunc EnvName(section, key string) stringfunc (c Config) Validate() errorTwo choices differ from the catalog sketch. New returns a *Server holding two http.Servers (the API and the health port) rather than a single *http.Server, because readiness and the drain belong to one object. And Deps holds middleware rather than domain interfaces (Keys, Limiter, and so on): the stage packages import this one, so this one cannot name their types.
The composition root, entry/go/cmd/gateway/compose.go, loads config.Load(path, os.Environ()), builds each stage (auth.Middleware, limit.Middleware, cache.Middleware, route.Middleware and route.Proxy, ledger.Meter), passes them in Deps, and calls Run with a context cancelled on SIGTERM. Until the streaming proxy exists, Deps.Proxy can be the tracer gateway’s handler.
Building it step by step
Section titled “Building it step by step”The design follows from seven observations, and it is worth seeing them before the code:
- Stages must not know each other, so the server must not know them either. If the server imported the auth or cache packages, every stage would depend on every other through it. Inverting the dependency (stages import
serverforMiddleware,Exchange,WriteError;mainwires them intoDeps) makes the skeleton buildable before any stage exists, and makes each stage replaceable. That is what a composition root is. - Order is a contract, so it lives in one place.
Handlercomposes the slots innermost first, in a fixed sequence, and anilslot is skipped. Nothing else decides the order. - Stages communicate through one request-scoped record. Context values are the standard carrier: one
*Exchangeper request, created by the first stage, behind a mutex because the proxy writes from the stream goroutine. - The body is a stream that can be read once. The first stage that needs it reads it (with a cap), parses it, caches the result, and puts identical bytes back so the proxy forwards them unchanged.
- Failure handling must sit where it can still answer.
recovergoes insideotel(so the span sees the 500) and outside every stage (so any stage’s panic is caught). It can only write a 500 if nothing was written; thestatusWriterrecords whether something was. - Shutdown is ordered by what the load balancer sees. Readiness flips first; then the listener closes; then in-flight requests drain; at the deadline a base context that every request descends from is cancelled. The health server stays up to the end so probes keep seeing 503.
- Configuration must fail loudly. Decode over defaults, reject undecoded keys (except
[ext]), apply environment overrides by reflection on the same struct tags, then validate. One precedence, checked in one order.
Composing the chain
Section titled “Composing the chain”The chain is built from the inside out: the proxy (or a 503 handler), then meter, route, cache, ratelimit, policy, authn, and finally the server’s own three stages.
func (s *Server) Handler() http.Handler { var h http.Handler = s.deps.Proxy if h == nil { // the only required slot: without it, an honest 503 h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { WriteError(w, http.StatusServiceUnavailable, "server_error", "no_capacity", "", "no upstream is configured") }) } // Innermost first: meter wraps the proxy, then route, cache, ratelimit. for _, m := range []Middleware{s.deps.Ledger, s.deps.Router, s.deps.Cache, s.deps.Limiter} { if m != nil { // stages land one at a time h = m(h) } } if s.deps.Policy != nil { // after authn, before ratelimit h = s.deps.Policy(h) } if s.deps.Keys != nil { h = s.deps.Keys(h) } h = s.recoverer(h) // inside otel, so a panic's 500 is on the span h = s.otel(h) return s.requestID(h) // outermost: everything after it can quote the id}Reading the wrapping order backwards gives the request order of the chain table. The first version of this file wrapped all six slots in one loop; adding the policy stage split out Policy so its position is explicit. The original is kept at history/gw.01/.../chain.go.
The first stage
Section titled “The first stage”requestID strips internal headers, picks the id, sets it on both sides, creates the Exchange, and wraps the writer so the status is recorded.
func (s *Server) requestID(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for k := range r.Header { // X-TL-Priority and X-TL-KV-Handle are set by the gateway toward // engines; a client must not set them. API version selection is public. if strings.HasPrefix(strings.ToLower(k), "x-tl-") && !strings.EqualFold(k, "X-TL-API-Version") { r.Header.Del(k) } } id := r.Header.Get("X-Request-Id") if !validRequestID(id) { // printable ASCII, 1 to 128 bytes: the tracer gateway's rule id = newID() } r.Header.Set("X-Request-Id", id) // forwarded upstream by the proxy w.Header().Set("X-Request-Id", id) ex := NewExchange(id, s.clock, s.cfg.MaxBodyBytes) next.ServeHTTP(&statusWriter{ResponseWriter: w, ex: ex}, r.WithContext(WithExchange(r.Context(), ex))) })}statusWriter sets the Exchange’s status on the first WriteHeader, or 200 on a first Write without one (which is what net/http sends), and exposes Unwrap so http.NewResponseController can still flush through it.
Recovering from panics
Section titled “Recovering from panics”The Exchange’s status tells the recover stage whether the response has started:
func (s *Server) recoverer(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { v := recover() if v == nil { return } if v == http.ErrAbortHandler { panic(v) // the handler asked for the connection to be dropped: honour it } ex := ExchangeFrom(r.Context()) log.Printf("gateway: panic in request %s: %v\n%s", ex.RequestID, v, debug.Stack()) if ex.Snapshot().Status == 0 { // nothing sent yet: we can still answer properly WriteError(w, http.StatusInternalServerError, "server_error", "internal_error", "", "internal error; quote X-Request-Id "+ex.RequestID) } // otherwise a stream is half sent: appending JSON would corrupt it }() next.ServeHTTP(w, r) })}The otel stage (skipped when Deps.Tracer is nil) starts a span named "<METHOD> <path>", and in a defer copies the final status and every attribute stages recorded with ex.SetAttr onto it before ending it.
Reading the body once
Section titled “Reading the body once”func (e *Exchange) Request(r *http.Request) (*Request, error) { e.mu.Lock() defer e.mu.Unlock() if e.req != nil || e.reqErr != nil { // parsed already: same answer for every stage if e.req != nil { r.Body = io.NopCloser(bytes.NewReader(e.req.Body)) // a fresh reader each time } return e.req, e.reqErr } var body []byte if r.Body != nil { // Read one byte past the cap, so "exactly the cap" and "too large" differ. b, err := io.ReadAll(io.LimitReader(r.Body, e.maxBody+1)) // ... a read error is cached and returned body = b } if int64(len(body)) > e.maxBody { e.reqErr = fmt.Errorf("the request body is larger than %d bytes", e.maxBody) return nil, e.reqErr } r.Body = io.NopCloser(bytes.NewReader(body)) // the proxy forwards these exact bytes req, err := ParseRequest(body) // ... cache req or err}ParseRequest requires the trimmed body to start with {, decodes only the fields stages need (unknown fields are ignored), and resolves the token limit with max_completion_tokens taking precedence over max_tokens. WriteError encodes param and code as *string, so an empty argument is null: all four keys are always present.
The servers and shutdown
Section titled “The servers and shutdown”There are two http.Servers. The API one gets a BaseContext the server can cancel:
s.baseCtx, s.cancelBase = context.WithCancel(context.Background())s.api = &http.Server{ Addr: cfg.Listen, Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second, // Every request context descends from baseCtx, so cancelling it at the // drain deadline reaches every in-flight handler and its upstream call. BaseContext: func(net.Listener) context.Context { return s.baseCtx },}Shutdown is the four-step sequence from earlier, in code:
func (s *Server) Shutdown(ctx context.Context) error { s.draining.Store(true) // 1. /readyz answers 503 from this instant err := s.api.Shutdown(ctx) // 2. close the listener, wait for active requests (streams too) if err != nil { // 3. the deadline passed with requests still running s.cancelBase() // their contexts end: handlers and engine calls stop _ = s.api.Close() // and their connections close } s.once.Do(s.cancelBase) hctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _ = s.health.Shutdown(hctx) // 4. last, so probes saw 503 for the whole drain return err // nil, or context.DeadlineExceeded}/readyz checks draining first and Deps.Ready second; /healthz always answers 200, because a draining process is alive and must not be restarted. Run serves until its context is done, then calls Shutdown with a fresh context bounded by DrainDeadline: the parent context is already cancelled, so it cannot be the drain’s deadline.
Loading configuration
Section titled “Loading configuration”Parse applies the three sources in reverse order of precedence, so each overwrites the last:
func Parse(data []byte, env []string) (Config, error) { c := Default() // 3rd: schema defaults md, err := toml.Decode(string(data), &c) // 2nd: the file, over the defaults // ... return a decode error var unknown []string for _, k := range md.Undecoded() { // keys the struct has no field for if len(k) > 0 && k[0] == "ext" { continue // [ext] is free-form by contract } unknown = append(unknown, k.String()) } // ... any unknown key is an error listing all of them if err := ApplyEnv(&c, env); err != nil { // 1st: the environment wins return Config{}, err } if err := c.Validate(); err != nil { // after overrides: env can be wrong too return Config{}, err } return c, nil}The core of ApplyEnv is the separator rule:
for _, kv := range vars { // sorted, so several bad variables give a deterministic error name, val, found := strings.Cut(kv, "=") // first "=": values may contain "=" if !found || !strings.HasPrefix(name, "TL_") { continue } section, key, ok := strings.Cut(strings.TrimPrefix(name, "TL_"), "__") if !ok { continue // TL_API_KEY and friends: secrets read by name, not overrides } // ... find the section and key by their toml tags, upper-cased; unknown: an error naming the variable if err := setScalar(f, val); err != nil { // parsed as the field's kind; tables and arrays refused return fmt.Errorf("%s: %w", name, err) }}Because the lookup uses the same toml tags as the decoder, there is no second list of keys to keep in sync. Validate checks the enumerations (route_policy, engine.role, prefix_cache) and ranges (key_cache_ttl_s 0 to 5, affinity_load_factor at least 1, trace_sample_ratio 0 to 1) that a typed decode cannot.
The composition root
Section titled “The composition root”entry/go/cmd/gateway/compose.go is the --config form: config.Load(path, os.Environ()), the stages built from the loaded [gateway] section, server.New(server.FromRuntime(g), deps), and Run under signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt).
The full solution is in chain.go, server.go, and config.go.
Why this design
Section titled “Why this design”The cost is small. The chain adds a header scan, one allocation for the Exchange, and a few lock operations per request, and the body is read at most once, with a 4 MiB cap, instead of once per stage.
Why middleware slots and not interfaces like Keys or Limiter? The server would have to name the stage packages’ types, and those packages import the server: an import cycle. Middleware is a type the server owns, so the dependency points one way.
Why a shared Exchange and not one context value per stage? Context values are write-once per derived context, and the proxy’s usage, recorded deep in the chain, must be visible to the limiter and the meter that wrapped it. A pointer to one mutable record, under a lock, is the simplest way to pass data back up.
Why not let net/http recover panics? It closes the connection, so a client cannot tell a crash from a network fault and gets no request id to report. Answering 500 in the contract’s shape is retryable and debuggable.
Why reflection for environment overrides? A hand-written switch per key would drift from the struct. Reusing the toml tags makes every scalar key overridable automatically and every unknown variable an error.
Note: One tradeoff is accepted. The drain deadline is shared by all streams, so a long stream started just before SIGTERM is cut at the deadline.
drain_deadline_smust be shorter than the pod’sterminationGracePeriodSeconds.
What can go wrong
Section titled “What can go wrong”The tests check the following cases. Each protects something later in the book:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the chain order by hand | unit | the enter and leave trace above, and server.Order | every later stage relies on what ran before it |
| nil stages are skipped | boundary | only a proxy: it serves; no proxy: 503 no_capacity | stages land one at a time |
| the request id stage | unit | kept, generated, replaced (129 bytes, a space); the response, the forwarded header, and the Exchange agree | log correlation joins logs on it |
| internal headers stripped | unit | client X-TL-* headers never reach the proxy | priority.internal; the router’s KV handle |
| a panic becomes a 500 | fault | a panicking stage: 500 internal_error with X-Request-Id, the span ends with 500, the next request is fine | one bug costs one request |
| a panic after the first byte | fault | a panic after the first byte appends nothing | streams are never corrupted |
| span attributes | unit | span POST /v1/chat/completions with method, route, status, and a stage’s tl.ratelimit.decision | the tracing section exports this span |
| the error shape | unit | exact bytes, with param and code, and with both null | every stage’s errors parse in OpenAI clients |
| parsing the request through the Exchange | unit | one read, body forwarded unchanged, max_completion_tokens wins, cached parse, non-objects and oversized bodies rejected | auth, limits, cache, and routing read the same fields |
| readiness | unit | /healthz 200; /readyz follows Deps.Ready; /metrics | scripts and Kubernetes wait on it |
shutdown flips /readyz, then drains | fault | the drain above: 503 during the drain, new connections refused, the stream finishes, Shutdown returns nil | the Helm rollout does not cut streams |
| shutdown cuts streams at the deadline | fault | at the deadline the handler’s context is cancelled and DeadlineExceeded returned | a stuck stream cannot block a rollout |
Run shuts down on cancel | unit | Run returns nil after its context is cancelled | the entry point’s SIGTERM path |
| the configuration hand example | unit | the precedence above, routes with an inline cascade, inline tables, [ext] | a generated runtime.toml for the full gateway |
| configuration defaults | unit | an empty file yields the schema defaults | templates can stay short |
| the override separator | unit | __ only; TL_API_KEY and lower-case names ignored; = inside a value | secrets are never misread as overrides |
| override types | unit | numbers parse; a non-integer fails naming the variable | a typo stops start-up |
| override errors | boundary | unknown key or section, a table, an array: errors naming the variable | the same |
| unknown keys rejected | boundary | unknown keys in the file, [ext] free-form | the same |
| validation after overrides | boundary | route_policy = "random" from the file or the environment, key_cache_ttl_s = 9 | enumerations hold after overrides |
Load and FromRuntime | unit | Load reads a file, FromRuntime turns drain_deadline_s into a duration | the entry point |
The common mistakes, their symptoms, and the line that prevents each:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| stages composed in the wrong order (the limiter around authn, the meter around the router) | limits keyed by nobody; usage recorded before routing | Handler wraps the slots in one fixed sequence, innermost first |
recover outside otel | the span of a crashed request ends with status 0, not 500 | h = s.recoverer(h) comes before h = s.otel(h) |
| a recover that only logs | the client sees a dropped connection instead of a 500 it can retry | recoverer writes a 500 internal_error when the status is still 0 |
forwarding client X-TL-* headers | any client can set its own engine priority | requestID deletes every X-TL-* header except X-TL-API-Version |
setting X-Request-Id only on the response | engine logs cannot be joined to the client’s id | the id is set on the request and the response |
writing after the first byte, or "param": "" | a JSON error spliced into an SSE stream; clients that test param == null misread errors | recoverer writes only when the status is 0; WriteError encodes empty param and code as null |
| ignoring unknown keys | cache_entires = 5 silently keeps 4096 | Parse turns every undecoded key outside [ext] into an error |
splitting on _, ignoring bad overrides, letting the file beat the environment, validating before overriding | TL_ENGINE__KV_BLOCKS never applies; a Kubernetes env override has no effect; TL_GATEWAY__ROUTE_POLICY=random starts | ApplyEnv cuts on __, errors on unknown or unparsable overrides, runs after the decode, and Validate runs last |
/readyz that ignores draining, or flips after the drain | new requests keep arriving during a rollout and get refused connections | Shutdown sets draining before closing the listener; /readyz checks it first |
| no cancellation at the deadline | a stuck stream holds the pod until SIGKILL, and the engine keeps generating | the API server’s BaseContext is cancelled and its connections closed when the drain times out |
reading the body without putting it back, or max_tokens over max_completion_tokens | the engine receives an empty body; limits reserve the wrong count | Exchange.Request replaces r.Body; ParseRequest checks max_completion_tokens first |
Where this leads
Section titled “Where this leads”The skeleton draws on the Go primer for context, net/http, goroutines, and signal handling, and on the tracer gateway for the request id rule and a proxy usable in the Proxy slot until the streaming proxy replaces it.
Every later stage of the gateway is a server.Middleware that reads the Exchange and answers errors with WriteError; together they make up the full gateway. In API keys and scopes, auth.Middleware is the Keys slot: it parses the model with ex.Request and answers 401 and 403 with WriteError. In Rate limiting, limit.Middleware is the Limiter slot and settles with the usage the proxy put on the Exchange. In The SSE streaming proxy, proxy.Handler is the Proxy slot, and its observer records the first byte and the usage on the Exchange. In Routing, cascades, and failover, route.Middleware is the Router slot, route.Proxy replaces the proxy, and Router.Ready feeds /readyz. The response cache fills the Cache slot. In The usage ledger and admin API, ledger.Meter is the Ledger slot and the admin API answers errors with WriteError. Finally, Usage policy enforcement fills the Policy slot, between authn and ratelimit.
Further reading
Section titled “Further reading”- Mat Ryer, How I write HTTP services in Go after 13 years (free, 2024).
- RFC 9110 section 15 (status codes).
- The ordered chain in production: Envoy HTTP filters (free), with filters configured per route, async filters, and per-filter stats.
Shutdownand/readyzin production: KubernetespreStophooks and Envoy drain listeners, which add a sleep before draining so endpoints propagate, and connection draining with GOAWAY on HTTP/2. See Kubernetes pod lifecycle and its section on pod termination (free).go/configin production: Viper and koanf (free), with many sources, file watching, and reload.- The
Exchangein production: OpenTelemetry baggage and Envoy dynamic metadata (free), for request-scoped data across filters and processes.
Key terms
Section titled “Key terms”- middleware: a function from handler to handler that can act before, after, or instead of the next handler.
- composition root: the one place (here
main) where independent components are constructed and wired together. - Exchange: the request-scoped, lock-protected record through which gateway stages pass data to each other.
- liveness (
/healthz): whether the process is alive and should not be restarted. - readiness (
/readyz): whether the process should receive new traffic. - draining: the shutdown phase in which a server refuses new work and finishes work in flight.
- environment override: a
TL_<SECTION>__<KEY>variable that replaces one scalar configuration value.
Summary
Section titled “Summary”- The chain order is a contract:
requestid -> otel -> recover -> authn -> policy -> ratelimit -> cache -> route -> proxy -> meter. A request is named, traced, and protected from panics before anything can reject it, authenticated before anything reads its key, and limited before the cache can answer it. - The server imports none of its stages. Each stage is plain middleware in
Deps; the stage packages import the server forMiddleware, theExchange, andWriteError, andmainwires them. That composition root is why the skeleton can be built before any stage exists. - One request-scoped
Exchangecarries what stages tell each other: the request id, the parsed body (read once, put back for the proxy), the status, the usage the proxy saw, and the worker the router chose. - Shutdown is a sequence:
/readyzturns 503 first, the listener closes, streams in flight run to completion until a deadline, then their contexts are cancelled. - Configuration has one precedence (environment over file over defaults), one separator (
__), and no silent typos: unknown keys and bad overrides stop the process at start-up.
Review questions
Section titled “Review questions”-
Why is
recoverinsideoteland not outside it?Answer
otelends its span in adeferwith the status from theExchange. Ifrecoverwere outside, the panic would unwind throughotelbefore any 500 was written: the span would end with status 0 and the trace would not show the crash. Inside,recoverwrites the 500 first, thenotel’sdeferrecords it. -
A stage reads
r.Bodydirectly instead of callingex.Request(r). What does the engine receive?Answer
An empty body: the stream has been consumed and nothing put it back.
ex.Requestexists so that the body is read once, cached, and replaced by an identical reader, which the proxy then forwards unchanged. -
During a rollout, why must
/readyzturn 503 before the listener closes, and why is the health server shut down last?Answer
Kubernetes removes a pod from its Service only after the readiness probe fails. If the listener closed first, the load balancer would keep sending new connections that are refused. Keeping the health server up until the end means every probe during the drain sees 503, so no new traffic is routed while in-flight streams finish.
-
Why is
TL_API_KEYignored byApplyEnv, whileTL_GATEWAY_CACHE_ENTRIES=5(single underscore) is also ignored, and is that second case a problem?Answer
Only a double underscore separates section from key, because keys themselves contain underscores. Neither variable has
__, so neither is an override:TL_API_KEYis a secret read by name, which is intended. The single-underscore typo is silently ignored too; the rule trades that risk for never misreading a secret as configuration. A wrong name with__(TL_GATEWAY__CACHE_ENTIRES) is an error. -
Why does
Runcreate a new context forShutdowninstead of passing its ownctx?Answer
Run’sctxis the one that was just cancelled by SIGTERM. Passing it toShutdownwould make the drain’s deadline already expired, so every stream would be cut at once. A fresh context bounded byDrainDeadlinegives in-flight requests their grace period.