Design an LLM Inference System
Understanding the Problem
⚡ What is an LLM inference system? An LLM inference system takes a prompt, runs it through a large language model on GPUs, and streams the generated tokens back. It's the machinery behind an endpoint like
/v1/chat/completions. The model weights are fixed; the hard part is running thousands of conversations at once on very expensive hardware while each user still sees the first word in under a second and the rest arriving faster than they can read.
You may hear this asked as "design OpenAI's inference API," "design a multi-tenant model serving platform," or "how would you serve a 70B model to millions of users." These are the same problem. The multi-tenant version adds many models, fine-tuned variants and per-customer limits on top of the single-model version, and we'll cover both.
Functional Requirements
We'll focus on the serving path: a request comes in, tokens go out. Training, fine-tuning and the product built on top are separate systems.
Core Requirements
- Users should be able to send a chat completion request (messages plus sampling parameters) and receive the response as a stream of tokens.
- Users should be able to choose among several models, including fine-tuned variants of a base model.
- Each tenant should get its own rate limits and priority, and be billed for the input and output tokens it uses.
Below the line (out of scope)
- Training and fine-tuning the models (see /ml-system-design/llm-fine-tuning).
- Conversation storage, memory and the chat product itself.
- Safety classifiers and content filtering, beyond noting where they plug in.
- Offline bulk jobs (see /ml-system-design/batch-inference).
Non-Functional Requirements
Ask your interviewer for the model sizes and the traffic. For our design: the flagship is a 70B-parameter dense model (Llama-3-70B-like: 80 layers, grouped-query attention with 8 KV heads of dimension 128), plus a few smaller models and hundreds of fine-tuned adapters. Peak traffic is 1,000 requests per second on the flagship, with an average of 1,500 input tokens and 300 output tokens. We run on H100 80 GB GPUs.
Core Requirements
- The system should return the first token quickly: time to first token (TTFT) p95 under 1 second for prompts up to a few thousand tokens.
- The system should stream fast: time per output token (TPOT) under 50 ms, so at least 20 tokens per second per user, which is faster than people read.
- The system should keep GPUs busy. GPUs are the dominant cost, so throughput per GPU is a first-class requirement, not an afterthought.
- The system should isolate tenants: one customer's burst can't blow up another customer's latency.
- The system should be highly available: a dead GPU or node shouldn't fail more than the requests running on it.
Below the line (out of scope)
- Multi-region failover beyond "run pools in several regions and route to the nearest healthy one."
- Exact output reproducibility across runs.
Now the math, because it shapes everything. Start with memory. The weights in BF16 are 70B × 2 bytes = 140 GB, which doesn't fit on one 80 GB GPU. We'll shard each replica across 4 GPUs with tensor parallelism (320 GB of HBM). Next, the KV cache: for each token in a sequence, every layer stores a key and a value vector for each KV head.
KV bytes per token = 2 (K and V) × 80 layers × 8 KV heads × 128 dims × 2 bytes
= 327,680 bytes ≈ 320 KB per token
One 1,800-token conversation ≈ 576 MB
After weights and runtime overhead, a 4-GPU replica has roughly 160 GB left for KV cache, which is about 500,000 tokens, or around 270 concurrent conversations of average length. The KV cache, not compute, decides how many users a replica can serve at once. (Without grouped-query attention, with 64 KV heads, it would be 2.5 MB per token, 8× worse. GQA is why 70B models are servable at all.)
Then speed. Generating one token for one sequence needs about 2 FLOPs per parameter, so 140 GFLOPs, but it also means reading all 140 GB of weights from HBM. A 4-GPU replica has about 4 × 3.35 TB/s = 13.4 TB/s of memory bandwidth, so a single decode step takes at least ~10 ms no matter how few sequences are in it. With one sequence, that step does 140 GFLOPs in 10 ms, about 14 TFLOP/s on hardware that can do nearly 4,000. The GPUs are more than 99% idle on compute. The only way to use them is to decode many sequences in the same step, sharing one read of the weights.
Finally, fleet size. 1,000 requests per second × 300 output tokens = 300,000 output tokens per second. If a replica sustains about 4,000 output tokens per second at our latency targets, decode needs about 75 replicas, or 300 GPUs. Prefill is 1.5M input tokens per second × 140 GFLOPs ≈ 2 × 10^17 FLOP/s; at around 40% utilization of an H100's ~1 PFLOP/s of BF16, that's another ~500 GPUs' worth of compute. We're looking at roughly 800 H100s for one model, or on the order of a million dollars a month. Every percent of utilization is real money.
The two numbers to put on the whiteboard early are KV bytes per token and "decode is memory-bandwidth-bound." Almost every design choice in LLM serving (continuous batching, paged attention, prefix caching, disaggregation, quantization) follows from those two facts.
The Set Up
Planning the Approach
We'll build the request path first (gateway, router, a model server), then open up the model server to see how one replica serves hundreds of streams at once, then grow it into a multi-model fleet. The deep dives cover the KV cache, batching, splitting prefill from decode, routing and multi-tenancy.
Defining the Core Entities
- Tenant: a customer account with API keys, a priority tier and limits in requests per minute and tokens per minute.
- Model Deployment: a base model (weights, tokenizer, parallelism config) plus any LoRA adapters it can serve, and the pool of replicas it runs on.
- Replica: one running copy of a model on a group of GPUs (here, 4 H100s with tensor parallelism). It has a fixed budget of KV cache blocks.
- Sequence: one in-flight generation: its prompt tokens, generated tokens so far, sampling parameters and the KV blocks it owns.
- KV Block: a fixed-size chunk of KV cache holding the keys and values for, say, 16 tokens across all layers.
The Sequence is the unit the scheduler works with. A request with n=3 becomes three sequences that share the prompt's KV blocks.
API or System Interface
We'll follow the OpenAI-compatible shape, since most clients already speak it.
POST /v1/chat/completions
Authorization: Bearer <api key>
{
"model": "llama-70b" | "llama-70b:ft-acme-support",
"messages": [{ "role": "system", "content": "..." }, { "role": "user", "content": "..." }],
"max_tokens": 512, "temperature": 0.7, "top_p": 0.95, "stop": ["\n\n"],
"stream": true
}
-> 200 text/event-stream
data: {"id":"req_1","choices":[{"delta":{"content":"Sure"}}]}
data: {"id":"req_1","choices":[{"delta":{"content":", here"}}]}
...
data: {"choices":[{"finish_reason":"stop"}],
"usage":{"prompt_tokens":1520,"completion_tokens":311,"cached_tokens":1024}}
data: [DONE]
-> 429 { "error": "rate_limited", "retry_after_ms": 2000 }
-> 503 { "error": "overloaded" }
GET /v1/models -> the models and adapters this key can use
max_tokens matters more than it looks: it's the client's promise about the worst-case size of the sequence, and the scheduler uses it to plan memory.
High-Level Design
1) Users should be able to send a request and receive a token stream
The simplest design that works: an API Gateway authenticates the key, applies rate limits and opens a Server-Sent Events stream back to the client. It forwards the request to a Router, which picks a replica of the requested model. The Model Server on that replica tokenizes the prompt, runs the model and pushes each token back up the stream as it's generated.
Generation happens in two phases, and they behave very differently:
- Prefill runs the whole prompt through the model in one forward pass. All 1,500 tokens are processed in parallel, which is big matrix multiplications: compute-bound. It produces the KV cache for the prompt and the first output token. Prefill time is most of TTFT.
- Decode then generates one token at a time. Each step feeds in only the newest token, reads the KV cache of every previous token, and writes one more entry. Each step is tiny matrix-vector work over huge weights: memory-bandwidth-bound. Decode step time is TPOT.
For the 1,500-token prompt, prefill is 1,500 × 140 GFLOPs ≈ 2.1 × 10^14 FLOPs, which on 4 H100s at a realistic 40% utilization takes around 130 ms. Then each of the 300 decode steps takes 10 ms or more. So the user waits a fraction of a second for the first token and a few seconds for the whole answer.
The first version runs one request at a time per replica. It's correct, but from the math above, decoding one sequence uses well under 1% of the GPU's compute. With 1,000 requests per second, we'd need thousands of replicas. The fix is batching, which lives inside the model server.
2) The system should serve many concurrent streams on each replica
Open up the model server. A modern serving engine (vLLM, SGLang, TensorRT-LLM and TGI all look roughly like this) has four parts:
- Frontend: accepts requests, tokenizes, detokenizes output incrementally and pushes deltas onto each client's stream. It runs on CPU, separate from the GPU loop, so slow clients and string handling don't stall generation.
- Scheduler: runs once per model step. It decides which sequences are in the next batch, how many prompt tokens to prefill, and what to do when memory runs out.
- KV Cache Manager: owns the GPU memory reserved for KV cache, split into fixed-size blocks, and hands blocks to sequences as they grow.
- Model Executor: one worker per GPU. Each holds a quarter of every weight matrix (tensor parallelism) and they exchange partial results with all-reduces over NVLink after each layer.
The key idea is continuous batching (also called iteration-level scheduling). Instead of collecting a batch of requests, running them all to completion and then taking the next batch, the scheduler rebuilds the batch on every step. A sequence that emits its stop token leaves the batch immediately and its blocks are freed; a newly arrived request joins on the very next step. The GPU always works on as many sequences as memory allows, and nobody waits for the slowest member of their batch.
With ~200 sequences in a decode batch, each step reads the 140 GB of weights once for all of them, plus their KV caches. The step takes longer (say 30-40 ms instead of 10 ms), but it produces 200 tokens instead of one. That's how a replica reaches thousands of output tokens per second while each user still sees 25-30 tokens per second.
The KV cache manager uses paged attention: the KV cache isn't one contiguous buffer per sequence but a list of blocks, like virtual memory pages, so we only allocate memory for tokens that actually exist. We'll dig into why that matters in the deep dives.
3) Users should be able to choose among models and fine-tuned variants
A real platform serves many models: the 70B flagship, an 8B model for cheap traffic, an embedding model, and hundreds of customer fine-tunes. We add:
- A Model Registry that records each deployment: weights location, tokenizer, parallelism, GPU type, which adapters it can load, and its replica pool.
- Model pools: replicas are grouped by base model. The router maps the
modelfield to a pool. - A Weight Store (S3 or similar, with a copy on each node's local NVMe) so new replicas can load weights quickly.
- An Autoscaler that adds or removes replicas per pool based on load.
Fine-tuned variants are mostly LoRA adapters: small low-rank matrices added to some weight matrices of a base model. A rank-16 adapter on all projection layers of a 70B model is a few hundred MB, versus 140 GB for the base. So we don't deploy a separate 70B replica per customer fine-tune. Each base-model replica keeps a set of adapters loaded and serves requests for many of them in the same batch. A request for llama-70b:ft-acme-support goes to the 70B pool, preferably to a replica that already has that adapter in memory. Full fine-tunes (all weights changed) do need their own deployment, which is why platforms encourage LoRA.
4) Each tenant should get limits, priority and usage billing
The gateway enforces limits per tenant in requests per minute and tokens per minute. Counting tokens matters because a 100k-token prompt costs a hundred times more than a 1k-token one. At admission we don't know the output length, so we reserve prompt_tokens + max_tokens against the tenant's budget and refund the difference when the request finishes. The counters live in Redis, exactly as in /system-design/rate-limiter.
Each request carries its tenant's priority tier down to the scheduler (we'll use it in the deep dives). When the request finishes, the model server emits a usage record (tenant, model, adapter, prompt tokens, cached tokens, output tokens) to Kafka. A billing pipeline aggregates those into invoices. Usage is counted on the server from what was actually processed, never from client claims, and records carry the request ID so the aggregation is idempotent.
Potential Deep Dives
1) How do we fit more concurrent sequences into GPU memory?
The KV cache decides how many sequences a replica can batch, and batch size decides throughput. So memory management is throughput management.
Bad Solution: Reserve the Maximum Length Up Front
Approach
When a request arrives, allocate one contiguous KV buffer big enough for its maximum possible length (the model's context limit, or prompt + max_tokens). That's how early serving stacks worked, and it's simple: attention kernels read one contiguous tensor per sequence.
Challenges
Most of that memory is never used. If we reserve the 8k context limit (2.6 GB per sequence at 320 KB per token), our 160 GB budget holds about 60 sequences, even though the average sequence only reaches 1,800 tokens. Most of the reserved memory sits empty, and contiguous buffers of different sizes also fragment the pool. Early systems wasted a large fraction of KV memory this way, and batch size was capped far below what the GPU could handle.
Good Solution: Paged Attention
Approach
Split KV memory into fixed-size blocks of, say, 16 tokens. Each sequence has a block table mapping its logical blocks (tokens 0-15, 16-31, ...) to whatever physical blocks happen to be free. A sequence gets a new block only when it fills its last one. The attention kernel is rewritten to follow the block table instead of assuming contiguous memory. This is the idea vLLM introduced, and every major engine now has a version of it.
Waste drops to at most one partially filled block per sequence. With memory proportional to actual length, the same 160 GB holds about 500k tokens, or ~270 sequences of average length, over 4× the static version. Blocks also enable sharing: parallel samples (n=3) or beam candidates point at the same physical blocks for the shared prompt, with a reference count and copy-on-write when one diverges.
Challenges
Now we can run out of memory mid-generation: we admitted sequences based on current length, and they all keep growing. The scheduler needs a policy for that moment. It can preempt a sequence: either swap its blocks to CPU memory over PCIe and bring them back later, or drop them and recompute the KV by re-running prefill on prompt plus generated tokens when it resumes. Recompute is often cheaper for short sequences, since prefill is fast and compute-bound; swapping wins for long ones. The scheduler should also leave headroom (admit new work only while, say, 5-10% of blocks are free) so preemption stays rare.
Great Solution: Paged Attention Plus Prefix Caching and a Quantized KV Cache
Approach
Two more wins on top of paging.
Prefix caching. Many requests share a long prefix: the same system prompt, the same few-shot examples, or the earlier turns of a multi-turn conversation that's being re-sent in full. Since blocks are fixed-size, we can hash each full block by its token contents and the hash of the block before it (so a block's hash identifies the entire prefix up to that point). When a sequence finishes, its blocks stay in the cache, marked as evictable, instead of being freed immediately. A new request that starts with the same tokens finds its first N blocks already computed and skips prefill for them. SGLang's RadixAttention keeps the same information in a radix tree. Evict least recently used blocks when memory is needed.
For chat traffic, where every turn re-sends the conversation so far, hit rates of 50% or more of prompt tokens are realistic. From our estimate, that's on the order of 250 GPUs of prefill we don't need. It also cuts TTFT for long conversations, and the API can report cached_tokens and charge less for them.
FP8 KV cache. Storing keys and values in 8 bits instead of 16 halves KV memory, so the same budget holds ~1M tokens. On H100s it has a small accuracy cost for most models, but it should be validated per model.
Challenges
Prefix caching only helps if requests with the same prefix land on the same replica. A 100-replica pool with random routing almost never hits. That pushes the problem into the router (deep dive 4). Cached prefixes are also tenant data: block hashes should include a tenant or cache-scope ID if you don't want one customer's requests to warm, or time, another's cache.
If your interviewer asks "how many users can one GPU serve," answer with KV memory: free HBM ÷ (KV bytes per token × average sequence length). Then say how paging and prefix caching move that number. That's a much stronger answer than "it depends on the batch size."
2) How do we batch requests without hurting latency?
Bigger batches mean more tokens per second per GPU but slower steps for each user. We need both TTFT and TPOT inside the SLO.
Bad Solution: Static Batching
Approach
Wait until we have a batch of, say, 32 requests (or a timeout passes), pad them to the same length, run them together until every one finishes, then take the next batch. This is how classic model serving batches image classifiers.
Challenges
Output lengths vary wildly: one request stops at 20 tokens, another runs to 1,000. The whole batch waits for the longest, so short requests finish late and their slots sit empty for hundreds of steps. New arrivals wait for the entire batch to drain, which wrecks TTFT. And padding wastes compute on fake tokens.
Good Solution: Continuous Batching
Approach
As in the high-level design: the scheduler rebuilds the batch every step. Finished sequences leave, waiting sequences join, and the batch stays as full as KV memory allows. A step that admits new requests runs their prefill alongside the ongoing decodes.
Challenges
The prefill of a long prompt is a big chunk of work. If a 16k-token prompt joins the batch, that step may take several hundred milliseconds, and all 200 decoding users see their stream freeze for that long. TPOT p99 goes bad whenever long prompts arrive. Engines that run "prefill steps" and "decode steps" separately have the opposite problem: while they prefill, decode stalls; while they decode, new requests wait.
Great Solution: Continuous Batching With Chunked Prefill and a Token Budget
Approach
Give each step a fixed token budget, say 2,048 tokens. Every decoding sequence costs 1 token of budget. The rest is filled with prefill work, and a long prompt is split into chunks that fit the remaining budget over several steps. A 16k-token prompt is processed in eight or so chunks, interleaved with decode, instead of one huge step.
each step:
budget = 2048
batch = all running decode sequences # 1 token each, say 200
budget -= len(batch)
for seq in waiting_queue (ordered by priority, then arrival):
if budget == 0: break
if not kv.can_allocate(seq, min(budget, seq.remaining_prompt)): break
chunk = min(budget, seq.remaining_prompt)
batch.add(seq, prefill_tokens=chunk)
budget -= chunk
run_model(batch)
Step times now stay in a predictable band, which keeps TPOT steady. Mixing compute-heavy prefill tokens with bandwidth-heavy decode tokens in the same step also uses both resources at once: the decode part reads the weights anyway, and the prefill part soaks up compute that would otherwise idle.
The budget is the dial between latency and throughput. A small budget keeps TPOT tight but slows prefill (higher TTFT under load); a big one does the opposite. Tune it per deployment against the SLOs, and cap how many sequences can decode at once so TPOT doesn't drift past 50 ms.
Challenges
There's still interference: every prefill chunk makes that step slower for decoders, and when traffic spikes the waiting queue grows and TTFT climbs. When long-prompt workloads (RAG, code, documents) dominate, it's worth separating the two phases entirely, which is the next question.
3) Should prefill and decode run on the same GPUs?
Prefill is compute-bound and wants big parallel matrix work. Decode is memory-bandwidth-bound and wants big batches over a large KV cache. Running both on the same replica means each step is a compromise, and you size the whole replica for the harder of the two SLOs.
Good Solution: Colocated, With Chunked Prefill
Approach
Keep both phases on every replica and rely on chunked prefill to smooth the interference, as above. It's one pool to scale, no extra network traffic, and it's what most deployments run.
Challenges
You can't tune TTFT and TPOT independently. A burst of long prompts slows every stream on the replica, and a pool full of long decodes delays new prompts. Parallelism choices are shared too, although prefill would often prefer different settings from decode.
Great Solution: Disaggregated Prefill and Decode
Approach
Run two pools for the same model. Prefill workers take new requests, run the prompt (in big compute-efficient batches), and produce the KV cache and the first token. They then transfer the KV cache to a decode worker, which adds the sequence to its continuous batch and generates the rest. The router assigns both. This is the design described in research systems such as DistServe, Splitwise and Mooncake, and newer versions of vLLM, SGLang and NVIDIA Dynamo support it.
The transfer is real data. A 1,500-token prompt has 1,500 × 320 KB ≈ 490 MB of KV cache. Over a 400 Gb/s RDMA NIC (about 50 GB/s), that's around 10 ms, and it can stream layer by layer while prefill is still running, so the first decode step isn't delayed by the whole transfer. Inside one 8-GPU node, NVLink is faster still.
Now each pool is sized and tuned for its own SLO. Prefill pool size tracks input tokens per second and TTFT; decode pool size tracks concurrent sequences, KV memory and TPOT. The ratio can shift with the workload (RAG with 20k-token prompts needs far more prefill than a chatbot). The decode pool can also run larger batches since prefill bursts never land on it.
Challenges
It's more machinery: KV transfer needs a fast interconnect (RDMA or NVLink, not ordinary TCP), the router has to place both halves, and a failure in the middle of the hand-off needs a retry path. For short prompts, the transfer overhead can outweigh the gain. It pays off at scale with long prompts and tight SLOs; for a smaller deployment, colocated with chunked prefill is the right call, and saying so is part of the answer.
4) How do we route requests across replicas?
The router picks which replica runs each request. It decides both load balance and whether the prefix cache hits.
Bad Solution: Round Robin
Approach
Send requests to replicas in turn, as an ordinary load balancer would.
Challenges
LLM requests vary in cost by orders of magnitude: a 50-token question and a 50k-token document are both "one request." Round robin piles expensive requests onto some replicas while others idle. And it spreads every conversation's turns across random replicas, so prefix caching almost never hits.
Good Solution: Load-Aware Routing
Approach
Each replica reports its state every few hundred milliseconds: running sequences, waiting queue length, free KV blocks, recent step time. The router picks the replica with the most headroom, using power-of-two-choices sampling so a hundred routers don't all pick the same "best" replica at once.
Challenges
It balances load well but still ignores the cache. Turn 5 of a conversation lands on a replica that has never seen turns 1-4, and it re-prefills the whole history.
Great Solution: Prefix-Aware Routing With Load Balancing
Approach
Route by prefix first, then load. The router hashes the first few blocks of the prompt (the system prompt plus the start of the conversation) and uses consistent hashing over the pool, so requests with the same prefix tend to land on the same replica. Better still, replicas publish which block hashes they hold (a compact summary, refreshed often), and the router scores each candidate as cached prefix length − α × load. A replica that already holds 4,000 of your 4,500 tokens wins unless it's overloaded.
Two guards keep this from going wrong. If the preferred replica's queue is above a threshold, fall back to the least-loaded one; a cache hit isn't worth a 3-second queue. And a hot prefix (a popular app's system prompt) shouldn't pin all its traffic to one replica: spread it across a small set of replicas so each holds a copy. For adapters, add "has this LoRA loaded" to the score.
Challenges
The router now holds approximate, slightly stale state about every replica, and it has to be fast (well under a millisecond) because it sits on the request path. Scaling events reshuffle the consistent-hash ring and cool caches; bounded-load consistent hashing keeps the reshuffling small. See /system-design/consistent-hashing.
5) How do we share the fleet across many tenants and models?
Multi-tenancy is where an inference platform makes or loses money. Three problems: fairness between tenants, serving many fine-tunes cheaply, and scaling pools whose replicas take minutes to start.
Fairness and priority. Rate limits at the gateway stop a tenant from exceeding its contract, but they don't stop a legal burst from one big tenant filling every replica's queue. So the scheduler also orders its waiting queue by priority tier (interactive before batch, paid before free) and, within a tier, by fair share of tokens: keep a running count of tokens served per tenant and admit the tenant that is furthest below its share next. Under overload, low-priority work waits or gets a 503, and preemption picks low-priority sequences first. Requests that can't possibly meet their deadline should be rejected at admission, not after they've used GPU time.
Serving hundreds of LoRA adapters. Batch requests for different adapters together. The base model's matrix multiplies run once for the whole batch; each sequence then adds its own small low-rank product x · A_i · B_i. Kernels such as those from Punica and S-LoRA do this for a mixed batch in one launch. Each replica keeps a few dozen hot adapters in GPU memory and more in CPU memory, loading on demand in tens of milliseconds, with LRU eviction. The router prefers replicas that already have the adapter. The extra compute is small next to the base model, so one pool serves hundreds of customers' fine-tunes at nearly the cost of serving the base model.
Autoscaling. A new 70B replica has to get 4 GPUs, start the engine, load 140 GB of weights (tens of seconds from local NVMe, minutes from object storage), allocate the KV cache and capture CUDA graphs. Scaling reacts in minutes, not seconds, so:
- Scale on signals that lead latency: waiting queue depth, KV block utilization and TTFT, not CPU or GPU "utilization," which reads near 100% on a busy replica even when it has room.
- Keep warm headroom (say 15-20%) per pool, and pre-scale for known daily peaks.
- Pre-stage weights on nodes' local disks, or stream them from a peer, so start-up isn't bottlenecked on S3.
- Fill idle capacity with preemptible batch work, so the headroom isn't wasted.
- Low-traffic models are the hard case. Keeping a 4-GPU replica up for a model that gets one request an hour is expensive; scale-to-zero means a cold start of a minute or more. Offer those models through a shared smaller pool, LoRA on a common base, or an explicit "cold start" latency tier.
Failures. A GPU fault kills every sequence on that replica (tensor parallelism means all 4 GPUs fail together). The frontend notices the dead worker and the router retries the affected requests on another replica. For a stream that had already sent tokens, it resubmits the prompt plus the tokens generated so far as the new prompt, so the continuation picks up where it stopped: the user sees a pause, not an error. Sampling won't produce the exact same continuation, which is acceptable for chat. Health checks also run a tiny real generation, because a replica can look alive while its GPU is in a bad state.
A common miss is treating the GPU fleet like stateless web servers. Replicas are slow to start, hold valuable cache state, and fail in large units. Your interviewer wants to hear that you route for cache locality, scale on queue and KV signals, and keep headroom because you can't scale in seconds.
Final Design
The full flow:
- The client sends
POST /v1/chat/completionswithstream: true. The API Gateway authenticates the key, checks the tenant's request and token limits in Redis (reservingprompt + max_tokens), and opens the SSE stream. - The Router looks up the model pool in the Model Registry, hashes the prompt's leading blocks, and picks a replica (or a prefill worker, in a disaggregated pool) by cached prefix length, load and adapter residency.
- On the replica, the scheduler queues the sequence by priority and fair share. Each step it builds a batch under a token budget: all running decodes plus chunks of waiting prefills.
- The KV cache manager reuses cached prefix blocks, allocates new blocks as the sequence grows, and preempts low-priority sequences if memory runs out.
- The tensor-parallel workers run the step; the frontend detokenizes the new tokens and pushes them onto each client's stream. In a disaggregated pool, the prefill worker ships the KV cache over RDMA to a decode worker, which streams the rest.
- When the sequence finishes, its blocks become cached prefix blocks, the gateway refunds the unused token reservation, and a usage record goes to Kafka for billing. The autoscaler watches queue depth and KV utilization per pool and adds replicas, loading weights from local NVMe.
What is Expected at Each Level?
Mid-level
You should get the request path right (gateway, router, model servers on GPUs, streaming over SSE) and explain prefill vs decode and why TTFT and TPOT are separate metrics. You should know that batching is how GPUs get used efficiently and, with a nudge, explain why static batching wastes capacity and continuous batching fixes it. Knowing that the KV cache exists and grows with sequence length is expected; the exact memory math can come with help.
Senior
You should do the memory math yourself (weights, KV bytes per token, how many sequences fit) and state that decode is memory-bandwidth-bound while prefill is compute-bound. Expect to explain paged attention and why it raises batch size, chunked prefill and the latency-throughput dial, and prefix caching with prefix-aware routing. Token-based rate limits, usage metering and LoRA multi-adapter serving should come up without much prompting.
Staff+
You should drive the design from cost and SLOs: how many GPUs this takes, where utilization is lost, and which optimization buys the most for this workload. Expect to reason about when prefill/decode disaggregation is worth its complexity, how parallelism and quantization choices trade latency against cost, how to keep tenants isolated under overload, and how to operate the fleet: scaling on queue and KV signals, warm headroom, slow cold starts, failure blast radius and recovering mid-stream. Knowing when not to build something (a smaller deployment doesn't need disaggregation) is part of the signal.