LLM Inference & Serving at Scale
Generative & Agentic AI · Customize & Ship · Advanced · 28 min
Explain prefill and decode, size the KV cache, and design a serving stack that uses continuous batching, paged memory, prefix caching, speculative decoding and Mixture of Experts, on Bedrock or SageMaker AI.
A busy restaurant kitchen. Reading the order is quick (prefill). Cooking happens one plate at a time (decode). Every open order takes a spot on the counter (the KV cache). A good head chef starts a new order the moment a spot frees up, and hands out counter space only as each order actually needs it.
The idea in everyday words
Think of a library desk with limited space. Each student (request) spreads out notes for every page they have read so far (the KV cache). If every student reserves a whole table just in case, the room fills with empty tables and new students wait outside. If the librarian hands out space one small tray at a time, and gives a seat to the next student the moment anyone leaves, the same room serves many more people.
Two phases: prefill and decode
Every request to an LLM runs in two very different phases.
- Prefill: the model reads the whole prompt in one go. All prompt tokens are processed in parallel, which is lots of maths at once, so prefill is compute-bound (limited by how fast the chip multiplies).
- Decode: the model writes the answer one token at a time. Each step reads every weight from memory to do a small amount of maths for one token, so decode is memory-bandwidth-bound (limited by how fast bytes move from memory to the chip).
The three numbers every serving team watches:
| Metric | Meaning | Mostly set by |
|---|---|---|
| TTFT (time to first token) | how long until the user sees anything | queueing + prefill |
| TPOT (time per output token, also called inter-token latency) | the gap between tokens while it streams | decode |
| Throughput | total tokens per second for everyone together | batch size |
Total latency ≈ TTFT + TPOT × (output tokens − 1). This is why long answers feel slow even on a fast model: a 500-token answer at 20 ms per token takes about 10 seconds after the first token.
A useful back-of-the-envelope rule: at batch size 1, one decode step has to move all the weights through the chip. Weights of 16 GB on a chip with about 2,000 GB/s of memory bandwidth (an example figure; check your hardware's data sheet) means at least 16 / 2000 = 8 ms per token, however fast the maths units are.
weights_gb, bandwidth_gb_s = 16, 2000 # example numbers, not a specific product
tpot_ms = weights_gb / bandwidth_gb_s * 1000
ttft_ms, out_tokens = 300, 500
print("lower bound per token:", tpot_ms, "ms")
print("total time for 500 tokens:", round((ttft_ms + tpot_ms * (out_tokens - 1)) / 1000, 2), "s")
The KV cache: memory that grows with every token
To write token number t, attention needs the keys and values of all earlier tokens. Recomputing them each step would be wasteful, so servers keep them in GPU memory: the KV cache. (The lesson "Making Models Smaller & Faster" introduced it; here we size it for real traffic.)
KV cache bytes = 2 (K and V) × layers × KV heads × head size × tokens × sequences × bytes per value
Worked example for an 8B-class model (32 layers, 32 query heads but only 8 KV heads, head size 128, bf16 = 2 bytes):
- Per token: 2 × 32 × 8 × 128 × 2 = 131,072 bytes, about 0.13 MB.
- One 8,192-token conversation: 131,072 × 8,192 ≈ 1.07 GB.
- A 24 GB GPU holding 16 GB of weights has 8 GB left: 7 full-length conversations at most.
Attention variants trade cache size for quality:
| Variant | KV heads | Cache vs multi-head | Used by |
|---|---|---|---|
| Multi-head (MHA) | one per query head (e.g. 32) | 1× | early LLMs |
| Grouped-query (GQA) | a few shared groups (e.g. 8) | 4× smaller here | most current open models |
| Multi-query (MQA) | just 1 | 32× smaller here | some speed-focused models |
GQA is the usual sweet spot: query heads in a group share one key and one value head, so the cache shrinks a lot while quality stays close to MHA.
Units matter in interviews. This lesson uses GB = 10⁹ bytes, matching "8B params × 2 bytes = 16 GB". A GiB is 2³⁰ bytes, about 7% bigger, and GPU spec sheets often quote GiB. Say which one you use.
Batching that never waits: continuous batching and PagedAttention
Batching means one forward pass serves many requests, so each read of the weights is shared. Decode is memory-bound, so a batch of 32 costs barely more per step than a batch of 1. That is where serving throughput comes from.
Static batching waits for a batch to fill, runs it, and waits for the slowest request to finish before starting the next batch. A 5-token reply is stuck behind a 2,000-token essay.
Continuous batching (also called iteration-level scheduling) decides at every decode step: finished requests leave, waiting requests join. GPU slots never sit idle waiting for a straggler.
Memory is the real limit on batch size, and older servers wasted most of it:
- They reserved space for the prompt plus the maximum possible answer (max_tokens) up front, contiguous in memory. Most answers are shorter, so most of that space stayed empty.
- PagedAttention (the idea behind vLLM) borrows from operating-system virtual memory. The cache is split into small fixed-size blocks (for example 16 tokens). Each request has a block table that maps its tokens to blocks anywhere in memory, and gets a new block only when its last one fills. Waste drops to the last, partly filled block of each request.
When memory does run out, the scheduler pre-empts a request: it frees that request's blocks and re-queues it to be recomputed (or swaps the blocks to CPU memory).
Prefix caching goes one step further. Many requests start with the same system prompt or the same document. Their blocks for that shared prefix can be reused instead of recomputed: TTFT drops and memory is shared. vLLM calls this automatic prefix caching; SGLang's RadixAttention does it with a tree of prefixes. Put the stable part of your prompt first (instructions, tools, documents) and the changing part last, or the cache never hits.
Chunked prefill splits a very long prompt into pieces mixed in with other requests' decode steps, so one huge prompt does not freeze everyone's streaming.
Speculative decoding and Mixture of Experts
Speculative decoding: guess cheaply, check in bulk.
- A small, fast draft model proposes the next k tokens (say 4).
- The big target model checks all k in one forward pass (checking k tokens costs about the same as writing one, because decode is memory-bound).
- Tokens are accepted left to right; at the first rejection the target supplies its own token there and the rest are thrown away.
With the standard accept / reject rule, the output follows exactly the same distribution as the big model alone: it is a pure speed-up, not an approximation. If each draft token is accepted with probability a, one target pass yields on average (1 − a^(k+1)) / (1 − a) tokens: 3.36 tokens for a = 0.8, k = 4. Variants replace the draft model with extra prediction heads (Medusa, EAGLE) or with n-grams copied from the prompt (prompt lookup), which works well for editing and RAG answers.
Mixture of Experts (MoE): a big model that only uses part of itself per token.
- Each MoE layer has many expert feed-forward networks and a small router that sends each token to the top few experts (often 2 of 8, or 8 of 256).
- Total parameters decide memory: every expert must be loaded. Active parameters decide compute per token.
- Example: Mixtral 8x7B has about 47B total parameters but uses about 13B per token. DeepSeek-V3 has 671B total and about 37B active.
- So an MoE model gives the quality of a large model at roughly the per-token compute of a small one, but it still needs the memory of the large one. Large MoE models are often spread across GPUs with expert parallelism (different experts on different GPUs), and training adds a load-balancing objective so the router does not overuse a few experts.
Serving on AWS
Amazon Bedrock (fully managed, pay per token):
- On-demand inference: shared capacity, billed per input and output token, with account quotas on tokens and requests per minute.
- Cross-region inference: call an inference profile (model IDs like
us.<model-id>) and Bedrock routes requests to other Regions in that geography when one is busy. More headroom for traffic spikes, no extra code. - Prompt caching: mark cache checkpoints after the stable start of your prompt (system prompt, tools, long documents). Later requests that reuse that prefix are faster and cheaper on the cached part. The cache expires after a few minutes without use.
- Latency-optimized inference for some models (Converse
performanceConfig: {"latency": "optimized"}), batch inference for big offline jobs, and Provisioned Throughput (reserved model units) for steady high volume and for serving some custom models.
Amazon SageMaker AI (you pick the hardware and the server):
- Real-time endpoints with the large model inference (LMI) containers, which bundle optimised servers such as vLLM, TensorRT-LLM and the Neuron backend. You set tensor parallel degree, max batch size, KV cache dtype and more as configuration.
- Inference components pack several models onto one endpoint's instances; autoscale on concurrency or invocations per instance.
- Chips: NVIDIA GPU instances, AWS Inferentia2 (Inf2) for cost-efficient inference, and Trainium (Trn1/Trn2), all programmed through the AWS Neuron SDK for the AWS chips.
- Prefer full control? Run vLLM on Amazon EKS with GPU nodes and Karpenter.
How to choose: start on Bedrock on-demand with prompt caching; add cross-region inference for bursts; move to Provisioned Throughput or a SageMaker AI endpoint when volume is steady, you need a specific open-weights or custom model, or you must tune the server yourself.
Elsewhere: vLLM, SGLang and TensorRT-LLM are the common open-source servers; GCP offers Vertex AI and GKE, Azure offers Azure AI Foundry and Azure Machine Learning endpoints. Check each pricing page, prices change often.
Go deeper (engineer level)
Arithmetic intensity explains the two phases. Arithmetic intensity is maths done per byte moved. Decode at batch size B does about 2 FLOPs per weight per token, so intensity is roughly B FLOPs per weight byte in fp16 terms. A chip with, say, 1,000 TFLOP/s and 3 TB/s needs a few hundred operations per byte to be compute-bound, so decode stays memory-bound until the batch is in the hundreds. Prefill with a 2,000-token prompt is far past that point from the start.
Disaggregated serving. Prefill and decode want different things: big parallel bursts versus steady low-latency streaming. Some large deployments run them on separate GPU pools and ship the KV cache from the prefill pool to the decode pool, so a burst of long prompts never slows streaming. The cost is moving the cache across the network.
Shrinking the cache further. KV cache quantization (fp8 or int8 keys and values) halves it again. DeepSeek's multi-head latent attention (MLA) stores a small compressed latent per token instead of full keys and values. Sliding-window attention caps how far back some layers look. Each trades a little quality or complexity for memory.
Parallelism and the cache. With tensor parallelism over N GPUs, each GPU holds 1/N of the weights and of the KV heads, so per-GPU cache per token also drops by N (until N exceeds the number of KV heads). Pipeline parallelism splits layers instead. Interviewers like asking which you would pick for a 70B model on 8 GPUs in one server (tensor parallel within the server, because the GPU-to-GPU links are fast).
Speculative decoding at scale. Its gain shrinks at large batch sizes, because the GPU is no longer idle while waiting on memory. It shines for latency-sensitive, low-concurrency traffic.
SLOs drive the scheduler. Real servers admit requests with both TTFT and TPOT targets in mind: too big a batch raises everyone's TPOT; too small wastes the GPU. Track p50 and p99 of both, not just averages.
Step by step
- The setup:
After the weights, the GPU has 7 KV blocks of 4 token slots. Six requests wait: A (prompt 7, wants 2 tokens), B (2, 6), C (5, 3), D (6, 4), E (3, 3), F (4, 2). Mode: paged blocks + continuous batching.
- Step 1: prefill:
A gets 2 blocks, B 1 and C 2: blocks for the prompt plus the first new token. D needs 2 blocks plus 1 spare and only 2 are free, so it waits. All three write their first token.
- Step 2: grow on demand:
A's ninth token overflows its 2 blocks, so it gets exactly one more block. A has its 2 tokens and finishes, and its 3 blocks are freed at once.
- Step 3: join mid-flight:
D (2 blocks) and E (1 block) are admitted while B and C are still writing: continuous batching. Four requests decode together; C finishes and frees 2 blocks.
- Steps 4 to 5:
E and then D fill their last block and each gets one new block. E finishes in step 5. F still waits: it needs 2 blocks plus 1 spare.
- Step 6: batch empties:
B and D write their last tokens and free everything. F is admitted in step 7 and finishes in step 8.
- Compare:
8 steps in total. Reserving prompt + max_tokens up front takes 11 steps, static batching 10, both together 15. Same GPU, same requests: scheduling and memory layout decide throughput.
Code example
# Serving calculator: KV cache per token, speculative decoding and MoE memory vs compute.
def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_value):
return 2 * layers * kv_heads * head_dim * bytes_per_value
for name, kv_heads in [("multi-head (32 KV heads)", 32), ("grouped-query (8)", 8), ("multi-query (1)", 1)]:
per_tok = kv_bytes_per_token(32, kv_heads, 128, 2)
print(name.ljust(26), per_tok // 1024, "KiB per token |", round(per_tok * 8192 / 1e9, 2), "GB per 8k sequence")
# Speculative decoding: expected tokens per big-model pass, k drafts accepted with probability a
for a in [0.6, 0.8, 0.9]:
k = 4
print("acceptance", a, "->", round((1 - a ** (k + 1)) / (1 - a), 2), "tokens per pass")
# Mixture of Experts: memory follows TOTAL params, compute follows ACTIVE params (bf16 = 2 bytes)
total_b, active_b = 47, 13
print("MoE weights:", total_b * 2, "GB to load, compute per token like a", active_b, "B dense model")Complexity
- Time: O(1): a handful of multiplications and one division
- Space: O(1)
Interview tips
Explain prefill vs decode, which is compute-bound and which is memory-bound, and how each maps to TTFT and TPOT.
Size a deployment out loud: weights = params × bytes; KV cache = 2 × layers × KV heads × head dim × tokens × sequences × bytes; whatever is left decides the batch size.
Why does continuous batching plus PagedAttention raise throughput so much? (No waiting for stragglers; memory handed out in small blocks instead of reserved for max_tokens.)
Speculative decoding: why is it exact, and when does it stop helping? (Accept / reject keeps the target distribution; gains shrink at high batch sizes.)
Bedrock on-demand vs cross-region inference vs Provisioned Throughput vs a SageMaker AI endpoint with vLLM: pick one for a given traffic pattern and justify it.
Challenge: How Many Conversations Fit on One GPU?
Write max_concurrent_sequences(gpu_gb, model, seq_len) that returns how many full-length sequences of seq_len tokens can have their KV cache on one GPU at the same time.
model is a dict like:
{"weights_gb": 16, "layers": 32, "q_heads": 32, "kv_heads": 8, "head_dim": 128, "bytes_per_value": 2}
Rules:
- GB means 10⁹ bytes everywhere. All inputs are whole numbers.
- Memory left for the cache = (gpu_gb − weights_gb) × 10⁹ bytes.
- KV cache bytes per sequence = 2 × layers × kv_heads × head_dim × seq_len × bytes_per_value.
- Return the number of whole sequences that fit (round down). If the weights fill or exceed the GPU, return
0.
Example: max_concurrent_sequences(24, model_above, 8192) → 7 (8 × 10⁹ free bytes ÷ 1,073,741,824 bytes per sequence = 7.45).
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- PagedAttention paper: Efficient Memory Management for LLM Serving
- Fast Inference from Transformers via Speculative Decoding
- GQA: Training Generalized Multi-Query Transformer Models
- Mixtral of Experts paper
- vLLM documentation
- Amazon Bedrock: prompt caching
More in Customize & Ship
- Fine-Tuning & LoRA
- Making Models Smaller & Faster
- Multimodal & Image Generation
- Evaluation & Guardrails
- LLMOps: Shipping GenAI on the Cloud
Previous: Making Models Smaller & Faster · Next: Multimodal & Image Generation