LLM Serving Engines
An LLM serving engine is the program that turns model weights into an API. You point it at a model like Llama 3.1 8B, and it loads the weights onto GPUs, accepts requests over HTTP, batches them together, runs the forward passes, manages the memory that holds each conversation's state, and streams tokens back. vLLM, SGLang, Hugging Face's Text Generation Inference (TGI), NVIDIA's TensorRT-LLM and llama.cpp are the names you'll hear most.
What these engines have in common matters more than their differences:
- Continuous batching: Requests join and leave the running batch at every decoding step, instead of waiting for a whole batch to finish. This is the single biggest reason a modern engine serves many times more traffic than a naive loop around
model.generate(). - KV cache management: Every sequence keeps attention keys and values for all its tokens. The engine allocates that memory in pages, shares it between requests with the same prefix, and decides who to evict when it runs out.
- An OpenAI-compatible API: Most of them expose
/v1/chat/completionsand/v1/completionswith streaming, so clients and gateways don't care which engine is behind them. - Parallelism and quantization: They split big models across GPUs (tensor and pipeline parallelism) and run them at lower precision (FP8, INT8, INT4) to save memory and bandwidth.
In an ML system design interview, you'll rarely be asked to compare engines for their own sake. But any design that self-hosts a model, like an inference platform, a batch job, a RAG system or a coding agent on open-weight models, has a box labeled "model server," and your interviewer may push on what's inside it. Knowing what an engine does lets you size the fleet, explain why latency rises under load, and pick a sensible default. Design an LLM Inference System builds the system around the engine; this post is about the engine itself.
What a Serving Engine Does
Generating text has two phases with very different costs, and every engine design follows from that:
- Prefill: process the whole prompt in one forward pass, computing and storing the KV cache for every prompt token, and produce the first output token. It's compute-bound: thousands of tokens go through the matrix multiplies together, so the GPU's arithmetic units are busy.
- Decode: generate one token at a time. Each step reads all the model weights and the sequence's KV cache from GPU memory to produce a single token per sequence. It's memory-bandwidth-bound: the arithmetic units mostly wait for memory.
The numbers make this concrete. Llama 3.1 8B in bf16 is about 16 GB of weights. An H100 SXM reads memory at roughly 3.35 TB/s, so one decode step takes at least 16 GB / 3.35 TB/s ≈ 4.8 ms just to stream the weights, an upper bound of about 200 tokens per second for one sequence. The trick is that reading the weights once serves the whole batch: 64 sequences decoding together cost only a little more per step than one. So throughput comes from batching, and batching is limited by how many KV caches fit in memory.
That's why the KV cache matters so much. For Llama 3.1 8B (32 layers, 8 KV heads, head dimension 128, bf16):
KV bytes per token = 2 (K and V) × 32 layers × 8 heads × 128 dims × 2 bytes
= 131,072 bytes = 128 KiB
On an 80 GB GPU with 90% reserved for the engine, about 72 GB is usable. Take away 16 GB of weights and a few GB for activations, and roughly 52 GB is left for KV cache: about 400,000 tokens of context across all running sequences. At an average of 4,000 tokens per sequence, that's about 100 concurrent sequences. Every engine feature in the next section is about using those 400,000 slots better.
Inside, every engine has roughly the same pieces:
- API server accepts requests, applies the chat template, tokenizes, and streams results back as server-sent events.
- Scheduler runs once per step. It decides which waiting requests to admit, how many prompt tokens of each to prefill this step, which running sequences decode, and who to preempt if memory runs out.
- KV cache manager hands out fixed-size blocks of GPU memory, tracks which blocks each sequence uses, and finds blocks that can be reused from earlier requests with the same prefix.
- Model runner executes the forward pass for the whole batch on one or more GPUs, using fused attention kernels (FlashAttention, FlashInfer or the engine's own) and, for decode, often a pre-captured CUDA graph to cut kernel-launch overhead.
- Sampler and detokenizer pick the next token (temperature, top-p, grammar constraints) and turn token IDs back into text.
The Techniques They All Share
These ideas started in different places, but by now the major GPU engines all implement some version of each. You should be able to explain them in a sentence or two; Inference Optimization and Distributed Training goes deeper.
Continuous batching (NVIDIA calls it in-flight batching). The batch is rebuilt at every decode step. When a sequence finishes, a waiting request takes its place right away. Static batching, by contrast, waits for the longest sequence in a batch to finish, wasting GPU time on padding.
Paged KV cache. Instead of reserving one contiguous region of memory per sequence sized for the maximum length, the KV cache is split into small fixed blocks (vLLM's default is 16 tokens), and a per-sequence block table maps logical positions to physical blocks, like virtual memory in an OS. Waste drops from "most of the reservation" to "part of the last block," which means many more sequences fit.
Prefix caching. Many requests share a beginning: the same system prompt, the same few-shot examples, the earlier turns of a conversation, the same long document. If those KV blocks are still in memory, the engine reuses them and skips that part of the prefill. For a chatbot with a 2,000-token system prompt, that's 2,000 tokens of prefill saved per request.
Chunked prefill. A 30,000-token prompt prefilled in one step would stall every decoding sequence for hundreds of milliseconds. Chunked prefill splits it into pieces of, say, 2,048 tokens and mixes each piece into a step alongside the decodes, so time-per-output-token for everyone else stays smooth.
Quantization. Running weights in FP8 halves memory and bandwidth versus bf16, which roughly halves decode time per step and frees memory for KV cache. INT4 weight-only formats (AWQ, GPTQ) go further. The KV cache itself can also be stored in FP8. Hardware matters: FP8 tensor cores arrived with Hopper (H100), and Blackwell adds FP4.
Speculative decoding. A cheap drafter (a small model, extra prediction heads, or n-gram matching against the prompt) proposes several tokens, and the big model verifies them in one forward pass. Because decode is bandwidth-bound, checking 4 tokens costs about the same as generating 1. It cuts latency at low batch sizes and helps less when the GPU is already saturated.
Parallelism. Tensor parallelism splits each layer's matrices across GPUs in one node (TP=2, 4, 8), which cuts per-token latency but needs fast NVLink between them. Pipeline parallelism puts different layers on different GPUs or nodes. Expert parallelism spreads a mixture-of-experts model's experts across GPUs. Data parallelism is just several independent replicas.
Structured output. Constrain sampling so the output must match a JSON schema, regex or grammar, by masking tokens that would break it at each step. Libraries like XGrammar, Outlines and llguidance do this efficiently, and engines integrate one or more of them.
Multi-LoRA serving. Keep one copy of the base model and swap in small LoRA adapters per request, so hundreds of fine-tuned variants share one GPU.
When an interviewer asks why a self-hosted model got slow at peak, the answer is almost always KV cache pressure. As concurrent sequences grow, the cache fills, the scheduler stops admitting new requests (time to first token climbs) or preempts running ones (they restart or stall). Watching KV cache utilization and the waiting-queue length, not CPU or even GPU utilization, is how you see it coming.
vLLM
vLLM came out of UC Berkeley in 2023 alongside the PagedAttention paper, which introduced the paged KV cache. It has become the default open-source serving engine: the broadest model support, the largest contributor community, and support for a wide range of hardware (NVIDIA and AMD GPUs, with TPUs, Intel accelerators and others supported through backends or plugins whose maturity varies).
Serving a model is one command:
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--max-model-len 16384 \
--gpu-memory-utilization 0.90 \
--tensor-parallel-size 1 \
--max-num-seqs 256
That starts an OpenAI-compatible server on port 8000. Clients use any OpenAI SDK with a different base_url. There's also an offline Python API (LLM(...).generate(prompts)) for batch jobs, which skips HTTP and lets the engine see the whole workload at once.
But what is actually happening under the hood? At startup, vLLM loads the weights, runs a profiling forward pass at the maximum batch size to measure activation memory, and then carves the remaining memory (up to --gpu-memory-utilization) into KV cache blocks. The log line telling you how many blocks, and therefore how many tokens of KV cache, you got is the most useful number it prints. It then captures CUDA graphs for common decode batch sizes, which takes extra time on startup but speeds up every decode step afterward.
Each step, the scheduler works within a token budget (--max-num-batched-tokens): decodes for running sequences first, then chunks of prefill for new or partially prefilled requests. Prefix caching hashes each full block of tokens together with everything before it, so a new request whose first N blocks match cached blocks reuses them directly. When memory runs out, the scheduler preempts the most recently admitted sequences, frees their blocks, and recomputes them later.
Things to know about vLLM for a design:
- Its newer "V1" engine architecture, the default since 2025, rewrote the scheduler and made prefix caching and chunked prefill on-by-default behavior. Defaults and flag names change between releases, so pin a version and read its docs.
- It exposes Prometheus metrics on
/metrics: running and waiting requests, KV cache usage, time to first token, time per output token. Those are the signals to autoscale and alert on. - It supports tensor, pipeline, data and expert parallelism, multi-LoRA, speculative decoding (draft models, EAGLE-style heads, n-gram), structured output and most quantization formats.
- For multi-node and disaggregated setups, it's usually combined with an orchestration layer such as llm-d, NVIDIA Dynamo, or Ray, rather than doing everything alone.
When to pick it: the default for self-hosting open-weight models on GPUs, especially when you serve many different models or care about new models working on day one.
SGLang
SGLang came out of the LMSYS group (the people behind Chatbot Arena) in 2024. It started as two things: a fast serving runtime and a small Python-embedded language for writing structured LLM programs (generate, branch, constrain, fork into parallel calls). The runtime is what most people use today, and it's a direct alternative to vLLM with the same OpenAI-compatible API:
python -m sglang.launch_server \
--model-path meta-llama/Llama-3.1-8B-Instruct \
--tp 1 --port 30000
Its signature idea is RadixAttention. Instead of caching blocks by hash, SGLang keeps every cached KV sequence in a radix tree keyed by token IDs. Any new request walks the tree to find its longest cached prefix, so sharing works for any common prefix, not only the system prompt: the shared turns of a conversation, the shared document in a batch of questions, the shared trajectory of an agent that branches into several tool calls. Leaves are evicted least-recently-used, and the scheduler can prefer requests that hit the cache.
But what is actually happening under the hood? When a request arrives, SGLang matches its tokens against the tree, pins the matched nodes so they aren't evicted while in use, allocates new KV slots only for the unmatched suffix, and inserts the new tokens as a branch when the request finishes. Reference counts protect nodes in use by running requests; unpinned leaves are the eviction candidates. The scheduler can sort the waiting queue to favor requests with long cached prefixes, which raises the hit rate further. This is especially effective for agent and multi-turn workloads, where most of each request is context the engine has already seen.
Other things SGLang is known for:
- Fast constrained decoding. It pioneered tricks that speed up decoding when the output must follow a grammar, such as jumping ahead over tokens the grammar forces, and it integrates grammar backends like XGrammar.
- Low scheduler overhead. Its scheduler overlaps CPU work for the next batch with GPU work for the current one, which matters for small, fast models where CPU overhead is a real share of each step.
- Large mixture-of-experts models. The project has put a lot of work into serving DeepSeek-style models at scale, with data-parallel attention, expert parallelism and prefill-decode disaggregation.
When to pick it: workloads with heavy prefix sharing (agents, multi-turn chat, many questions over the same long context), structured outputs, or large MoE models. Benchmarks between vLLM and SGLang flip back and forth by release and workload, so in a design it's reasonable to say "vLLM or SGLang, chosen by benchmarking our traffic."
TGI (Text Generation Inference)
TGI is Hugging Face's serving engine, built to power its own Inference Endpoints. Its architecture has a clean split you can describe in an interview:
- A launcher starts everything and downloads the model from the Hugging Face Hub.
- A router, written in Rust, serves HTTP, validates and queues requests, and runs the continuous batching logic.
- One or more model server shards, in Python, run the model (one per GPU when sharded with tensor parallelism), talking to the router over gRPC.
It's typically run as a container:
docker run --gpus all --shm-size 1g -p 8080:80 \
-v $PWD/data:/data \
ghcr.io/huggingface/text-generation-inference:<version> \
--model-id meta-llama/Llama-3.1-8B-Instruct
TGI was an early mover on continuous batching, FlashAttention and paged attention in an easy-to-deploy package, and it exposes both its own /generate API and an OpenAI-compatible Messages API. It has also added the ability to run other engines (such as TensorRT-LLM or llama.cpp) as backends behind its router.
Its license history is worth knowing because it comes up: it moved to a more restrictive license in 2023 and back to Apache 2.0 in 2024. More importantly for a new design, Hugging Face has said TGI is in maintenance mode and has pointed users toward vLLM and SGLang, which it also supports as backends in its own products. Check the project's current status before choosing it.
When to pick it: you're already deeply on Hugging Face infrastructure, or you're maintaining an existing TGI deployment. For a new self-hosted platform, vLLM or SGLang is the safer default.
TensorRT-LLM
TensorRT-LLM is NVIDIA's open-source library for running LLMs as fast as possible on NVIDIA GPUs. It comes from the same place as the GPU, so it tends to get kernels for new hardware features first: FP8 on Hopper, FP4 on Blackwell, and highly tuned attention, GEMM and communication kernels.
The workflow has historically been different from vLLM's:
- Convert a checkpoint into TensorRT-LLM's format.
- Build an engine (
trtllm-build): compile the model for a specific GPU type, precision, tensor-parallel degree and maximum batch and sequence sizes. - Serve the engine, usually through Triton Inference Server with the TensorRT-LLM backend, or with
trtllm-serve, which exposes an OpenAI-compatible API.
The build step is what gives TensorRT-LLM its peak performance and its operational cost: an engine built for 4× H100 at FP8 with a 32K max length doesn't run on 2× A100, and every change of shape limits or hardware means a rebuild. NVIDIA has been moving toward a PyTorch-based path and a high-level Python LLM API that reduce the separate build step, so how much of this applies depends on the version you use.
Feature-wise it has what you'd expect: in-flight batching, paged KV cache with reuse across requests, chunked prefill, speculative decoding (draft models, Medusa, EAGLE), multi-LoRA, and tensor, pipeline and expert parallelism. NVIDIA also packages it into NIM containers and supports it as a backend in Dynamo, NVIDIA's framework for distributed serving with disaggregated prefill and decode and KV-aware routing.
When to pick it: a large, stable deployment of a few models on NVIDIA hardware, where squeezing out the last 20-50% of throughput per GPU is worth a more involved build-and-deploy pipeline. It's NVIDIA-only.
llama.cpp
llama.cpp is different from the rest. It's a C/C++ engine with no Python dependency, built originally to run LLMs on a MacBook's CPU, and now on almost anything: x86 and ARM CPUs, Apple Silicon through Metal, NVIDIA through CUDA, AMD, and Vulkan for other GPUs. Models are stored in its single-file GGUF format, with a family of quantization types (Q8_0, Q5_K_M, Q4_K_M and lower) that trade size for quality.
The size math is simple: Q4_K_M averages a little under 5 bits per weight, so an 8B model is roughly 8B × 4.85 / 8 ≈ 4.9 GB, small enough for a laptop or a phone-class device. A 70B model at the same quantization is around 40 GB, which fits on a Mac with enough unified memory.
It ships an HTTP server with an OpenAI-compatible API:
llama-server -m llama-3.1-8b-instruct-Q4_K_M.gguf \
-c 16384 -np 4 -ngl 99 --port 8080
Here -c is the total context, split across -np parallel slots (four concurrent requests with 4,096 tokens each), and -ngl 99 offloads all layers to the GPU if there is one. It supports continuous batching across slots, but it's built for one machine and a handful of concurrent users, not for hundreds of concurrent streams on a GPU cluster.
Much of the local-LLM ecosystem is built on it or on its ggml library: Ollama and LM Studio, for example, have used it as their engine (Ollama has been adding its own engine for some models, so check). In a design, llama.cpp is the answer for edge and on-device inference: offline assistants, privacy-sensitive deployments on customer hardware, CPU-only servers, and developer laptops.
When to pick it: on-device, edge, CPU-only or Apple Silicon serving, single-user or low-concurrency workloads, and anywhere you need a small dependency-free binary.
Comparing Them
| vLLM | SGLang | TGI | TensorRT-LLM | llama.cpp | |
|---|---|---|---|---|---|
| Origin | UC Berkeley, community | LMSYS, community | Hugging Face | NVIDIA | Community (ggml) |
| Language | Python + CUDA/C++ kernels | Python + CUDA kernels | Rust router + Python shards | C++/CUDA with Python API | C/C++ |
| Hardware | NVIDIA, AMD, others via backends | Mostly NVIDIA and AMD | NVIDIA, AMD, others | NVIDIA only | CPU, Apple Silicon, NVIDIA, AMD, Vulkan |
| KV cache reuse | Hash-based prefix caching | RadixAttention prefix tree | Prefix caching | KV cache reuse | Per-slot cache reuse |
| Strength | Breadth, ecosystem, default choice | Prefix-heavy and agent workloads, structured output, MoE at scale | Easy HF-integrated deployment | Peak throughput on NVIDIA | Runs anywhere, tiny footprint |
| Weakness | Defaults shift between versions | Smaller model coverage than vLLM | Maintenance mode | Build complexity, NVIDIA lock-in | Not for high-concurrency datacenter serving |
| Typical deploy | Container on Kubernetes, behind a router | Same | Container, HF Endpoints | Triton, NIM or Dynamo | Laptop, edge box, Ollama |
Don't present engine choice as a permanent architecture decision. All of them speak an OpenAI-style API, so in a design you put a gateway or router in front of the model servers and treat the engine as a swappable component. "We start with vLLM, benchmark SGLang and TensorRT-LLM on our real traffic mix, and can switch per model because clients only see the gateway" is a strong answer.
Choosing an Engine
A short decision path covers most interview situations:
- Is it on-device, CPU-only or a laptop? llama.cpp (or a tool built on it, like Ollama).
- Is it a GPU fleet serving open-weight models? Start with vLLM: it supports the most models and hardware, and it's what most platform teams already know.
- Is most of each request a prefix the engine has seen before (agents re-sending a long trajectory, multi-turn chat, many questions over the same document)? Benchmark SGLang, whose radix cache handles that well, and turn on prefix-aware routing in front of either engine.
- Is it a few very high-volume models on NVIDIA hardware with a stable configuration? Consider TensorRT-LLM, for example through Triton or Dynamo, if benchmarks show a throughput win large enough to pay for the build pipeline.
- Is it a hosted API (OpenAI, Anthropic, Bedrock, Vertex)? Then there's no engine for you to choose; the design question moves to the gateway, quotas and fallbacks (Design an LLM Gateway).
What matters more than the engine is the configuration: precision, tensor-parallel degree, maximum context length, maximum concurrent sequences, prefix caching, and the hardware. Those choices change throughput by multiples. Engine choice usually changes it by tens of percent.
Running an Engine in Production
Picking an engine is the easy part. Most of the design work is around it.
Sizing. Work out the memory first, then the throughput:
- Weights: parameters × bytes per parameter. 70B in bf16 is 140 GB, so at least 2× 80 GB GPUs, and in practice TP=4 to leave room for KV cache. In FP8 it's 70 GB, which fits on 2 GPUs with plenty of cache.
- KV per token:
2 × layers × kv_heads × head_dim × bytes. For a Llama-3-70B-style model (80 layers, 8 KV heads, head dimension 128, bf16) it's about 320 KiB per token, so 100 sequences × 8,000 tokens is roughly 260 GB. Context length is a capacity decision, not a free setting. - Throughput per replica: measure it. Run a load test with your real prompt and output length distribution and record tokens per second at your latency targets (p50 and p99 time to first token, time per output token). Then replicas = peak tokens per second ÷ measured tokens per second per replica, plus headroom. Numbers to Know for ML Systems has the reference figures.
Routing. A plain round-robin load balancer works, but it wastes the prefix cache, because a conversation's second turn lands on a replica that never saw the first. Prefix-aware or session-affinity routing (consistent hashing on the conversation or system-prompt hash, with load as a tiebreaker) keeps cache hits high. Route on engine signals like queue depth and KV usage rather than connection counts.
Autoscaling. CPU utilization is meaningless for these processes and GPU utilization is a weak signal. Scale on waiting requests, KV cache usage, or time to first token. Remember scale-up is slow: a new replica has to get a GPU node, pull a multi-GB container image, load 16-140 GB of weights (at 1-2 GB/s from object storage, a 140 GB model takes one to two minutes), and warm up. Keep warm headroom, cache weights on local NVMe, and pre-scale before known peaks.
Health checks and draining. Readiness should pass only after weights are loaded and warm-up is done. On shutdown, stop accepting new requests and let in-flight streams finish within a grace period, or long generations get cut off mid-answer. The same probe pitfalls as any service apply; see Kubernetes.
Version pinning and evaluation. Engine upgrades change kernels, defaults and sometimes numerics. Pin versions, and before rolling a new engine or quantization out, run an evaluation suite and a load test, then canary it (Design an LLM Evaluation and Observability System).
A very common mistake is to put "GPU server" in the diagram and move on. Saying what runs on it (vLLM with FP8 weights, TP=2, 32K max context, prefix caching on), how many sequences each replica holds, and which metric you autoscale on turns a box into a design.
LLM Serving Engines in an Interview
When to Bring It Up
- Self-hosted model serving is central to the question: an inference platform, an internal LLM API, offline batch inference over billions of rows, or an app that must run open-weight models for cost, privacy or customization (fine-tuned or LoRA variants).
- You're sizing a GPU fleet. The engine's batching and KV cache behavior is what turns "QPS" into "number of GPUs."
- Edge or on-device is part of the question: llama.cpp-style quantized models on the device, with a server fallback.
If the design uses a hosted model API, one sentence is enough: the provider runs the engine, and your concerns are rate limits, cost and fallbacks.
Knowing Their Limitations
- They serve one model replica, not a fleet. Routing across replicas, multi-model placement, autoscaling, tenancy and billing live outside the engine, in your router, gateway and orchestration layer.
- Throughput is bounded by memory. Long contexts and many concurrent sequences fill the KV cache, and then latency climbs or requests get preempted. More GPUs or lower-precision KV cache are the fixes, not engine flags.
- Benchmarks don't transfer. Results depend on prompt length, output length, prefix sharing, batch size and hardware. Always benchmark your own traffic.
- Fast-moving software. Flags, defaults and supported features change from release to release. Pin versions and test upgrades.
- Cold starts are slow. Minutes, not seconds, to bring up a large-model replica.
Questions You Might Get
- "Why is vLLM so much faster than a simple HuggingFace
generate()loop?" Continuous batching keeps the GPU full, paged KV cache fits more sequences, prefix caching skips repeated prefill, and fused kernels plus CUDA graphs cut overhead. - "How many concurrent users can one GPU serve?" Do the arithmetic: memory left after weights ÷ KV bytes per token ÷ average tokens per sequence, then check against the latency targets with a load test.
- "Why does time to first token spike under load?" Requests wait for KV cache space or for long prefills in the queue. Chunked prefill, admission control, more replicas, or splitting prefill and decode onto separate pools help.
- "vLLM or SGLang?" Both are good defaults with OpenAI-compatible APIs. SGLang's radix cache shines on prefix-heavy workloads; vLLM has the broadest model and hardware coverage. Benchmark on your traffic and keep the engine swappable behind a router.
- "When would you use TensorRT-LLM?" High, steady volume on NVIDIA GPUs, where the throughput gain is worth compiling engines per hardware and configuration.
Summary
A serving engine turns weights into an API by batching requests at every decoding step, managing the KV cache in pages, reusing cached prefixes and running fused kernels on one or more GPUs. Decode is memory-bandwidth-bound, so throughput comes from batching, and batching is limited by how many tokens of KV cache fit. That one fact explains most of how these engines behave under load.
vLLM is the broad default for GPU serving, SGLang excels when requests share long prefixes, TGI is mainly relevant for existing Hugging Face deployments, TensorRT-LLM squeezes the most out of NVIDIA hardware at the cost of a build pipeline, and llama.cpp runs quantized models anywhere, from laptops to edge boxes. In an interview, pick a sensible default, say how you configured it and how many sequences each replica holds, keep it swappable behind a router, and spend your time on the system around it: routing, autoscaling, sizing and evaluation.