Serving models and LLMs¶
What you'll be able to do¶
- Choose a serving pattern from a latency need and a traffic shape.
- Split a generative request's latency into queueing, prefill and decode, and estimate how GPU memory caps concurrency.
- Explain what batching, replicas, canaries, load shedding and cancellation each trade away.
Training and inference are different jobs¶
Training is one long job you can restart from a checkpoint and judge by throughput over days. Inference is a service: many small requests, each with a deadline, so the goal becomes latency per request. A training job fails loudly and you rerun it. A serving system is slow for 1% of requests, runs out of memory when two long prompts coincide, or runs the wrong model version while health checks stay green.
Pick a pattern from how fast the caller needs an answer and how traffic arrives.
| Pattern | Shape | Use when |
|---|---|---|
| Online | One request, one response | A person or service waits for the full result |
| Streaming | Partial results as they are produced | Output is slow to finish but useful early (chat, transcription) |
| Batch / offline | Score a whole dataset on a schedule | No one waits; you want the cheapest cost per item |
| Embedded | Model runs as a library inside your process | Tiny model, no network hop, simple deployment |
| Edge | Model runs on a device near the data | No reliable network, privacy, or very tight latency |
Prefer batch when no one is waiting. The Atlas includes an edge-inference IoT case for the last row.
The shape of a model service¶
The model server loads weights once at startup. Fetching a large file and moving it to the GPU can take long: the cold start. Loading per request is the classic bug. While loading, the process is alive but cannot serve. Liveness asks "should this process keep running?"; readiness asks "may I send it traffic now?". A health check that returns 200 before the weights load sends users to a server that cannot answer; a liveness check that fails during a slow load gets the process killed repeatedly.
In front sits an ordinary API (api design): validate input, cap prompt and output length, authenticate, apply rate limits, tag logs with a request id. Graceful shutdown matters because requests are long: report not-ready so traffic stops, finish in-flight requests, then exit. Otherwise deploys cut users off mid-answer.
Treat the model as a versioned artifact: immutable weights plus tokenizer, prompt template and generation settings, with the version recorded per replica. Package it in a container (Docker lesson) and keep secrets in configuration (config and secrets).
Where the time and memory go¶
For a generative model, one request's latency has three parts:
time to first token (TTFT) = queue time + prefill
total latency (N >= 1) = TTFT + (N - 1) x avg inter-token latency
Queue time is waiting for capacity. Prefill processes the whole prompt in parallel, grows with prompt length and ends by producing the first output token. Decode produces the remaining tokens one at a time, since each depends on the previous one. These are model-side approximations: end-to-end latency adds input processing (such as tokenizing) and transport. A longer prompt raises prefill time and KV cache use (below), and may raise decode time per token; a long output raises total time through many sequential steps. A streaming user feels TTFT; a caller awaiting complete JSON feels the total. Set targets on what your user feels (latency and throughput).
Memory sets how many requests run at once. The GPU holds the weights plus, per active request, a KV cache: the attention keys and values of earlier tokens, kept so decode does not recompute them. It grows with sequence length and with concurrent requests:
kv bytes = 2 x layers x kv_heads x head_dim x seq_len x batch x bytes_per_value
2 x 32 x 8 x 128 x 4096 x 1 x 2 = 536,870,912 bytes = 512 MiB per request
80 GiB GPU - 16 GiB weights = 64 GiB free; 64 GiB / 0.5 GiB = 128 requests
at 8192 tokens each: 1 GiB per request -> 64 requests
These are illustrative round numbers, not a product, and 128 is an upper bound (real servers also need activation memory). In this KV-only example, doubling every active sequence from 4096 to 8192 tokens halves that bound. It is the budgeting from how programs run, with a tighter ceiling.
Making it faster per dollar¶
Batching. A decode step often spends much of its time reading weights, a cost the whole batch shares. Take a toy cost model, 50 ms + 10 ms x batch size:
- Batch of 1: 60 ms, so 1000 / 60 = 16.7 requests per second.
- Batch of 8: 50 + 80 = 130 ms, so 8000 / 130 = 61.5 requests per second, about 3.7 times more.
The price is waiting. Static batching waits for a full batch: if one request arrives exactly every second, the first of 8 waits 7 seconds for the batch to fill. Dynamic batching releases a batch when it is full or the oldest request has waited max_wait. That bounds the wait for batch formation; a busy server can still add queue time after the batch is ready. Under light load batches leave by timeout, adding latency for little gain; under heavy load they fill fast and throughput rises. Continuous batching fixes another flaw: a static batch is held by its longest sequence. The server re-forms the batch every decode step, letting finished sequences leave and waiting ones join.
Quantization stores weights in fewer bits: smaller, often faster, at some risk to accuracy, so evaluate on your task. A prefix cache reuses the computed state of a repeated prompt start, such as a long system prompt. A response cache skips the model, and is valid only when the key covers every input that changes the answer: model version, template, parameters, user permissions (caching). Model parallelism (one model across GPUs) and speculative decoding (a small draft model proposes tokens, the large one verifies) only need names here.
Scaling and releasing¶
Run replicas behind a load balancer (load balancing). Request cost varies with prompt and output length, so prefer least in-flight work over round-robin. Scale on queue depth, in-flight requests or GPU utilization, not CPU, which can look idle while the GPU is saturated. A new replica must load weights and warm up, so for spiky traffic keep a warm pool of ready spares and accept the idle cost. Small models can share a GPU (multi-model serving).
Release a model like any risky change (CI/CD): canary it on a small share of traffic and compare quality, latency and errors, or use shadow traffic, copying real requests to the new version and discarding its answers. Keep the old version one command away, and plan a fallback (a smaller model, a cached answer, an honest error) (timeouts and retries).
Operating it under load¶
Export per model version: queue time, TTFT, inter-token latency, tokens per second, GPU memory and utilization, error rates (observability). Trace multi-step requests to find the slow step.
When demand exceeds capacity, an unbounded queue turns overload into timeouts for everyone. Load shedding rejects excess work early and keeps answering the rest (rate limiting). Add cancellation: when a client disconnects, stop generating, or the GPU keeps producing answers nobody reads. It is cooperative: the decode loop checks a flag between tokens.
Build or buy¶
| Question | Managed API | Self-hosted |
|---|---|---|
| Control (versions, fine-tuned weights) | Limited to what is offered | Full |
| Cost | Usually per use; reserved capacity adds fixed cost | Pays for provisioned compute, engineering and operations |
| Latency | Network hop; shared capacity | You control placement and batching |
| Privacy | Data usually leaves your boundary, under contract | Data can stay inside |
| Operations burden | Low | You own scaling, upgrades, on-call |
Neither is cheaper by rule. Compare measured cost per successful request at the expected load, including idle time and quality; either option can win. Weigh that with data location and custom-weight needs, and revisit as load changes.
For AI engineers¶
For AI engineers
You know how to call model(x); a service must make that call reliable and affordable. The load at the top of your notebook becomes a startup phase behind a readiness gate. Batch size becomes a latency-versus-throughput trade bounded by a max-wait. The out-of-memory error on a long input becomes a capacity plan: weights plus KV cache per request, with caps on prompt and output length. See LLM reliability and cost for the application side.
Common mistakes¶
- Loading the model inside the request handler, so every call pays the load.
- Ignoring cold starts, or autoscaling a GPU workload on CPU use: capacity arrives too late.
- Batching without a max-wait, so a request waits for company that never comes.
- Never cancelling, so abandoned requests keep burning GPU.
- Unbounded prompt and output length, so one request can consume the memory of many.
- No fallback when the model server is down.
Check yourself¶
Requests arrive every 200 ms at an idle server that handles a single request in well under 200 ms. Your batcher has max_batch_size 8 and max_wait 50 ms. What happens to latency, and what do you change?
No second request shows up in time, so each waits the full 50 ms and then runs alone: 50 ms more latency and no throughput gain. Lower max_wait, since the server is not saturated.
GPU replicas show 20% CPU, yet latency rises. What do you check, and what should the autoscaler watch?
Queue time, GPU utilization and GPU memory: the GPU is probably saturated or out of KV-cache room. Scale on queue depth, in-flight requests or GPU utilization.
Weights take 16 GiB and each request's KV cache is 1 GiB on a 48 GiB GPU. How many requests fit at most, and how many if every sequence doubles in length?
(48 - 16) / 1 = 32. If every request's sequence doubles, the cache is 2 GiB per request, so 32 / 2 = 16.
During a deploy, users see answers cut off mid-sentence. Which part of the service shape was skipped?
Graceful shutdown: report not-ready, stop taking new work, finish in-flight requests, then exit.
Lab¶
In code/serving-models/, build the pieces around model(x) as a deterministic simulation with an injected clock: a dynamic batcher, a one-server simulator showing batching raise latency under light load and throughput under heavy load, KV-cache and concurrency arithmetic, a readiness gate with draining, and a cancellable token loop. Run: cd code/serving-models && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Interactive: Designed to Scale - latency and throughput
- Kubernetes documentation for liveness and readiness probes.
- Google SRE books for overload and load shedding.
- Software Engineering Handbook, ch. 4 "Từ một server đến scalable".
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.

