Serving Models
The inference layer — whether to self-host, how to make a model fit, how to serve it fast, and how to survive failure.
Goal
Everything between “I have a model” and “my app can call it under load.”
The AI API taught you to make one call;
AI system design and
scaling to production surveyed the system
around it. This section is the layer in between — the inference layer — and it is the part
of the stack a managed API hides from you until the day you need it.
The layer
flowchart LR
App[Your app] --> GW[Gateway - routing and fallback]
GW --> LB[Queue and load balancer]
LB --> ENG[Serving engine - vLLM or TensorRT or SGLang]
ENG --> W[Model weights - quantized]
W --> GPU[GPU or CPU you chose]Read the diagram right to left and you have the order of this section: you pick the hardware,
you make the weights fit it, you put an engine in front of them, you put a queue in front of
the engine, and you put a router in front of everything.
In this section
The order is a dependency chain, not a menu — each page assumes the one above it:
If you never self-host, read 1 and 5. Page 1 tells you why staying on a managed API is
usually right, and page 5 applies to managed APIs unchanged — routing and fallback are the
two patterns every production AI app needs regardless of who runs the GPU.
What each layer buys you
| Layer | Lever | Typical gain | Cost of pulling it |
|---|
| Hardware choice | Own GPUs vs pay per token | Fixed cost beats per-token above a volume threshold | Ops, capacity planning, idle spend |
| Quantization | Numeric precision of the weights | 2–4× less VRAM, 1.5–3× faster decode | Some quality loss — must be measured |
| Serving engine | Memory layout and batching | 5–20× throughput over a naive loop | A new system to operate and tune |
| Queue + load balancer | Admission control across replicas | Survives spikes instead of collapsing | Added latency, more moving parts |
| Routing + fallback | Which model answers | Big cost savings, no single point of failure | Behaviour varies by which model served you |
Each row is only worth pulling when the row above it is already tuned. Quantizing a model
that a managed API could serve you is a classic case of solving the wrong problem.
Where to go next
Most teams should read page 1, conclude “stay on the API”, implement page 5, and come back to
pages 2–4 the year they actually need them.
Sources
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023) — arXiv:2309.06180
- Frantar et al., GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers (2022) — arXiv:2210.17323
- Lin et al., AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration (2023) — arXiv:2306.00978
- Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs (2023) — arXiv:2312.07104
1 - Local vs Cloud
Whether to run the model yourself — the three reasons that justify it, and the costs nobody puts in the spreadsheet.
The gate for this whole section.
Goal
Decide honestly whether to self-host an open model or stay on a managed API. This is the most
expensive decision in the section, it is usually made for the wrong reason, and every other
page here only matters if you answer “self-host.”
The three options
| Option | What you run | What you pay for | Scales by |
|---|
| Managed API | Nothing | Tokens | Someone else’s problem |
| Managed open model | Nothing; an open model on a provider’s GPUs | Tokens, or GPU-hours | Provider autoscaling |
| Self-hosted | Weights, engine, GPUs, the lot | GPU-hours, whether or not you use them | You, deliberately |
The middle row is the one people forget. Providers serve open weights per-token, which gets you
model choice and portability without owning a single GPU. It is the right first step away
from a closed API — not a jump straight to your own cluster.
flowchart LR
Start[Need inference] --> Q1{Must data stay in your network}
Q1 -->|yes| Self[Self-host]
Q1 -->|no| Q2{Do you need a custom fine-tuned model}
Q2 -->|yes| Q3{Will a provider host your adapter}
Q3 -->|no| Self
Q3 -->|yes| Managed[Managed open model]
Q2 -->|no| Q4{Is spend high and steady enough to beat GPU cost}
Q4 -->|yes| Managed
Q4 -->|no| API[Managed API]The three reasons that justify self-hosting
Only three hold up. If your reason is not on this list, it is probably a preference.
- Data residency — the text legally cannot leave your network. Regulated industries, some
government work, some EU data agreements. This is the only reason that is not a trade-off:
it is a constraint, and it settles the question by itself.
- Volume economics — per-token pricing is a rental. Above some steady throughput, owning
or reserving GPUs is cheaper. The key word is steady: GPUs bill while idle, so bursty
traffic destroys the arithmetic that made self-hosting look good.
- A model no one will serve you — a fine-tune, a merge, a research model, or one with a
licence that keeps it off managed platforms. See
Adaptation before assuming you need this.
Reasons that do not justify it: latency (a nearby managed region usually wins), cost at low
volume (it never wins), privacy as a feeling rather than a contract term (read the provider’s
zero-retention terms first), and “we want control” without naming what you would do with it.
Sizing the hardware
The first number is VRAM for the weights: roughly parameters × bytes per parameter.
At FP16 that is 2 bytes each, so a 7B model needs ~14 GB before anything else.
| Model size | FP16 | INT8 | INT4 |
|---|
| 7B | ~14 GB | ~7 GB | ~4 GB |
| 13B | ~26 GB | ~13 GB | ~7 GB |
| 70B | ~140 GB | ~70 GB | ~35 GB |
Then add the part that surprises people: the KV cache, the per-request memory holding
attention state for every token in flight. It grows with context length and with the number
of concurrent requests, and at high concurrency it can rival the weights themselves. A model
that “fits in 24 GB” may fit exactly one user.
This is why the next page exists: quantization is how you
buy back the headroom, and serving engines is how you
stop the KV cache from wasting it.
The costs nobody puts in the spreadsheet
The comparison is usually written as GPU-hours vs token spend, and that is the easy half:
- Idle time. A managed API costs nothing at 3 a.m. A reserved GPU costs the same at 3 a.m.
as at peak. Compare against your average utilisation, not your peak.
- Ops. Driver and CUDA versions, engine upgrades, OOM crashes at 2 a.m., capacity planning,
and a rollback story. This is a standing engineering cost, not a one-off setup.
- Model upgrades. Providers ship a better model and you change a string. Self-hosted, you
re-benchmark, re-quantize, re-tune, and redeploy.
- The quality gap. Open weights have closed much of the distance, but on the hardest
reasoning and tool-use work the frontier closed models are still ahead. Measure it on
your eval set before committing.
Strengths & limitations
- Strengths of self-hosting — data never leaves; fixed, predictable cost at steady high
volume; any model you like, including your own fine-tunes; no provider rate limits or
deprecation schedule.
- Limitations — real ops burden; idle GPUs bill anyway; you own every failure; the quality
ceiling is whatever open weights offer today; and the break-even point is far higher than
most teams estimate, because the spreadsheet usually omits everything in the section above.
Stay on the managed API until you can name which of the three reasons applies to you.
Where to go next
Sources
2 - Quantization
Trading numeric precision for memory and speed — FP16, INT8, INT4, and the GPTQ, AWQ, and GGUF formats that implement it.
How a model that needs 140 GB runs on a 48 GB card.
Goal
Understand the one lever that decides whether a model fits your hardware at all, what it costs
you in quality, and which of the confusing format names — AWQ, GPTQ, GGUF — you actually need.
What it is
A model’s weights are numbers. Training produces them at high precision; inference rarely
needs that precision. Quantization stores each weight in fewer bits — 16 down to 8, or 4 —
and dequantizes on the fly during the matrix multiplications.
You get three things at once, and pay for them in one currency:
flowchart LR
W[Weights at FP16] --> Q[Quantize to fewer bits]
Q --> M[Less VRAM]
Q --> S[Faster decode - less memory traffic]
Q --> C[Cheaper GPU fits the model]
Q --> L[Some quality loss]Speed is the part people miss. Token generation is memory-bandwidth bound, not
compute-bound: the GPU reads the entire weight set for every token it produces. Halve the
bytes and you roughly halve the reading, which is why INT4 decodes faster than FP16 on the
same card even though the arithmetic is no simpler.
The precision ladder
| Precision | Bits | Memory vs FP16 | Typical quality | Use it for |
|---|
| FP32 | 32 | 2× more | Reference | Training, almost never inference |
| FP16 / BF16 | 16 | baseline | The baseline everything is measured against | The default serving precision |
| FP8 | 8 | 0.5× | Near-lossless on modern hardware | Newer NVIDIA GPUs with native support |
| INT8 | 8 | 0.5× | Very close to baseline | The safe production choice |
| INT4 | 4 | 0.25× | Noticeable but often acceptable | Fitting a big model on a small card |
| INT3 / INT2 | 3–2 | 0.19× / 0.13× | Degrades badly | Experiments, not production |
BF16 vs FP16: same 16 bits, split differently. BF16 keeps FP32’s exponent range with less
mantissa, so it rarely overflows — it is the safer default where hardware supports it.
The honest shape of the curve: FP16 → INT8 costs almost nothing. INT8 → INT4 is where you start
trading real quality, and it hurts small models much more than large ones. A 70B model at INT4
generally beats a 13B model at FP16 on the same VRAM budget — when you must choose, take the
bigger model at lower precision.
This is the part that confuses people, because the three names are not the same kind of thing.
| Format | What it is | Runs on | Reach for it when |
|---|
| GPTQ | A post-training quantization algorithm, layer-by-layer, using a calibration set | GPU | You want mature 4-bit GPU support and broad tooling |
| AWQ | An algorithm that protects the ~1% of weights the activations care about most | GPU | You want better 4-bit quality than GPTQ, and fast kernels |
| GGUF | A file format / container, from llama.cpp, holding weights at many quantization levels | CPU, Apple Silicon, GPU offload | You are running locally, on a Mac, or without a CUDA GPU |
So GPTQ and AWQ answer “how were the weights rounded?”; GGUF answers “what file is this, and
what runs it?”. Comparing AWQ to GGUF is comparing a method to a container.
AWQ’s idea in one line: not all weights matter equally — a small fraction, identified by
looking at activation magnitudes rather than the weights themselves, carries most of the
quality, so scale those before rounding and the damage drops. In practice AWQ usually edges out
GPTQ at the same bit width, and both are far better than naive round-to-nearest.
GGUF k-quants: inside GGUF you will see names like Q4_K_M or Q5_K_S. Read them as
bits · k-quant · size variant — Q4_K_M is 4-bit, k-quant, medium. The k-quants mix
precisions across a tensor, spending more bits where they matter. Q4_K_M is the usual
recommended default; Q5_K_M if you have the room; below Q4 only if you must.
What to measure
Quantization is the one change in this section that can silently make your product worse, so
never ship it on vibes. Before and after, on the same inputs:
- Your eval set — task accuracy on real queries, not a public benchmark. See
Evaluation in practice.
- Tokens per second at your real concurrency, not single-stream.
- Peak VRAM including the KV cache under load, not just the weights at rest.
- Format adherence — quantized models degrade at
structured output and tool calling noticeably
earlier than they degrade at prose. If an agent
depends on clean JSON, test that specifically.
That last point is the practical trap: a 4-bit model that still writes fluent paragraphs may
have quietly become unreliable at emitting a valid tool call.
Strengths & limitations
- Strengths — 2–4× memory reduction turns an impossible deployment into a cheap one; faster
decode as a free side effect; INT8 is close to lossless; pre-quantized checkpoints mean you
usually download rather than compute anything.
- Limitations — quality loss is real, task-dependent, and worst on small models, long
contexts, and structured output; the format must match your serving engine and GPU;
quantizing yourself needs a calibration set and GPU hours; and it does nothing for the KV
cache, which is often what actually ran you out of memory.
Where to go next
Sources
3 - Serving Engines
vLLM, TensorRT-LLM, and SGLang — what an inference engine does that a naive loop cannot, and which to pick.
Why the same GPU serves 5 users or 100, depending on the software in front of it.
Goal
Understand what a serving engine actually does, why it is worth 5–20× the throughput of a
straightforward generation loop, and how to choose between the three engines that matter.
The two phases of a request
Every generation splits into two phases with completely different performance characters, and
almost everything an engine does follows from this split:
| Phase | What happens | Bound by | Cost shape |
|---|
| Prefill | Process the whole prompt at once, fill the KV cache | Compute | One big parallel pass |
| Decode | Emit one token, append to the KV cache, repeat | Memory bandwidth | Hundreds of tiny sequential passes |
Prefill is a sprint; decode is a long walk. During decode the GPU is mostly waiting on memory
while its compute units idle — which is exactly the gap an engine fills by running many
requests’ decode steps together.
flowchart LR
R[Request] --> P[Prefill - prompt to KV cache]
P --> D[Decode - one token at a time]
D --> D
D --> Out[Response]What an engine buys you
Three ideas do most of the work:
- Continuous batching. Static batching waits for a whole batch to finish before starting
the next, so one long generation holds nine short ones hostage. Continuous batching works at
token granularity: the moment a sequence finishes, a queued request takes its slot. This
alone is the single largest throughput win.
- PagedAttention. The KV cache used to be allocated as one contiguous block per request,
sized for the worst case — wasting most of it. vLLM borrowed virtual memory’s trick: split
the cache into fixed-size pages, allocate on demand, share pages between sequences with a
common prefix. Waste drops from ~60–80% to a few percent, and that recovered memory becomes
concurrency.
- Prefix reuse. Requests sharing a leading prefix — a long system prompt, a few-shot block,
a conversation history — can share its KV cache instead of recomputing it. When your prompts
have a big fixed head, this cuts prefill dramatically.
The result is that throughput is mostly a memory management problem, not a math problem. An
engine is worth far more than a faster GPU.
The three engines
| Engine | Core idea | Hardware | Strongest at | Cost |
|---|
| vLLM | PagedAttention + continuous batching | NVIDIA, AMD, others | General-purpose serving; the default | Little — easiest to adopt |
| TensorRT-LLM | Ahead-of-time compiled, hardware-specific kernels | NVIDIA only | Squeezing the last 20–40% of latency out of known hardware | A build step per model and per GPU; rigid |
| SGLang | RadixAttention — a prefix tree over the KV cache | NVIDIA, AMD | Heavy shared prefixes: agents, many-turn chat, structured programs | Newer, smaller ecosystem |
RadixAttention in one line: keep the cached prefixes in a radix tree so any new request
automatically reuses the longest matching prefix already in memory, instead of only handling
the one prefix you told it to cache. That is why it shines for
agent loops, where every iteration resends a
long and largely identical context.
Choosing one
flowchart TD
Start[Need to self-host] --> A{Do requests share long prefixes}
A -->|yes - agents or long system prompts| SG[SGLang]
A -->|no| B{Is latency the binding constraint}
B -->|no| V[vLLM]
B -->|yes| C{Fixed NVIDIA hardware and one model}
C -->|yes| TRT[TensorRT-LLM]
C -->|no| VStart with vLLM. It is the honest default: broad model support, good throughput out of the
box, and the least operational surprise. Move to TensorRT-LLM only when you have measured a
latency target you are missing on hardware you control and will not change soon. Reach for
SGLang when your workload is prefix-heavy, where it wins by construction rather than by tuning.
The knobs that matter
Whichever engine you pick, the same few dials decide behaviour:
- Max concurrent sequences — how many requests share the GPU. Too high and per-user latency
collapses; too low and the GPU idles.
- KV cache memory fraction — how much VRAM the cache may claim. Raising it buys concurrency
and takes room the weights may need.
- Max context length — caps the worst-case cache per request. Advertising a 128k window you
cannot serve at concurrency is a common self-inflicted outage.
- Tensor parallelism — split one model across several GPUs when it will not fit on one.
Every one of these is the same trade: more concurrency, worse tail latency. Decide which
you are optimising before you touch them, and watch both in
observability.
Strengths & limitations
- Strengths — order-of-magnitude throughput over a naive loop; near-complete recovery of
wasted KV memory; OpenAI-compatible endpoints in all three, so your app code barely changes.
- Limitations — one more system to run, tune, and upgrade; throughput gains come from
batching, which raises single-request latency; model and quantization format support varies
per engine; and a compiled engine like TensorRT-LLM must be rebuilt for every model and GPU
change, which is a real release-process cost.
Where to go next
Sources
4 - Load Balancing & Queuing
Going from one replica to many — admission control, backpressure, cache-aware routing, and autoscaling on the right signal.
The front door, and what it does when too many people arrive.
Goal
Keep a fleet of model replicas fast and honest under bursty traffic: decide what to admit, what
to queue, what to reject, and which replica each request should go to. This page deepens
§Queues and async for the self-hosted case.
Why the usual load balancer is wrong here
A web load balancer assumes requests are short, cheap, and interchangeable. Model requests are
none of those:
| Assumption | Reality for inference |
|---|
| Requests take milliseconds | They take seconds to minutes |
| Cost per request is uniform | A 200-token and a 100k-token prompt differ by 500× |
| Any replica is equally good | The replica holding your prefix in cache is far cheaper |
| CPU shows saturation | A GPU pinned at 100% may still have capacity, or none |
| Round-robin spreads load evenly | It spreads requests evenly and load terribly |
So the interesting decisions move from “pick a backend” to “should this run now, and where.”
flowchart LR
C[Clients] --> AD[Admission control]
AD --> Q[Queue]
Q --> RT[Cache aware router]
RT --> R1[Replica 1]
RT --> R2[Replica 2]
RT --> R3[Replica 3]
AD --> Rej[Reject fast with retry hint]Admission control and backpressure
The queue is not a place to hide an overload — an unbounded queue turns a capacity problem into
a latency problem, and every request in it eventually times out anyway. Serve work you can
finish:
- Bound the queue. Past the limit, reject immediately with a
429 and a Retry-After. A
fast, honest rejection is better service than a request that waits 90 seconds and then fails. - Set a queue-time budget. Drop requests that have waited longer than the client will, and
stop paying to compute answers nobody is still listening for.
- Estimate cost before admitting. Prompt tokens are known up front and
max_tokens bounds
the rest, so you can reject a request that cannot possibly fit your latency target. - Separate the queues. Interactive chat and overnight batch should not share a line. Give
each its own queue and concurrency budget, or the batch job will starve your users.
Backpressure must reach the caller. If your API accepts everything and silently buffers,
clients keep sending and the collapse is just delayed — and worse, invisible until it is total.
Cache-aware routing
This is the one big inference-specific win. Because a
serving engine caches KV state for prompt prefixes,
routing a request to the replica that already holds its prefix skips most of prefill.
- Sticky by prefix / session — hash the system prompt or conversation id and send matching
requests to the same replica. Enormous for multi-turn chat and
agent loops, where each turn resends a nearly
identical context.
- Least-pending, not round-robin — route by each replica’s queue depth and KV-cache
occupancy, the metrics that actually reflect load.
- Keep an escape hatch — stickiness that survives a hot replica becoming overloaded is a
bug. Fall back to the least-loaded replica when the preferred one is saturated.
Autoscale on the right signal
GPU utilisation is a poor scaling signal: a decode-bound replica shows high utilisation while
mostly waiting on memory. Scale on what users feel:
| Signal | Why it works |
|---|
| Queue depth / queue wait time | Directly proportional to the latency users experience |
| KV cache occupancy | The real capacity ceiling — when it is full, concurrency stops |
| Time to first token | The user-visible symptom of prefill contention |
Two cautions. GPU replicas take minutes to become ready — model download, load, and
warm-up — so scale on a leading indicator and keep warm headroom; reactive scaling arrives
after the spike is over. And scale down slowly: flapping a GPU pool is expensive in both
money and cold starts.
Strengths & limitations
- Strengths — a bounded queue plus admission control converts a total collapse into
graceful, honest degradation; cache-aware routing is close to free throughput on prefix-heavy
workloads; queue-depth autoscaling tracks user experience far better than CPU or GPU
utilisation.
- Limitations — every layer adds latency and another thing to operate; stickiness fights
even load balancing and needs an override; queue-time budgets and admission thresholds are
workload-specific and must be tuned with real traffic; and none of this helps if a single
replica is misconfigured — it will just distribute the problem evenly.
Where to go next
Sources
5 - Routing & Fallback
Sending each request to the right model, and keeping the app alive when that model is slow, expensive, or down.
The two patterns every production AI app needs — self-hosted or not.
Goal
Stop treating “the model” as one fixed dependency. Route each request to the cheapest model
that can handle it, and degrade gracefully when a model is overloaded, rate-limited, or gone.
This page deepens §Reliability and applies
unchanged whether you self-host or call a managed API.
The gateway
Both patterns live in one place: a model gateway between your app and every model, so that
“which model answers” becomes a policy decision rather than a constant scattered through your
code.
flowchart LR
App[App] --> GW[Model gateway]
GW --> CL{Classify request}
CL -->|simple| Small[Small cheap model]
CL -->|hard| Large[Large capable model]
Small --> V{Good enough}
V -->|no| Large
Large --> Err{Error or timeout}
Err -->|yes| FB[Fallback provider]
Err -->|no| Out[Response]
FB --> OutBuild this as a thin internal layer, not a rewrite: one function that takes a request and
returns a response, owning the model choice, the retry, and the fallback chain.
Routing — the right model per request
Most traffic does not need your best model. Classification, extraction, routing, summarising,
and reformatting are handled well by small models at a fraction of the cost and latency.
| Strategy | How it decides | Good for | Watch out for |
|---|
| Static by task | The call site says which model | Clear, distinct workloads | Drifts out of date as models change |
| Escalation / cascade | Try the cheap model, escalate if the answer fails a check | Mixed difficulty in one endpoint | Two calls when it escalates — the check must be cheaper than the saving |
| Classifier | A tiny model or heuristic labels difficulty first | High volume, wide difficulty spread | The classifier is now a thing to evaluate |
| Capability | Needs vision, tools, a long context, or JSON | Multimodal and agentic apps | Config sprawl |
Escalation is the highest-leverage version, and it lives or dies on the check: a
grader, a schema validation, a
confidence signal, or a retrieval-grounding test. If deciding costs as much as the big model,
the cascade has bought you nothing.
Two rules that keep this honest. Route on a measured difference, not a guess — build the
routing policy against your eval set, and
re-check it when models change. And log which model served each request, or you will be
debugging a quality complaint with no idea what produced the answer.
Fallback — surviving failure
Models fail in five distinguishable ways, and they do not want the same response:
| Failure | Right response |
|---|
| Rate limit (429) | Back off and retry, honour Retry-After, then shed to another provider |
| Timeout / slow | Cancel and retry once elsewhere — do not stack retries on a struggling endpoint |
| Server error (5xx) | Retry with jitter, then trip the circuit breaker |
| Content filter / refusal | Do not retry blindly — it will refuse again. Surface it or reroute deliberately |
| Bad output (invalid JSON) | Retry once with the error fed back; then fall back to a stricter or larger model |
The mechanics that make this safe:
- Retry with exponential backoff and jitter, capped. Uncapped retries during a provider
outage turn one failure into a self-inflicted flood.
- Circuit breaker. After repeated failures, stop calling that endpoint for a cooldown and
fail fast to the fallback. Hammering a dead provider only spends your own latency budget.
- Hedged requests, carefully. Firing a second call when the first exceeds its p95 cuts tail
latency but multiplies cost — cap it to a small fraction of traffic.
- Idempotency. Retries are only safe if a duplicated call cannot double-charge or
double-write. Pass a request key and make tool side effects idempotent, especially inside an
agent loop.
Graceful degradation
The last line of defence is deciding what “broken” looks like to the user. In descending order
of quality: cached answer → smaller or older model → non-AI path (keyword search instead of
RAG, a template instead of a generated summary) → an honest error
that says when to come back.
Never let one provider’s outage become a 100% outage. Design the degraded path before you
need it, and exercise it — an untested fallback is not a fallback.
Decide in advance which is worse for your users: a slower answer, a weaker answer, or no
answer. Every choice on this page follows from that.
Strengths & limitations
- Strengths — routing often cuts spend substantially with no quality loss on easy traffic;
fallback removes the single point of failure; the gateway centralises cost tracking, logging,
and model swaps in one place.
- Limitations — answers now vary by which model served them, which complicates evaluation
and reproducibility; cascades add latency when they escalate; every provider added is another
contract, prompt format, and behaviour to maintain; and prompts tuned for one model are
rarely optimal on its fallback, so quality on the degraded path must itself be measured.
Where to go next
Sources