Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 89/ 160
05. AI System Design

Inference Serving with vLLM

High-throughput open-source serving with PagedAttention and continuous batching.

AdvancedvLLM · Batching · Throughput3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

vLLM is a program that runs open AI models very efficiently on GPUs so many people can use them at once, and it speaks the same language as popular AI APIs.

Think of it like…

A well-run restaurant kitchen: instead of cooking one table's order at a time (naive serving), a head chef (the scheduler) keeps every station busy, starts new orders as soon as a burner frees up and stores ingredients in standard-size containers so no shelf space is wasted.

Where you’ve seen it

A team serves a 70B open model with FP8 weights. Weights take about 70 GB, so they use two 80 GB GPUs with tensor parallelism (--tensor-parallel-size 2) and --gpu-memory-utilization 0.90, leaving 2 × 80 × 0.9 = 144 GB of usable memory. After 70 GB of weights and roughly 10 GB for activations and CUDA graphs, about 64 GB remains for the KV cache. At 320 KiB per token (FP16 KV, grouped-query attention) that holds 64 × 10⁹ ÷ 327,680 ≈ 195,000 tokens, enough for about 55 concurrent 3,500-token sequences without sharing, and more with prefix caching (a shared 2,400-token system prompt is stored once). Clients keep using the OpenAI SDK with base_url pointed at the vLLM server; a Prometheus dashboard watches queue depth and KV-cache utilisation, and the load balancer routes sticky by prefix. The vLLM paper reported that earlier systems used only about 20% to 40% of reserved KV memory for real tokens and that PagedAttention-based serving reached 2 to 4 times the throughput at similar latency.

Words you’ll hear

PagedAttention
KV cache stored in fixed-size blocks mapped through a block table, avoiding fragmentation.
Continuous batching
Scheduling at each decode step so finished sequences leave and new ones join immediately.
Tensor parallelism
Splitting each layer's weights across several GPUs that work on every token together.
OpenAI-compatible server
An HTTP API that accepts the same requests as the OpenAI chat and completions endpoints.

Visual diagram

Loading interactive diagram

Theory & deep dive

What makes it efficient

Traditional serving preallocates a contiguous KV buffer per request for the maximum length, so most of it sits unused (internal fragmentation) and gaps appear between requests (external fragmentation); the vLLM paper measured only about 20% to 40% of reserved KV memory holding real tokens. PagedAttention divides the KV cache into blocks (for instance 16 tokens), allocates them on demand and records each sequence's blocks in a block table, so waste is limited to the last partially filled block. Blocks can be shared between sequences (parallel sampling, beam search, shared prompt prefixes) with copy-on-write, and freed blocks return to a pool immediately.

Continuous batching (iteration-level scheduling) lets the scheduler change the batch at every step: finished sequences release their blocks, waiting requests are admitted as soon as memory allows, and long prompts can be split by chunked prefill so they don't stall decoding. Together these raise the number of concurrent sequences a given amount of memory can hold and keep the GPU saturated. Additional features include automatic prefix caching, quantised weights and KV cache (more capacity, slightly lower accuracy), speculative decoding, guided decoding for JSON schemas or regexes, multi-LoRA serving of many adapters over one base model and support for many model families.

KV capacity

144 GB usable − 70 GB weights − 10 GB overhead = 64 GB for KV. At 327,680 bytes per token, 64e9 / 327,680 ≈ 195,000 tokens. Average sequence 3,500 tokens → about 55 concurrent sequences; with a shared 2,400-token prefix the unique part is about 1,100 tokens, allowing roughly 175 concurrent sequences.

Key takeaway: Paged KV blocks and per-step scheduling turn leftover GPU memory into maximum safe concurrency.

Deploying and tuning vLLM

Start the server with the model and key flags: vllm serve <model> --tensor-parallel-size 2 --max-model-len 16384 --gpu-memory-utilization 0.90 --max-num-seqs 64 --enable-prefix-caching (flag names evolve, so check the docs for your version). Size memory first: weights (parameters × bytes per parameter: 70B at FP8 ≈ 70 GB, at FP16 ≈ 140 GB) must fit across the GPUs with room for KV; --max-model-len bounds the context you support and the per-sequence KV worst case; --gpu-memory-utilization leaves headroom for spikes. Use tensor parallelism inside a node (fast interconnect such as NVLink) and pipeline parallelism across nodes. Quantisation (AWQ, GPTQ, FP8) frees memory for KV and speeds decode, but evaluate quality on your own tasks.

