Chapter 23: Build a Model Server
Everything earlier in this book produces a checkpoint. This chapter turns a checkpoint into a service: a Rust engine behind an OpenAI-compatible HTTP API that streams completions through Candle tensor operations. By the end, the same API that any OpenAI client can call is backed by continuous batching, a paged and prefix-cached KV pool, disaggregated prefill and decode, speculative decoding, constrained tool calls, and the metrics and traces that let you tell how well it all works.
Concepts from other sections (28)
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.
- continuous batching: re-forming the batch at every step so finished requests leave and waiting ones join immediately. Read more: 23.3 Continuous batching scheduler with priority and preemption
- KV pool: the GPU memory left for KV cache after weights and activation headroom; it sets maximum concurrency. Read more: 20.4.6 Load tests and the deployment runbook
- Speculative decoding: drafting several tokens cheaply and verifying them with one target forward pass, keeping the longest acceptable prefix. Read more: 23.9 Speculative decoding in the engine
- Server-Sent Events (SSE): a
text/event-streambody ofdata: ...events, each terminated by a blank line. Read more: 23.1 Your first endpoint: a std-only Rust HTTP/1.1 + SSE server - OTLP: the OpenTelemetry Protocol for exporting telemetry, here as an HTTP POST to
/v1/traces. Read more: 11.1 One trace from gateway to engine in Systems Engineering - model runner: the component that loads a checkpoint and runs one batched forward step, writing K and V into the pool and returning last-token logits. Read more: 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32
- chunked prefill: prefilling a prompt over several steps in pieces of at most
prefill_chunktokens, mixed with decodes. Read more: 23.4 Chunked prefill (mixed prefill + decode batches) - Regression gate: a check that fails a head run only when it is worse than the base by more than a budget and the difference is unlikely under noise. Read more: 23.12 Run comparison and the regression gate
- prefix cache: a store of finished requests’ full KV blocks, reused by later requests whose prompts begin with the same tokens. Read more: 23.5 Block manager with prefix cache (none, hash, radix)
- Constrained decoding: masking, at every step, every token that would take the output outside an allowed language. Read more: 23.10 Tool calls and constrained decoding
- Permutation test: a test that compares the observed statistic difference with its distribution over random relabelings of the pooled samples. Read more: 23.12 Run comparison and the regression gate
- bigram model: a language model that predicts the next token from the current token alone, stored as a table. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- 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
- Block pool: one slab of fixed-size KV blocks handed out by id. Read more: 21.8 A paged KV block pool in C
- PCG32: a permuted congruential generator with 64-bit state and an odd stream increment, producing 32-bit outputs from the old state. Read more: 23.1 Your first endpoint: a std-only Rust HTTP/1.1 + SSE server
- chat template: the model’s own Jinja template that turns
messagesinto the exact text format it was trained on. Read more: 23.6 tl-serve: OpenAI-compatible HTTP + SSE on tokio/hyper - bounded admission: a fixed-capacity command queue filled with
try_send, so a full queue is an immediate 429. Read more: 23.6 tl-serve: OpenAI-compatible HTTP + SSE on tokio/hyper - Service Level Objective (SLO): a target for a defined measure of service behavior over a specified window. Read more: Chapter 13: Engineering Acronyms in Software Engineering
- OTLP/HTTP JSON: the OpenTelemetry export format used here, one
ExportTraceServiceRequestPOSTed to/v1/traces. Read more: 23.8 Serving metrics and tracing - N-gram draft: a draft that picks, token by token, the most frequent continuation of the last few tokens in the context, ties to the lowest id. Read more: 23.9 Speculative decoding in the engine
- Accept-or-resample: accept a drafted when , else sample from the residual; the emitted token’s law is exactly . Read more: 23.9 Speculative decoding in the engine
- Token mask: the set of token ids whose full byte sequence keeps the DFA live from the current state, plus EOS in accepting states. Read more: 23.10 Tool calls and constrained decoding
- Byte trie: a prefix tree over the vocabulary’s bytes that shares mask walks between tokens and prunes dead subtrees. Read more: 23.10 Tool calls and constrained decoding
- Coordinated omission: the measurement error of a closed-loop client that stops sending during a stall and so records it once instead of in every request it delayed. Read more: 23.11 An open-loop load generator
- TTFT (time to first token): time from a request’s arrival to its first generated token. Read more: 23.4 Chunked prefill (mixed prefill + decode batches)
- ITL: inter-token latency, the gap between consecutive content chunks of a stream. Read more: 23.11 An open-loop load generator
- TPOT (time per output token): time between successive tokens of a running request, about one step. Read more: 23.4 Chunked prefill (mixed prefill + decode batches)
- Log-linear histogram: a histogram with 128 equal buckets per power of two, giving at most 1/128 relative error in fixed memory. Read more: 23.11 An open-loop load generator
The chapter grows the engine in two movements. It opens with the smallest server that can possibly work: a std-only HTTP/1.1 and SSE server, with no async runtime and no dependencies, serving the byte bigram and emitting one hand-written OTLP span per request. That first endpoint fixes the API and the streaming format. The rest of the chapter rebuilds the engine behind that same API on tokio and hyper, one capability at a time: a real model runner and sampler, a batching scheduler, chunked prefill, the block manager, the production server, disaggregation across engines, observability, speculation, and tool calls. The last two sections step outside the engine to measure it: an open-loop load generator in Go and a statistical regression gate built on its reports.
Learning objectives
- Serve streamed completions over HTTP and SSE, first with only the standard library and then on tokio and hyper, behind one OpenAI-compatible contract.
- Schedule many sequences at once with continuous batching, chunked prefill, priorities, and preemption, over a paged KV pool with a prefix cache.
- Split prefill and decode across engines, moving only the KV blocks the receiver lacks, without leaking blocks on any error path.
- Expose contract-exact Prometheus metrics and W3C-propagated OTLP traces for every request.
- Speed up decoding with exact speculative verification, and guarantee schema-valid tool calls with constrained decoding.
- Measure the engine honestly with an open-loop load generator, and gate regressions with a permutation test.
Before you begin
Section titled “Before you begin”You should be comfortable reading Rust and know how HTTP and server-sent events work; the Rust and HTTP and SSE primers in Programming and Algorithms cover both, and the later sections also lean on the primers for async Rust and tokio, Protocol Buffers and gRPC, and Go. Many sections port a Python reference from the inference chapter, so having read it helps. Two contracts frame the whole chapter: the API in openai-subset.v0.yaml (and its later v1), and the engine role in spec/cli-roles.md.
In this chapter
Section titled “In this chapter”- Your first endpoint: a std-only Rust HTTP/1.1 and SSE server. The smallest working engine: hand-parsed HTTP, streamed SSE completions from the byte bigram, and one OTLP span per request, with no dependencies at all.
- The model runner and sampler. A Candle runner for Llama-family and bigram models (with int4 weights), the Rust KV cache and block pool, and the sampler with its PCG32 generator, held to the Python reference.
- Continuous batching. A scheduler that admits and retires sequences every step, with priorities and preemption, so the batch stays full.
- Chunked prefill. Splitting long prompts into chunks that share a batch with decodes, so one long prompt no longer stalls every stream.
- The block manager and prefix cache. Allocating KV blocks per sequence and reusing shared prefixes, with no cache, a hash cache, or a radix cache.
- The OpenAI-compatible server on tokio. The production server,
tl-serve: the engine step loop behind hyper, chat templates, bounded admission, abort on disconnect, drain on SIGTERM, and health and readiness routes. - Disaggregated prefill and decode. Prefill on one engine and decode on another, with deduplicated KV transfer over gRPC, an exact RNG hand-off, and a heartbeat to the gateway’s registry.
- Serving metrics and tracing. A hand-written Prometheus registry with SLO histograms, and W3C trace propagation with OTLP/HTTP JSON export.
- Speculative decoding in the engine. Prompt-lookup and n-gram drafts, exact greedy and accept-or-resample verification, and KV rollback of rejected drafts.
- Tool calls and constrained decoding. A canonical regex-to-DFA compiler, JSON-schema grammars, token masks over a byte trie, and the OpenAI tool-calling surface with streamed deltas.
- An open-loop load generator. A Go load generator that avoids coordinated omission, measures TTFT, ITL, and TPOT from the stream, and records them in log-linear histograms.
- Run comparison and the regression gate. An optional section: a seeded one-sided permutation test that fails CI only when a run is both worse beyond a budget and significantly so.
- Inference stack: from tokens to an interface. Provider-neutral contracts and configuration across preparation, generation, structured output, interpretation, runtime, and delivery, with defaults, precedence, failure symptoms, and measurement methods.