Building an LLM Inference Server from Scratch: KV Cache, Continuous Batching and vLLM

vLLM serves 9,370 tokens per second on an 8 GB GPU. My server, built from scratch, manages 788. That's a 12× gap at peak load (about 4× with a single request). Because I built each piece myself and benchmarked it along the way, I can point to the main sources of that gap.
This post walks through building an LLM inference server one optimization at a time: no KV cache, then KV cache, then static batching, then continuous batching with live cache editing, then admission control. Each step is benchmarked on the same hardware with the same model, so you can see exactly what each technique buys you — and what it doesn't.
The goal isn't to build a production server. It's to understand why production servers are built the way they are.
Setup
Everything runs on one NVIDIA GPU with about 8 GB of VRAM, serving Qwen2.5-0.5B. The server is a FastAPI app. Each benchmark uses closed-loop load testing: each client sends a new request the moment its previous one finishes. We vary the number of concurrent clients and measure four things:
- TTFT — time to first token (how long the user waits before text starts streaming)
- TPOT — time per output token (how fast the stream flows once it starts)
- Throughput — total tokens per second across all requests
- Tail latency — p95 and p99 total request time
All results use max_length=64. The full code is at github.com/NotShrirang/inference-from-scratch.
Step 1: The Baseline (No Cache, No Batching)
The simplest possible server: take a prompt, generate tokens one at a time, return the result. No KV cache, no batching, no streaming. Each new token requires reprocessing the entire sequence from scratch.
Baseline: the model reprocesses the entire sequence for each new token
1class ChatModel:
2 def generate(self, prompt: str, max_length: int = 64):
3 input_ids = self.tokenizer.encode(prompt)
4
5 for _ in range(max_length):
6 # Reprocess ENTIRE sequence every step
7 outputs = self.model(input_ids)
8 next_token = sample(outputs.logits[:, -1, :])
9 input_ids = torch.cat([input_ids, next_token], dim=-1)
10
11 if next_token == self.tokenizer.eos_token_id:
12 break
13
14 return self.tokenizer.decode(input_ids)This is deliberately terrible. At step 50, the model processes all 50 previous tokens just to produce token 51. No streaming either: the user waits for the full response.
How bad is it? Take one forward pass over L tokens, with hidden size d. Each layer does two kinds of work:
- Projections and MLP (the matrix multiplies with the weights): about L·d², linear in L.
- Attention scores (every token attends to every token): about L²·d, quadratic in L.
The baseline runs that full pass again for every new token, with L = 1, 2, …, N. Summing over all steps, the weight work grows as N²·d² and the attention work as N³·d: quadratic and cubic in sequence length. A KV cache (Step 2) processes only the new token at each step, which brings these down to N·d² and N²·d. At the lengths in this post (around 100 tokens, while Qwen2.5-0.5B has d = 896), L stays well below d, so the weight work dominates and the waste you'd actually see is closer to the quadratic term. The cubic attention term takes over for long sequences.
I didn't benchmark this step: it has no streaming endpoint, so there is no TTFT or TPOT to measure. The first token arrives only with the whole response. It exists only to establish the floor.
Step 2: KV Cache
The attention mechanism computes key and value projections for every token at every layer. For token 51, the keys and values for tokens 1–50 are identical to what we computed at token 50 — we're redoing work. The KV cache stores these projections so each step only processes the new token:
KV Cache: cached tokens (blue) are skipped — only the new token (green) is processed
1def generate_stream(self, prompt: str, max_length: int = 64):
2 input_ids = self.tokenizer.encode(prompt)
3 past_key_values = None # KV cache starts empty
4
5 for i in range(max_length):
6 outputs = self.model(
7 input_ids if i == 0 else input_ids[:, -1:], # full prompt or just last token
8 past_key_values=past_key_values,
9 use_cache=True,
10 )
11 past_key_values = outputs.past_key_values # store for next step
12
13 next_token = sample(outputs.logits[:, -1, :])
14 input_ids = torch.cat([input_ids, next_token], dim=-1)
15
16 yield next_token # stream each token as it's generated| Concurrency | Throughput | TTFT p50 | TPOT p50 | e2e p99 |
|---|---|---|---|---|
| 1 | 59 tok/s | 23 ms | 12 ms | 1.44 s |
| 2 | 75 tok/s | 66 ms | 24 ms | 1.81 s |
| 4 | 79 tok/s | 89 ms | 47 ms | 3.47 s |
| 8 | 83 tok/s | 207 ms | 90 ms | 6.43 s |
| 16 | 83 tok/s | 379 ms | 179 ms | 12.5 s |
The flat throughput is the key observation. With the KV cache, a single request is fast — TTFT drops to 23 ms. But with 16 concurrent requests, throughput barely moves (59 → 83 tok/s) while TPOT grows 15× and end-to-end latency hits 12.5 s. The GPU sits idle while Python shuffles between requests.
Lesson: The KV cache eliminates redundant computation within a single request. It does nothing for concurrency. For that, we need batching.
Step 3: Static Batching
Instead of processing one prompt at a time, batch N prompts together into a single forward pass. The GPU reads the model weights once and applies them to all sequences simultaneously:
Static batching: all requests processed in a single forward pass — GPU reads weights once
1def generate_batch(self, prompts: list[str], max_length: int = 64):
2 # Left-pad so all sequences align on the right (generation end)
3 inputs = self.tokenizer(
4 prompts, padding=True, padding_side="left",
5 return_tensors="pt"
6 ).to(self.device)
7
8 past_key_values = None
9 for i in range(max_length):
10 outputs = self.model(
11 inputs["input_ids"] if i == 0 else new_tokens,
12 attention_mask=inputs["attention_mask"],
13 past_key_values=past_key_values,
14 use_cache=True,
15 )
16 past_key_values = outputs.past_key_values
17 new_tokens = sample(outputs.logits[:, -1, :])
18
19 # Extend attention mask for the new position
20 inputs["attention_mask"] = torch.cat([
21 inputs["attention_mask"],
22 torch.ones(len(prompts), 1, device=self.device)
23 ], dim=1)| Batch Size | Throughput | Per-sequence | Median time |
|---|---|---|---|
| 1 | 98 tok/s | 98 tok/s | 0.65 s |
| 2 | 148 tok/s | 74 tok/s | 0.87 s |
| 4 | 321 tok/s | 80 tok/s | 0.80 s |
| 8 | 589 tok/s | 74 tok/s | 0.87 s |
| 16 | 1,204 tok/s | 75 tok/s | 0.85 s |
| 32 | OOM | — | — |
This is the most important insight in the whole project: token generation is memory-bandwidth bound, not compute bound. The GPU reads the model weights from memory once per step regardless of how many sequences are in the batch. Adding more sequences is essentially free — until you run out of memory for the KV caches. Per-request time stays flat at ~0.85 s while throughput scales ~12×.
But static batching has a problem: it needs all N prompts upfront. In a real server, requests arrive at different times and finish at different times. A batch that waits for a slot to free up wastes the GPU.
Step 4: Continuous Batching
This is the big one. Continuous batching (also called in-flight batching, or iteration-level scheduling in the Orca paper) is how vLLM, TGI and TensorRT-LLM keep the GPU busy. A background engine runs the model in a loop. New requests join the batch as they arrive; finished requests leave without stalling the rest:
Continuous batching: the rightmost column is the current forward pass — all active requests decode there simultaneously
1class BatchingEngine:
2 """Background loop that drives the model for all active requests."""
3
4 async def _run(self):
5 while self._running:
6 # Admit new requests from the waiting queue
7 while self._waiting and len(self._batch) < self.batch_size:
8 req = self._waiting.popleft()
9 self._prefill(req) # prefill alone, splice KV into batch
10 self._batch.append(req)
11
12 if not self._batch:
13 await asyncio.sleep(0.01) # nothing to do
14 continue
15
16 # One forward pass for the whole batch
17 self._step()
18
19 # Remove finished requests, free their KV rows
20 self._evict_finished()The Hard Part: Editing the KV Cache
In static batching, the cache is built once for a fixed set of prompts. Continuous batching means the cache must change shape while the model is running: a new request's cache must be spliced in, and a finished request's row must be removed. This is the core engineering challenge.
1def _prefill(self, req):
2 """Prefill a single new request and splice its KV cache into the batch."""
3 outputs = self.model.forward(
4 req.input_ids.unsqueeze(0),
5 use_cache=True,
6 )
7 new_cache = outputs.past_key_values
8
9 if self._cache is None:
10 self._cache = new_cache
11 return
12
13 # The new request's cache may be shorter — left-pad it to match
14 for layer in range(len(self._cache)):
15 for kv in (0, 1): # keys, values
16 existing = self._cache[layer][kv] # [batch, heads, seq, dim]
17 incoming = new_cache[layer][kv] # [1, heads, seq', dim]
18
19 pad = existing.shape[2] - incoming.shape[2]
20 if pad > 0:
21 incoming = F.pad(incoming, (0, 0, pad, 0)) # left-pad seq dim
22
23 # Concatenate on the batch dimension
24 self._cache[layer][kv] = torch.cat(
25 [existing, incoming], dim=0
26 )The Hardest Bug: One Line
The first version crashed with OOM after a few hundred requests. Memory climbed to 7.6 GB on a 0.5B model. The cause:
1# Before (broken): autograd saves the entire KV cache at every step
2def forward(self, input_ids, **kwargs):
3 return self.model(input_ids, **kwargs)
4
5# After (fixed): one decorator, memory stays flat
6@torch.no_grad()
7def forward(self, input_ids, **kwargs):
8 return self.model(input_ids, **kwargs)Without @torch.no_grad(), PyTorch saves the full computational graph at every step — including the KV cache that's passed back in as input. Memory grows without bound. model.eval() does not disable gradient tracking — it only changes dropout and batch-norm behavior. This was the hardest bug in the project, fixed in one line.
A Subtle Position Bug
After splicing a new request's KV cache into the batch, positions must be recomputed from the attention mask. If they're wrong, RoPE applies incorrect rotary encodings. The model generated "Paris is" instead of "Paris." — no crash, no NaN, just a quietly wrong answer. The fix: recompute position_ids from the attention mask at every forward pass.
Results
| Concurrency | v1 tok/s | Fixed tok/s | TPOT p50 | TTFT p50 |
|---|---|---|---|---|
| 1 | 47 | 90 | 7 ms | 114 ms |
| 2 | 80 | 146 | 11 ms | 34 ms |
| 4 | 145 | 258 | 13 ms | 43 ms |
| 8 | 286 | 459 | 14 ms | 48 ms |
| 16 | 389 | 724 | 19 ms | 60 ms |
| 32 | 383 | 774 | 18 ms | 1.19 s |
| 64 | 382 | 788 | 18 ms | 3.53 s |
The cache-editing and no_grad fixes doubled peak throughput from 389 to 788 tok/s. TPOT stays under 20 ms from 1 to 64 requests (step 2 TPOT grew 15× from 1 to 16 requests). Past the batch size of 16, extra load adds only waiting time — TTFT grows linearly.
Step 5: Admission Control
The batch holds 16 requests. Past that, new requests wait in a queue, and in Step 4 that queue had no limit: at 256 concurrent requests the server still answered everything, but p99 latency reached 32 seconds. The fix is a bounded queue that rejects extra requests with HTTP 429:
1class BatchingEngine:
2 def __init__(self, model, batch_size=16):
3 self.batch_size = batch_size
4 self.max_waiting = 4 * batch_size # bounded queue
5
6 def submit(self, request):
7 if len(self._waiting) >= self.max_waiting:
8 raise HTTPException(
9 status_code=429,
10 detail="Server at capacity. Try again later."
11 )This doesn't increase throughput. With 16 running and 64 waiting, the server holds 80 requests; anything beyond that gets a 429 right away instead of waiting. At 128 concurrent requests, 2,323 requests were rejected; at 256, 1,294 were. The requests that are accepted keep a steady TPOT (22–30 ms), and p99 latency at 256 drops from 32 s to 21 s. The value isn't speed. It's a clear contract: the server tells you when it's full instead of making everyone wait.
The Capstone: My Server vs vLLM
Same model (Qwen2.5-0.5B), same prompts, same measurements. Each server gets the full GPU to itself — vLLM takes about 90% of GPU memory at startup.
| Metric | Mine | vLLM | Gap |
|---|---|---|---|
| Throughput (1 req) | 66 tok/s* | 270 tok/s | ~4× |
| Peak throughput | 788 tok/s (at 64) | 9,370 tok/s (at 256) | ~12× |
| TTFT p50 (1 req) | 30 ms* | 9 ms | ~3× |
| TPOT p50 (1 req) | 13.6 ms* | 3.6 ms | ~4× |
| Errors at 256 req | 902 (429s) | 0 | — |
* Measured after the streaming fix described below, in a separate run, so these gaps are approximate. The capstone run itself showed 90 tok/s, 114 ms and 7.2 ms at 1 request, but its stream loop dropped tokens, which distorted all three. Peak throughput was not affected (see "Why the 1-request numbers differ").
These gaps are not independent, so they don't add up neatly. The 12× peak gap includes everything vLLM does better, and with a single request the throughput gap is about 4×. Here are the main sources as far as my measurements can show.
Peak throughput (~12×): mostly batch capacity
My engine stores the KV cache as one contiguous tensor per layer. Each request gets a row, left-padded to the length of the longest sequence. I cap the batch at 16, because with this layout batch 32 already ran out of memory on this GPU (Step 3). Past that, requests wait or get a 429.
vLLM uses PagedAttention: the KV cache is split into fixed-size blocks allocated from a free-block list, like virtual memory pages. No padding, no fragmentation. This lets vLLM pack hundreds of sequences into the same 8 GB: its throughput is still climbing at 256 requests, while mine flattens after 16. Its faster kernels (next section) add to this gap too.
Per-token latency (~4×): fused kernels and CUDA graphs
I profiled the engine with cProfile. The forward pass alone is 85% of wall time — but a large chunk is Python overhead: HuggingFace's module dispatch, dtype casts, and ~159,000 individual CUDA kernel launches per 100 requests. The GPU keeps waiting for Python to tell it what to do next.
vLLM solves this with fused kernels and CUDA graphs. I tried torch.compile with CUDA graphs, but it recompiles almost every step because the batch shape changes — generation went from 12 ms to 178 ms per step (15× slower). CUDA graphs need fixed input shapes, which continuous batching breaks by design.
Time to first token: engine overhead, not prefill
I first blamed slow prefill for the 13× TTFT gap. My own numbers say otherwise. The Step 2 server, on the same Python and PyTorch stack, had a 23 ms TTFT. It jumped above 100 ms only once requests went through the engine loop (127 ms in Step 4, 117 ms in Step 5, 114 ms in the capstone).
The cause was the streaming loop. It checked each request's token queue and slept for 0.1 s whenever the queue was empty, so the first token could sit waiting for up to 100 ms:
1# Before: poll the queue, sleep 0.1 s when it is empty
2while not req.finished:
3 if not req.queue.empty():
4 token = await req.queue.get()
5 if token is None:
6 break
7 yield decode(token)
8 else:
9 await asyncio.sleep(0.1)
10
11# After: wait on the queue until the end-of-stream marker
12while (token := await req.queue.get()) is not None:
13 yield decode(token)In before-and-after runs on the same day, TTFT at 1 request dropped from 116 ms to 30 ms, and it stays between 37 and 55 ms from 2 to 16 requests. The fix also stopped the loop from dropping the last few tokens of a request. That brings the gap to vLLM's 9 ms down to roughly 3×. I haven't broken down the remaining ~20 ms yet. Likely candidates are the engine loop's 5 ms idle sleep, prefilling each new request on its own and splicing its cache into the batch, and Python request handling.
Where the Time Goes: A Profile
cProfile breakdown of the continuous-batching engine (100 requests, 8 concurrent, Qwen2.5-0.5B):
Two things stand out. First, the endpoint code (FastAPI, async queues) is 1.5% — the web framework is not the bottleneck. Second, cache editing — the complicated part — is only 1.2%. The forward pass dominates at 85%, and within that, it's mostly Python-side overhead in HuggingFace's model layers, not GPU compute.
The Whole Journey: Where It Started, Where It Ended
Here is every stage in one place, from the naive loop to the final engine, with vLLM on the same GPU as the reference point. Every number comes from the benchmark files in the repo (Qwen2.5-0.5B, max_length=64, one 8 GB GPU).
| Stage | 1 req | Peak | TTFT p50 | TPOT p50 | Heavy load |
|---|---|---|---|---|---|
1 · Baseline Naive loop: whole sequence recomputed per token | — | — not benchmarked | — | — | — no streaming endpoint |
2 · KV cache Reuse past keys and values | 59 tok/s | 83 tok/s at 16 req | 23 ms | 12 ms | 12.5 s p99 at 16 req |
3 · Static batching* N prompts in one forward pass | 98 tok/s | 1,204 tok/s at batch 16 | — | — | Out of memory at batch 32 |
4 · Continuous batching v1 Engine loop; requests join and leave | 47 tok/s | 389 tok/s at 16 req | 127 ms | 16 ms | 32 s p99 at 256 queue has no limit |
5 · Admission control Bounded queue, HTTP 429 when full | 75 tok/s | 602 tok/s at 16 req | 117 ms | 9 ms | 21 s p99 at 256 extra requests get 429 |
Final engine Steps 4 + 5 with KV cache editing and no_grad | 66 tok/s† | 788 tok/s at 64 req | 30 ms† | 14 ms† | 17 s p99 at 256 0 errors up to 64 |
vLLM (reference) PagedAttention, fused kernels, CUDA graphs | 270 tok/s | 9,370 tok/s at 256 req | 9 ms | 3.6 ms | 2.1 s p99 at 256 0 errors |
TTFT and TPOT are measured at 1 request; "at 16 req" means 16 concurrent requests. † From the run after the streaming fix; the peak and heavy-load numbers are from the capstone run. * Static batching receives every prompt in one call, so it is an upper bound rather than a server handling separate requests.
* Static batching receives all prompts in one call, so it is an upper bound, not a server handling separate requests.
What it all adds up to, comparing the final engine with the Step 2 server:
One number went the wrong way for a while. TTFT for a single request rose from 23 ms to 114 ms once requests went through the engine loop, because of the 0.1 s polling sleep. After the fix it is 30 ms, close to Step 2 again, and it stays under 55 ms up to 16 concurrent requests, while Step 2's grows to 379 ms at 16.
Why the 1-request numbers differ
The single-request throughput jumps around between stages: 59, 98, 47, 75, 90 tok/s. Those numbers don't all measure the same thing. Some come from different benchmark scripts, and some from runs with a bug in the streaming loop:
| Run | 1 req | How it was measured |
|---|---|---|
2 · KV cache Simple loop, no engine | 59 tok/s | Streaming endpoint, all 64 tokens delivered. Clean. |
3 · Static batching Batch of one prompt | 98 tok/s | A different script: one non-streaming call, median of 3, tokens assumed to be 64. No per-token streaming, so it isn't comparable with the other rows. |
4 · Continuous batching v1 Recomputed the batch when it changed | 47 tok/s | Streaming, with the stream bug. |
5 · Admission control Engine before the no_grad fix | 75 tok/s | Streaming, with the stream bug. |
Final engine (capstone run) KV cache editing and no_grad | 90 tok/s | Streaming, with the stream bug. |
Final engine (after fix) Same engine, stream loop fixed | 66 tok/s | Streaming, about 62 of 64 tokens delivered. Clean. |
The stream bug. Until the fix, the streaming loop could exit while tokens were still in the queue, so those runs delivered only 49 to 54 of the 64 tokens per request. The 0.1 s polling also delivered tokens in bursts. Shorter streams and bursty arrivals make requests look faster and the gaps between tokens look smaller, and the next request could start while the engine was still finishing the previous one. So the 47, 75 and 90 tok/s results can't be compared cleanly with Step 2, and the 7.2 ms per-token time from the capstone run was an artifact: the same engine measures 13.6 ms after the fix.
The clean comparison. With one request, the fixed engine does 66 tok/s against Step 2's 59, but its time per token is slightly worse (13.6 vs 11.7 ms). With nothing to batch, the engine's extra bookkeeping doesn't pay for itself; its advantage only shows with concurrency. Under load the bug barely mattered: same-day runs before and after the fix peak at 738 and 744 tok/s, with about 20 ms per token in both, which is why the peak numbers in this post stand.
What I Learned
1. Decoding is memory-bandwidth bound
The GPU reads the entire model from memory at every decode step, regardless of how many sequences are in the batch. This is why batching gives a near- linear throughput increase for free: the per-step cost is dominated by the weight read, not by the computation.
2. The KV cache is the central design problem
Every interesting decision in an inference server comes back to the KV cache: how to store it, how to grow it, how to share it, and how to decide when you're out of room. The cache decides your maximum batch size, which decides your throughput.
3. Measure before you explain a gap
These are the main sources of the vLLM gap, not a complete breakdown; they overlap, and the peak number includes everything vLLM does better. My first explanation for the TTFT gap (slow prefill) was wrong. Comparing against my own Step 2 numbers pointed at the engine loop, and one line of code removed most of it. The other two gaps need custom GPU kernels, which is where I stopped: the goal was to understand what each technique does, not to close the gap.
4. eval() ≠ no_grad()
model.eval() changes dropout and batch-norm behavior. torch.no_grad() disables gradient tracking. During inference, you need both, and the second one is the one that matters for memory. Without it, autograd silently saves every intermediate tensor, and your 0.5B model eats 7.6 GB.
5. The position bug teaches you RoPE
When a new request joins the batch with left-padding, its tokens start at a different position than existing requests. If you pass wrong position IDs, RoPE applies incorrect rotary encodings. The output isn't garbage — it's subtly wrong. "Paris is" instead of "Paris." — no crash, only catchable by comparing single-request vs batched outputs.
The Progress So Far
Steps completed: baseline, KV cache, static batching, continuous batching with cache editing, admission control, and the vLLM capstone. Steps on the list but not yet done: quantized model serving (next), prefix caching, speculative decoding, different attention types (GQA/MQA, sliding window), monitoring, structured output, and an OpenAI-compatible API.
Out of scope by design: custom GPU kernels (PagedAttention kernel, fused attention, FlashAttention) and multi-GPU. The vLLM comparison suggests these are behind most of the remaining throughput and per-token gap, and they don't fit a "build it in Python to understand it" project.
Try It
1git clone https://github.com/NotShrirang/inference-from-scratch.git
2cd inference-from-scratch
3uv venv .venv
4source .venv/bin/activate
5uv sync
6python main.py # serves on http://localhost:8000Run the benchmarks yourself:
1# Benchmark the continuous-batching endpoint
2python scripts/benchmark_endpoint.py \
3 --model Qwen/Qwen2.5-0.5B --load \
4 --endpoint generate-continuous-batch
5
6# Save and plot
7cp bench_endpoint_results.json benchmarks/step8_admission_control.json
8python scripts/plot_endpoint.py \
9 --results benchmarks/step8_admission_control.json \
10 --out benchmarks/step8_admission_control.png \
11 --title "Step 5: Admission Control (Qwen2.5-0.5B)"
12
13# Compare all steps on one plot
14python scripts/board.py compare --out benchmarks/step_comparison.pngThe repo has benchmark scripts for every step, a comparison board that plots them side by side, and a contamination checker that verifies batched requests don't mix outputs. Everything runs on a single 8 GB GPU.
Code: github.com/NotShrirang/inference-from-scratch
References
- Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023)
- Orca: A Distributed Serving System for Transformer-Based Generative Models (Yu et al., 2022) — the continuous batching paper
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (Dao et al., 2022)
- vLLM Documentation
If this resonated, pass it along.