Simple definition#
Inference is running a trained model to produce output. For an LLM it has two phases: reading the whole prompt (prefill) and then generating the answer one token at a time (decode). Almost every latency, throughput and cost decision in an AI system traces back to these two phases.
The two phases of a request#
sequenceDiagram
participant App as Application
participant GW as Inference server
participant GPU as GPU
App->>GW: prompt of 3,000 tokens
GW->>GPU: Prefill: process all 3,000 tokens in parallel
Note over GPU: Builds the KV cache.<br/>Compute-bound. Sets time to first token.
GPU-->>App: first output token
loop Decode, one token per step
GW->>GPU: next step uses KV cache
GPU-->>App: next token, streamed
end
Note over GPU: Memory-bandwidth-bound.<br/>Sets tokens per second.
GPU-->>App: stop token or max tokens
- Prefill processes the input tokens in parallel. Long prompts mean a longer wait before the first token.
- Decode generates output tokens one at a time; each step depends on the previous one. Long answers mean a long total time.
That is why output tokens cost more and take longer than input tokens, typically 3–5× the price per token.
Latency metrics#
| Metric | Meaning | What drives it |
|---|---|---|
| TTFT — time to first token | Wait before anything appears | Prompt length, queueing, model size, network |
| TPOT / ITL — time per output token | Speed of generation | Model size, hardware, batch load |
| Tokens per second (per request) | 1 / TPOT | Same as above |
| End-to-end latency | TTFT + output tokens × TPOT | Mostly output length |
| Throughput | Total tokens per second across all users | Batching, hardware, concurrency |
Worked example. TTFT 0.5 s, 60 tokens/s, 600-token answer → 0.5 + 600/60 = 10.5 s. Halving the answer length saves 5 s; a model twice as fast saves 5 s. Asking for concise output is often the cheapest latency win.
KV cache#
During decode, each new token needs the keys and values of every earlier token for attention. Recomputing them every step would be wasteful, so the server keeps them in GPU memory: the KV cache.
- It grows with sequence length × batch size and is often the main consumer of GPU memory.
- Long contexts and many concurrent users compete for the same cache memory, which limits concurrency.
- Techniques such as PagedAttention (vLLM) store the cache in pages, like virtual memory, to cut waste and fit more concurrent requests.
Prompt caching#
Many requests share a long, identical prefix: the same system prompt, tool definitions or document. Prompt caching (also called prefix caching) stores the prefill result for that prefix and reuses it.
flowchart LR
subgraph Prompt
direction LR
A["System prompt + tool definitions<br/>STATIC, cached"] --> B["Reference documents<br/>static per session, cached"] --> C["Conversation + new user message<br/>DYNAMIC"]
end
A -.->|"cache hit: up to ~90% cheaper, faster TTFT"| X[(Provider cache)]
Design rule: put stable content first and variable content last. A timestamp or user name at the top of the system prompt breaks the cache for every request.
Throughput: batching#
A GPU is far more efficient when processing many requests together. Continuous batching (in-flight batching) adds new requests to the running batch as soon as others finish, instead of waiting for a whole batch to complete. It is the default in serving engines such as vLLM, TensorRT-LLM, SGLang and Hugging Face TGI.
Trade-off: larger batches give higher total throughput but each request’s TPOT gets slightly worse.
Making models smaller and faster#
For the mechanics behind these — compute- vs bandwidth-bound workloads, MFU/MBU, speculative decoding, KV-cache sizing, continuous batching and parallelism — see inference optimisation.
| Technique | Idea | Trade-off |
|---|---|---|
| Quantization | Store weights in 8-bit or 4-bit instead of 16-bit (INT8, FP8, INT4, GPTQ, AWQ, GGUF) | 2–4× less memory and faster; small quality loss, larger at 4-bit |
| Distillation | Train a small “student” model to imitate a large “teacher” | Much cheaper per call; needs training and data |
| Speculative decoding | A small draft model proposes several tokens; the big model verifies them in one step | 2–3× faster decode, same output quality |
| Smaller model / routing | Send easy requests to a small model | See model selection |
GPU memory estimate for self-hosting. Weights ≈ parameters × bytes per parameter. A 70B model in FP16 (2 bytes) needs ~140 GB just for weights — two 80 GB GPUs before any KV cache. In INT4 (0.5 bytes) it needs ~35 GB.
Hosted API or self-hosted?#
flowchart TB
Q{"Where should inference run?"}
Q --> A["Provider API<br/>Anthropic, OpenAI, Google"]
Q --> B["Cloud-managed<br/>AWS Bedrock, Azure AI Foundry, Google Vertex AI"]
Q --> C["Self-hosted open-weight<br/>Llama, Mistral, Qwen, Gemma on vLLM or similar"]
A --- A1["Fastest start, frontier quality,<br/>pay per token, data leaves your network"]
B --- B1["Same models inside your cloud account,<br/>enterprise controls, regional data residency"]
C --- C1["Full control and data isolation,<br/>you run GPUs, scaling and upgrades"]
Most enterprises start with a cloud-managed or direct API, and self-host only for data-sovereignty requirements, very high steady volume, offline use or specialised fine-tuned models.
Rate limits and capacity#
Providers limit requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM). A design that works for one user can fail at 500 concurrent users.
- Estimate peak tokens per minute: peak requests/min × average tokens per request.
- Handle HTTP 429 with exponential backoff and jitter; respect
retry-after. - Queue non-interactive work and use batch APIs (typically ~50% cheaper, results within hours).
- Spread load across regions or providers through an AI gateway.
- Provisioned throughput (reserved capacity) gives predictable latency for steady high volume.
Estimating cost#
Formula: monthly cost = requests per month × (input tokens × input price + output tokens × output price).
Worked example — internal RAG assistant
| Input | Value |
|---|---|
| Users | 2,000 employees, 10 questions/day, 22 working days → 440,000 requests/month |
| Input tokens per request | 500 system + 4,000 retrieved context + 500 history/question = 5,000 |
| Output tokens per request | 400 |
| Illustrative prices | $3 per million input, $15 per million output |
Input: 440,000 × 5,000 = 2.2B tokens → $6,600. Output: 440,000 × 400 = 176M tokens → $2,640. ≈ $9,240/month, before caching.
Levers, roughly in order of impact: shorter retrieved context (better retrieval and reranking), prompt caching for the static prefix, routing simple questions to a cheaper model, response caching for repeated questions, and concise output instructions.
Common mistakes#
Review questions#
Why is time to first token different from total latency? TTFT is dominated by prefill (prompt length and queueing); total latency adds output tokens × time per token, which usually dominates. Long answers are slow even on fast models.
What is the KV cache and why does it limit concurrency? The stored attention keys and values for every token processed so far, kept in GPU memory so decode does not recompute them. Its size grows with context length and the number of concurrent sequences, so it caps how many requests fit on a GPU.
How would you reduce LLM latency in a chat application? Stream responses; shorten prompts and outputs; use prompt caching with a stable prefix; route simple requests to smaller, faster models; cache frequent answers; run independent calls in parallel; place inference in a nearby region.
How do you estimate the monthly cost of an LLM feature? Requests per month × (input tokens × input price + output tokens × output price), with realistic token counts including system prompt, retrieved context and history. Then apply caching, routing and batch discounts.
When would you self-host a model? Strict data residency or air-gapped environments, very high steady volume where GPUs are cheaper than per-token pricing, need for a fine-tuned open-weight model, or latency control at the edge. Otherwise managed APIs are cheaper to operate.
What is quantization? Storing model weights at lower numerical precision (8-bit or 4-bit) to reduce memory and speed up inference, with a small loss in quality.
Summary#
- Prefill reads the prompt in parallel (sets TTFT); decode writes one token at a time (sets total time).
- Output tokens are slower and pricier than input tokens; concise answers save both.
- KV cache, batching and quantization determine self-hosted capacity.
- Prompt caching rewards a stable prefix.
- Cost = requests × tokens × price; retrieval quality and routing are the biggest levers.
References#
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM), 2023.
- Leviathan et al., Fast Inference from Transformers via Speculative Decoding, 2023.
- Anthropic, Prompt caching.