Operate it like any service. Use the OpenAI-compatible endpoint so applications and evaluation harnesses need only a new base_url; run multiple replicas behind a load balancer with prefix-aware routing and health checks; plan for slow cold starts (loading tens of gigabytes of weights takes minutes, so keep warm replicas and pre-pull images); and export metrics (running and waiting requests, KV-cache utilisation, TTFT and inter-token latency histograms) for dashboards and autoscaling on queue depth. Common problems: out-of-memory at startup from too large --max-model-len or too little headroom; thrashing when KV is nearly full (requests get pre-empted and recomputed); mismatched chat templates producing poor output; and security gaps from exposing the server without authentication. Decide self-hosting by comparing GPU cost at your utilisation against API prices (see GPU versus API cost).

Weights vs memory

70B parameters at FP16 need 140 GB, which doesn't fit on two 80 GB GPUs with usable 144 GB once KV and overhead are added. At FP8 (70 GB) it fits with about 64 GB left for KV, which is why quantisation often decides whether a model fits at all.

Key takeaway: Size weights, KV and headroom first, then tune concurrency and parallelism and operate with queue-based autoscaling.

How it works, step by step

Step 1 of 4
Platform

1. Size the memory

Compute weights, overhead and KV capacity; choose GPU count, quantisation and max model length.

70 GB + 10 GB + 64 GB KV on 2 × 80 GB
Key numbers at this step
KV
320 KiB per token

When to use it & trade-offs

What it is

vLLM is an open-source, high-throughput inference engine for LLMs. Its two defining ideas are PagedAttention (managing the KV cache in small fixed-size blocks, like virtual-memory pages, to avoid fragmentation and enable sharing) and continuous batching (adding and removing requests at every decoding step so the GPU stays busy). It exposes an OpenAI-compatible HTTP server, supports tensor and pipeline parallelism, quantised weights (AWQ, GPTQ, FP8), automatic prefix caching, LoRA adapter serving, speculative decoding and constrained (structured) output. In practice you launch it with a model name and a few flags, point existing OpenAI-style clients at it and tune memory, concurrency and parallelism for your hardware.

Why it matters: Self-hosting open models can cut cost at scale, keep data in your environment and allow customisation, but naive serving (a framework's generate call, static batches, contiguous KV allocation) wastes most of the GPU. vLLM-style engines reach multiples of the throughput on the same hardware, and understanding its memory model lets you size deployments, avoid out-of-memory errors and make sensible build-versus-buy decisions.

When to reach for it

  • Self-hosting open models at moderate to high volume
  • Keeping data inside your own environment
  • Serving LoRA-customised variants

When to avoid or be careful

  • Exposing the server without authentication
  • Setting max model length far above what you need
  • Skipping quality evals after quantisation

Serving options

vLLM (self-hosted)
Best for: High-throughput open-model serving with control

Strengths: Efficient memory use; OpenAI-compatible; rich features.

Watch out: You run GPUs, scaling and upgrades.

Managed API
Best for: Fastest start and top frontier models

Strengths: No infrastructure; elastic.

Watch out: Per-token cost and data-sharing constraints.

Naive framework generate loop
Best for: Prototypes and offline experiments

Strengths: Simple.

Watch out: Poor GPU utilisation and concurrency.

Interview signals & numbers to know

When this topic comes up

  • “We want to self-host an open model”
  • PagedAttention and continuous batching
  • OpenAI-compatible endpoint
  • KV cache sizing
  • Tensor parallelism

Benchmarks & rules of thumb

~195,000 tokens -
KV capacity from 64 GB at 320 KiB per token
20% – 40% -
KV memory holding real tokens in older systems (vLLM paper)
2 – 4× -
throughput gain reported over prior systems at similar latency

Common mistakes & follow-ups

Common interview mistakes

  • Forgetting that KV memory, not weights, caps concurrency.
  • Using a wrong chat template and blaming the model for bad output.
  • Scaling on CPU instead of queue depth.

Likely interviewer follow-ups

  • What problem does PagedAttention solve?
  • How would you size GPUs for a 70B model?
  • What would you monitor on a vLLM deployment?
Interview tip: Do the KV-capacity arithmetic aloud (leftover memory ÷ bytes per token). It shows you know what actually limits concurrency.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Inference Serving with vLLM with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Throughput vs Latency
Next topic
Continuous Batching