LLM Inference Serving
Schedule prefill, decode and KV memory across GPU replicas with explicit overload and recovery contracts.
- Kind
- Case study
- Level
- Advanced
- View
- Interview prep
- Sections
- 4
- By
- Sourav Banerjee
- Last updated
- 20 Nov 2026
Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.
Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.
Case brief
The case in one line: batch LLM requests onto stateful GPUs, pick the GPU that has KV memory for the next request, and keep serving when a GPU dies mid-stream.
30-Second Cheat Sheet
- The prompt: an end-to-end system that batches LLM requests onto GPUs, decides which GPU has capacity and survives a GPU failure.
- How it's graded: as a distributed-systems question about queues, batches, load balancing, health checks and backpressure.
- The hard part: each GPU is a stateful server with a fixed memory budget, not an interchangeable worker.
- Two phases: prefill sets time to first token (TTFT); decode sets time per output token (TPOT) and total duration.
- The KV cache grows with every token, so KV memory, not request count, decides where a request can run.
- The tension: a bigger batch buys throughput, and every request in it pays in latency.
- The core idea: admit before the GPU, place by free KV, batch continuously, stream by request ID.
- Every capacity number is a constructed example, not a benchmark. Say so in the room.
1. Batch Language-Model Requests on Stateful GPUs
What the interviewer asks
- An end-to-end system that batches large language model (LLM) requests onto GPUs.
- It decides which GPU has capacity for the next request.
- It keeps working when a GPU fails.
- It sounds like an AI question. It is graded as a distributed-systems question: queues, batches, load balancing, health checks and backpressure.
Backpressure = pushing "slow down" signals back toward the caller.
Why it's hard: the GPU holds state
- Each GPU is a stateful server with a fixed memory budget, not an interchangeable worker.
- A model generates text in two phases:
| Term | Meaning |
|---|---|
| Prefill | Reads the whole prompt in one parallel pass and produces the first output token. Sets time to first token (TTFT). |
| Decode | Produces one token per step. Sets time per output token (TPOT) and total duration. |
| KV (key-value) cache | The attention keys and values the GPU keeps for every token a sequence has seen. Grows with every token until the sequence ends. |
| Backpressure | "Slow down" signals pushed back toward the caller. |
- Request count says little about load. KV memory decides where a request can run.
The one tension
- A bigger batch buys throughput.
- Every request inside it pays for that throughput in latency.
The core idea (Figure 1 as a flow)
tokenise and assign an ID → queue has room? → route by free KV → batch continuously → stream by request ID
- Queue full → refuse early ("retry later") instead of letting the request wait.
- That early refusal is the one branch that matters most.
Trace one request
- A caller sends a 1,000-token prompt and asks for a streamed answer.
- The gateway counts its tokens on CPU and gives it a request ID.
- Admission checks two things:
- The caller's tenant has token budget.
- The bounded queue has room.
- If not, the caller gets an immediate "retry later", not a seven-second wait that times out.
- An admitted request goes to a GPU with enough free KV for about 1,250 tokens.
- That GPU's scheduler slots it into the running batch at the next decode step.
- Each generated token travels back to the caller, matched by its request ID.
The caveat to say aloud
- Every capacity number in this case is a constructed example, not a benchmark of a real engine.
Soundbite (source's line): "I would replace these with a load test of the actual model."
2. The Anchor Prompt and Four Related Prompts
- Five interview prompts share one foundation.
- The anchor asks for the whole batching system. The other four shrink, scale, critique or debug it.
- Understand the anchor and you can answer all five.
| Case | Shared foundation | What changes | Where it's taught |
|---|---|---|---|
| Batching system (anchor): end-to-end batching for LLM queries, with "which GPU has capacity?" and "how do you handle failover?" | Admission → capacity-aware routing → local scheduler → streamed result | Balanced interactive service with failover | Design walkthrough, cost pivot (full casebook) |
| One GPU, up to 100 synchronous inputs per batch | Same request IDs and batching | Size-or-time flush, futures and one bounded queue | Deep dive: One GPU with synchronous callers |
| Token-generation service at 100,000 requests/s | Same token-work method | Independent cells, global backpressure, large reserved headroom | Deep dive: One hundred thousand requests per second |
| Review a junior developer's batching design | Same invariants | Rank flaws: static generative batches, unbounded FIFO, round-robin routing | Deep dive: Review a junior design |
| Diagnose high latency in an LLM inference pipeline | Same spans | Diagnose tokenization, network, queue, prefill, KV, decode, post-processing | Deep dive: Walk the latency stack |
Where the prompts come from
- The source labels the first four as Anthropic prompts.
- It labels the latency prompt as an OpenAI favourite.
- The latency walk is shared with the Observability and Production Diagnosis case.
Who it's for
- Engineers preparing for Forward Deployed, solutions or applied-AI rounds.
- Especially rounds about LLM serving, request batching or GPU capacity.
What it assumes you know
- How a transformer generates tokens
- Basic GPU memory
- Queueing with Little's Law
- Load balancing
The dangerous constraint
- KV memory, not request count, decides placement.
- A GPU can fail mid-stream.
By the end you should be able to
- Explain the system end to end, starting from that constraint.
- Answer follow-ups on:
- Prefill and decode capacity
- Continuous batching
- KV budgeting
- Routing and failover
- Backpressure
- Latency diagnosis
- Cost
Scope
- The case serves an existing model. It does not train one.
How the sections divide the work
- Design walkthrough: the interview answer, in order.
- Technical deep dives: KV arithmetic and the four related prompts.
- Practice (full casebook): self-checks, the 45-minute plan and the cost pivot.
- Quick review: the card for the night before.
Quick Recall: Lines to Say in the Interview
- "This is a distributed-systems question about queues, batches and backpressure."
- "A GPU is a stateful server with a memory budget, not an interchangeable worker."
- "Prefill sets first-token time; decode sets streaming speed."
- "KV memory, not request count, decides where a request can run."
- "A bigger batch buys throughput, and every request in it pays in latency."
- "A full queue refuses early instead of a seven-second wait that times out."
- "I would replace these numbers with a load test of the actual model."
Design walkthrough
The goal: a batching service that admits work before the GPU, places each sequence by free KV memory, batches continuously and fails loudly and safely when a GPU dies.
30-Second Cheat Sheet
- Request shape first: tokens in and out at p50 and p95. Anchor: 1,000 in, 250 out, 1,000 rps peak, interactive and streamed.
- Testable targets: TTFT p95 ≤ 500 ms, TPOT p95 ≤ 50 ms, ≤ 70% utilisation, 99.9% complete or fail explicitly, and goodput next to throughput.
- Size three ways: compute (0.15 replica-seconds →
214 replicas), slots (7,000 in flight → ~110), memory. Compute binds. - Admit globally, route by capacity, batch locally. Only the replica sees its own KV, so it has the final say.
- Continuous batching: sequences join and leave at every decode step; chunked prefill protects streams.
- Route by free KV with power of two choices and prefix affinity, never round-robin.
- Refuse early: token-weighted tenant buckets, a bounded queue, 429 or 503 with Retry-After.
- Recover honestly: retry unstreamed work under a 10% budget; streamed work re-prefills or returns an explicit partial error.
Opening line (source's version): "A GPU is a stateful server with a memory budget. Prefill sets first-token time, decode sets streaming speed, and the KV (key–value) cache decides how many requests fit at once. I'll design the scheduler around those three facts."
1. Establish the Request Shape Before Sizing
- "100,000 requests per second" means nothing until you know the tokens in each request.
- A 20-token completion and a 2,000-token essay differ in decode work by two orders of magnitude.
- Ask what kind of request this is. State an assumption aloud for each question the interviewer declines.
| Question | Why it matters | Anchor assumption |
|---|---|---|
| Input and output tokens per request, at p50 and p95? | Input drives prefill; output drives decode. They cost GPU time differently | 1,000 in, 250 out on average |
| Interactive or offline? Streamed or whole? | Interactive needs a first-token target; offline can batch hard | Interactive, streamed |
| Which latency matters: first token, per token or total? | Three different SLOs with three different fixes | First token and per-token both |
| One model or many? Fixed or variable output length? | Variable length rules out static batching | One model, variable output |
| Peak rate, burst shape, tenants and priorities? | Sets headroom, fairness and shedding policy | 1,000 rps peak, bursty, several tenants |
SLO (service level objective) = the target you commit to internally, such as "95% of answers in under 3 seconds". p50 / p95 = the median and the value 95% of requests beat.
One more question the table doesn't carry
- What should a caller see if a GPU dies after some tokens have already streamed?
- The answer chooses between continuing elsewhere and an explicit partial error.
- Step 8 depends on it.
- Model count matters too. Several models mean separate pools: one model's weights and KV can't serve another.
Weak vs strong answer
| Answer | What it does |
|---|---|
| Weak | Draws a load balancer, a queue and a pool of GPUs, then stops. Never says what a batch is or why a GPU fills up. |
| Strong | Names the two phases of inference in the first two minutes, because every later decision schedules prefill and decode on scarce memory. |
Soundbite: "A GPU is a stateful server with a memory budget. Prefill sets first-token time, decode sets streaming speed, and the KV cache decides how many requests fit at once."
2. Define Latency, Useful Throughput and Failure Contracts
- A requirement that can't fail a test is a preference.
- "Fast" is a preference.
- "First token under 500 ms at p95 at 1,000 rps" is a constraint.
- The nouns come from the prompt. The must/should split and every number are the source's assumptions.
Must-haves (the anchor's wording)
- Accept generation requests: a prompt, a token limit, sampling parameters and a stream flag.
- Batch them onto GPUs.
- Route each sequence to a GPU with capacity.
- Deliver the response to the right caller, streamed or whole.
- Detect a failed GPU and move its work elsewhere.
- Reject or queue excess load rather than collapse under it.
Should-haves (make it operable)
- Per-tenant quotas and priorities.
- Cancellation when a caller disconnects.
- Prefix reuse for repeated system prompts.
- Rolling model upgrades (drain and canary) without dropping traffic.
- Metrics that separate queue wait from service time.
Non-functional targets a load test can fail
| Constraint | Stated so it can be tested |
|---|---|
| First-token latency (TTFT) | p95 ≤ 500 ms at peak for interactive traffic |
| Per-token latency (TPOT) | p95 ≤ 50 ms between streamed tokens |
| Throughput | 1,000 rps sustained at peak with the anchor request shape |
| Utilisation target | ≤ 70% of measured replica capacity, because queueing delay climbs steeply past roughly 70–80% (rule of thumb) |
| Availability | 99.9% of requests complete or fail explicitly; none vanish |
| Failover | Losing one GPU loses no un-streamed request; losing one zone keeps service at reduced headroom |
| Fairness | No tenant above its quota can raise another tenant's p95 |
| Goodput | Requests per second that finish inside the SLO, reported next to raw throughput |
TTFT = how long until the first word appears. TPOT = how fast the rest streams once started.
Two definitions to say plainly
- Goodput counts only requests that finish within their objective.
- Raw throughput can rise while goodput falls.
- That means the fleet does more paid work that arrives too late to matter.
- The 70% utilisation ceiling is a planning rule that leaves room for bursts and failures.
- Where tail latency climbs depends on how variable service times are.
- Measure the real curve before trusting the rule.
Every must-have gets an owner
| Requirement | Primary component(s) |
|---|---|
| Accept and validate requests | API gateway, tokenizer service |
| Batch onto GPUs | Per-replica scheduler with continuous batching |
| Route to a GPU with capacity | Router plus capacity registry |
| Deliver to the right caller | Response demultiplexer keyed by request ID, streaming layer |
| Survive GPU failure | Health checker, router eviction, retry with a budget |
| Reject excess load | Admission controller, bounded queues |
| Fairness | Per-tenant token buckets at admission |
Spoken answer (source's short form): "Functionally, admit, place on a replica with KV room, batch, stream, cancel, fail loud. Non-functionally, TTFT and TPOT SLOs, no lost streams, and tenant fairness. The model only does prefill and decode."
3. Calculate Compute, Concurrency and Memory Separately
- GPU count is the answer, never the method.
- The method: requests → token work → replicas.
- A replica is one copy of the model serving traffic; here, one GPU.
The general single-rate formula (source's air-gapped design chapter)
Replicas = ⌈ (QPS × Tokens_request) / (TokensPerSecond_replica × UtilizationTarget) ⌉
- The chapter's warning:
- GPU count without throughput → you miss the bottleneck.
- Memory without throughput → you miss the placement constraint.
- Prefill and decode run at very different rates, so this case prices each phase separately.
- Three independent checks: compute, slots and memory.
Why the rates need H100-class hardware
- Assumptions: an illustrative 8B-class model on one 80 GB H100-class GPU.
- Prefill is compute-bound.
- A forward pass costs roughly 2 FLOPs per parameter per token → about 16 GFLOP a token for 8B.
- 20,000 input tokens/s → about 320 TFLOP/s before attention overhead.
- That's about a third of an H100 SXM's dense BF16 peak of roughly 989 TFLOP/s.
- It's slightly above an A100's 312 TFLOP/s peak, so an A100 can't reach this prefill rate. The numbers don't transfer to older hardware.
| Assumption | Value |
|---|---|
| Prefill rate per replica (assumed, H100-class) | 20,000 input tokens/s |
| Decode rate per replica | 2,500 output tokens/s aggregate, at ~64 concurrent sequences |
| Anchor request | 1,000 input, 250 output tokens |
| Peak arrival | 1,000 rps |
| Utilisation target | 70% |
Check one: compute
1,000 ÷ 20,000 + 250 ÷ 2,500 = 0.05 + 0.10 = 0.15replica-seconds per request.× 1,000 rps= 150 replicas of pure work.÷ 0.70= 214.3 → plan on about 214 (215 if you round strictly up).
- Decode is 0.10 of the 0.15, two-thirds of the bill, so output length is the biggest cost lever.
Check two: slots, by Little's Law
Little's Law = work in flight = arrival rate × time in the system.
- Each sequence streams at
2,500 ÷ 64 ≈ 39tokens/s, roughly 26 ms a token. - Decode is usually memory-bandwidth-bound, not compute-bound.
- Each step reads the 16 GB of weights plus the batch's KV: about 10 GB for 64 anchor sequences (KV deep dive).
- At an H100 SXM's 3.35 TB/s, that's at least about 8 ms a step.
- So 26 ms a token is deliberately conservative: room for scheduling, prefill interference and kernel overhead.
- A request lives about 0.5 s to first token +
250 × 26 ms ≈ 6.4 s→ about 7 s total. 1,000 rps × 7 s≈ 7,000 sequences in flight.7,000 ÷ 64slots a replica → about 110 replicas' worth of slots.
Take the larger number
- Compute says 214; slots say 110. Compute binds.
- Provision about 214, then add N+1 per zone, so losing a GPU or a zone doesn't breach targets.
- Say both checks aloud: a reviewer trusts the number that survived two independent methods.
Check three: memory
- The KV cache grows with every token. The KV deep dive does this model's arithmetic.
- The source borrows the air-gapped design's replica budget to show the shape of the check:
| Budget line | Size |
|---|---|
| Quantised weights | 12 GB |
| Runtime overhead | 2 GB |
| KV cache and activations | 6 GB |
| Batch buffers and fragmentation slack | 2 GB |
| Total | roughly 22 GB: too tight for a 24 GB card even when compute fits |
- Treat it as the shape, not this model's numbers.
- Its 6 GB KV line would hold fewer than 40 of this case's 1,250-token sequences at 128 KiB a token.
- The KV deep dive's figures (16 GB fp16 weights + about 10 GB for 64 sequences) fit an 80 GB card with room to spare.
- The same design's rule: if the replica count exceeds the hardware pool, challenge the request profile rather than ask for more GPUs.
The caveat
- All three results move with the real model, hardware, batch occupancy and token distributions.
- They're a way to reason in the room, not a purchase order.
Soundbite: "0.15 replica-seconds a request, about 214 replicas at 70%, cross-checked at about 110 by Little's Law, so compute binds."
4. Admit Globally, Route by Capacity, Batch Locally
Model vs code
- The LLM does: prefill and token-by-token decode.
- Code owns: request identity, quotas, admission, placement, scheduling policy, health, the retry budget and response routing.
The organising rule: admit → route → batch per GPU
- Admission and routing are global and hold no GPU state.
- Admission keeps per-tenant token buckets and queue depth.
- Routing reads the capacity registry.
- Neither knows which KV blocks a replica has free right now.
- Batching is local, because only the replica can see its own memory.
- Replica-local memory checks have final authority over whether a sequence fits.
The request path, step by step (Figure 2)
- Gateway: authenticates, assigns a request ID, validates limits and tokenises on CPU. Token work is known before any GPU time is spent.
- Admission: charges the tenant's token bucket by estimated tokens and places the request in a bounded priority queue.
- When the objective can't be met, it signals at once: 429 with Retry-After, or deferral to a batch tier.
- Router: samples healthy replicas using free KV blocks, queue length and shared-prefix warmth.
- The chosen replica does the final capacity check, which stops several routers herding onto one replica from stale registry data.
- Replica scheduler: adds waiting sequences and removes finished ones at each decode step.
- Chunked prefill stops a long incoming prompt from stalling running streams.
- GPU: runs prefill and decode while paged KV blocks are allocated on demand.
- Demux: tokens are matched to callers by request ID, detokenised and streamed.
- Health probes evict sick replicas.
- Unstreamed requests may retry under a budget.
- After partial output, the product either resumes by re-prefilling (with caveats) or returns an explicit partial error.
- Disconnect or stop cancels the sequence and frees its KV. Rollouts drain replicas and canary new versions rather than dropping active requests.
The other views the source draws
| Figure | What it adds |
|---|---|
| Figure 3: request path in detail | Power-of-two choice with prefix affinity at the router, the 429 or batch-defer exit at admission, a disconnect that frees the KV slot immediately, SSE stream back to the client |
| Figure 4: capacity and health loop | Replica heartbeats about every 1 s fill a registry of free KV blocks, waiting, running and health; a three-layer health checker (liveness, readiness, 1-token probe) evicts or drains |
| Figure 5: the whole system | Control plane at the left (model registry, autoscaler, tenant quotas, drain-and-canary); two replicas heartbeating to one capacity registry; the full path with its 429 and cancel exits |
The control plane
- Versions the model registry, tenant quotas, routing and health policy, and SLO targets.
- Runs drain-and-canary rollouts.
- The autoscaler uses queue depth and KV use, not CPU.
- The service reports TTFT, TPOT, queue wait vs service time, goodput, KV use and errors.
Thirteen components
- Closed = refuses rather than guesses. Degrades = keeps serving with less.
| # | Component | Responsibility | Fails how |
|---|---|---|---|
| 01 | Gateway | Authenticates, validates, assigns request_id, tokenizes |
Closed: bad request rejected before any GPU work |
| 02 | Tokenizer | Text to token IDs on CPU; counts tokens for admission | Degrades: add CPU replicas; never on the GPU hot path |
| 03 | Admission controller | Per-tenant token buckets weighted by estimated tokens; bounded queue | Closed: 429 with Retry-After, never an unbounded wait |
| 04 | Router | Picks a replica by free capacity, with prefix affinity | Degrades: least-loaded fallback if the affinity target is hot |
| 05 | Capacity registry | Each replica's free KV blocks, queue and running count | Degrades: stale data tolerated by random-two choice plus replica-side check |
| 06 | Replica scheduler | Continuous batching: admits and evicts sequences every decode step | Degrades: preempts lowest priority when KV is full |
| 07 | GPU worker | Prefill and decode on a paged KV pool | Fails: evicted by health checker, work rerouted |
| 08 | Health checker | Liveness, readiness and a one-token synthetic probe | Closed: an unready replica gets no traffic |
| 09 | Demultiplexer | Returns each sequence's tokens to its caller by request_id |
Closed: an unmatched ID is dropped and logged, never misdelivered |
| 10 | Detokenizer and post-processor | Incremental text, stop sequences, safety or schema checks | Degrades: skip optional checks, never required ones |
| 11 | Streaming layer | SSE or websocket, flushes per token | Degrades: fall back to whole response |
| 12 | Autoscaler | Scales on queue depth and KV use, not CPU | Degrades: headroom absorbs the minutes a new replica often takes to provision and load |
| 13 | Rollout controller | Drains a replica before upgrade; canaries a new model version | Closed: a failing canary stops the rollout |
Three boundaries to point at
- Admission is the only place load is refused, so no downstream queue grows without limit.
- The router decides where a request runs, never how, because only the replica sees its memory.
- The request ID is the thread through everything, so a response can never reach the wrong caller.
Soundbite: "Admit globally, route by capacity, batch locally: only the replica sees its memory, so it has the final say."
5. Tokenise at the Edge and Stream Back by Request ID
Tokenise at the gateway
- Tokenisation is CPU work. On the GPU's request thread it steals time from the most expensive machine in the building.
- Tokenising early buys three things:
- Admission charges a tenant by real tokens, not request count.
- The router estimates KV memory before picking a replica.
- A malformed or oversized prompt fails before it reaches a queue.
- Cap input length at the gateway with a clear error: one 100,000-token prompt can monopolise a replica's prefill.
Detokenise incrementally
- Some tokens are partial characters, so the streaming layer buffers until a complete character exists.
- Stop sequences are checked on assembled text, not on tokens, for the same reason.
Streaming changes perceived latency, not total latency
- A user reading the first sentence after 500 ms experiences a fast system, even if the answer takes seven seconds.
- Stream over server-sent events (SSE) or a websocket, flushing per token.
- Watch for buffering proxies: one buffering hop turns streaming back into a seven-second wait.
- Report TTFT and TPOT as separate objectives, because they break for different reasons.
Cancellation is a cost control
- If any hop fails to pass the disconnect on, the sequence keeps decoding, burning GPU time on tokens nobody reads.
- The source's references show both halves:
- vLLM's server aborts a request when the client disconnects.
- A reported vLLM issue shows the abort breaking when middleware fails to forward the disconnect.
- Propagate the disconnect through every hop to the scheduler, which evicts the sequence and frees its KV blocks at the next step.
- Test the middleware rather than assuming it.
Soundbite: "Streaming changes perceived latency, not total latency; one buffering proxy undoes it."
6. Batch at the Iteration That Can Release Work
- A GPU is efficient only when it multiplies many rows at once, so batching is the whole point.
- The design question: when does a batch form and when does it end?
| Strategy | How a batch forms | How it ends | Right for |
|---|---|---|---|
| Static | Wait for N requests | When the longest sequence finishes | Fixed-shape offline work only |
| Dynamic | Flush at N requests or after a max wait, such as 10 ms | When the batch's forward pass finishes | Fixed-shape models: embeddings, classifiers, rerankers |
| Continuous (iteration-level) | New sequences join at every decode step | Each sequence leaves the moment it finishes | Generative LLMs with variable output length |
Static fails generative traffic
- A batch finishes only when its longest member finishes.
- Example: a 10-token answer batched with a 1,000-token answer is done after 10 steps, and its slot sits idle for the remaining 990.
Dynamic suits fixed-shape models
- Flushes when full or when the oldest request has waited a max time, such as 10 ms.
- Every item takes one forward pass, so nobody waits for a longer neighbour.
Continuous schedules every decode step
- Every iteration the scheduler removes finished sequences and admits waiting ones into the freed slots.
- Same pair: the 10-token answer leaves after step 10; a waiting request takes its slot at step 11 while the long answer keeps decoding.
Prefill complicates it: chunked prefill
- A long prompt's prefill can stall every decoding sequence for tens of milliseconds, seen as a per-token latency spike.
- Split long prefills into chunks and interleave them with decode steps.
- The trade: a little first-token time for the new request, against smooth streaming for everyone else.
- Say it aloud: it's the same throughput-versus-latency tension the case opened with.
Batch size is a knob, not a constant
- Larger batches raise throughput and raise per-token latency.
- Tune against the TPOT objective and goodput, not the largest raw token-throughput number.
- Let the scheduler cap concurrency when per-token latency drifts up.
Soundbite: "Static batches wait for the longest output; continuous batches release each sequence the step it finishes."
7. Route by Free Memory and Refuse Overload Early
Why not round-robin
- Round-robin assumes every request costs the same. Here none do.
- Long and short prompts land on the same GPU in turn, and the long ones pile up.
"Which GPU has capacity?" → a capacity registry
- Each replica publishes on a heartbeat of about one second, and piggybacks it on every response:
- Free KV blocks
- Sequences running
- Sequences waiting
- Health
- The router scores a replica by free KV left after reserving the new request's estimated tokens. Queue length breaks ties.
Power of two choices
- Registry data is always slightly stale.
- If every router picks the single best replica, they all pick the same one and herd onto it.
- Instead: sample two replicas at random and send to the better.
- Spreads load almost as well as perfect knowledge and tolerates stale data.
- The replica makes the final check: if it can't fit the request, it rejects quickly and the router tries its next choice.
Prefix affinity
- Hash the prompt's shared prefix (such as a system prompt) to a preferred replica, so its cached prefix blocks get reused.
- Override affinity when that replica is hot. A cache hit isn't worth a queue.
Admission decides how much work gets in
- An unbounded queue turns overload into latency for everyone, then timeouts for everyone. Refuse early and explicitly.
- Each tenant holds a token bucket charged by estimated tokens, not request count, so one tenant's long prompts can't starve another's short ones.
- The queue behind it is bounded.
| Condition | Response | Why |
|---|---|---|
| Tenant over its own budget | 429 Too Many Requests | The tenant exceeded its quota |
| Shared queue full | 503 Service Unavailable with Retry-After | More accurate: the caller did nothing wrong |
- Both tell well-behaved clients when to come back.
The bound follows from Little's Law
queue wait = queue length ÷ drain rate.- A queue deeper than the latency objective allows only serves requests that already failed their objective.
- Those requests consume GPU time and still arrive late.
Backpressure flows upstream
replicas signal saturation via the registry → router stops sending → admission tightens → gateway rejects
- Shed by priority: interactive traffic stays; offline traffic moves to a batch tier.
- The Observability and Production Diagnosis case answers its provider-limits scenario the same way.
- The High-Volume Batch Inference Pipeline case applies it at batch scale: admission control belongs before the quota breach, not after.
- Measure queue wait separately from service time, or peak overload looks like a slow model.
Soundbite: "Route by free KV with two random choices; refuse overload at admission with 429 or 503 and Retry-After."
8. Recover a Failed Worker Without Amplifying Failure
- A GPU fails in ways a process check can't see: the process stays alive while the device throws memory errors or hangs mid-kernel.
- Three health-check layers, each answering a different question:
| Check | Question it answers | Action on failure |
|---|---|---|
| Liveness | Is the process running? | Restart the process |
| Readiness | Is the model loaded and the scheduler accepting? | Remove from the registry; send no traffic |
| Deep probe | Can it generate one token inside, say, 200 ms? | Drain and evict; alert on repeated failure |
Recovery depends on what the caller has seen
- A failed replica takes its KV cache with it, so in-flight sequences can't simply continue elsewhere.
| Caller has seen | Action | Caveat |
|---|---|---|
| No token streamed | Retry from scratch on another replica | Caller sees only extra latency |
| Tokens streamed | Re-prefill the original prompt plus emitted tokens on a new replica and continue, if the product's continuation contract allows | Greedy decoding: very likely to match, not guaranteed (batch size and GPU kernels change floating-point results). Sampling: text may diverge |
| Tokens streamed, no continuation contract | Explicit error carrying the partial output | The honest alternative; the product decides which |
Retries need a budget
- When a zone degrades, naive retries multiply load just as capacity drops: a retry storm.
- Cap retries at a fixed share of traffic, such as 10%, with jittered backoff.
- Key them by request ID, so a duplicate is detected rather than re-run.
- Keep N+1 headroom per zone and fail over between zones at the router.
Headroom, not autoscaling, absorbs a sudden loss
- A new GPU replica often takes minutes to provision, pull its image and load weights.
- The source's references: weight loading alone can take seconds with a fast streamer; provisioning is what takes minutes.
- Upgrades follow the same logic: drain before upgrading, canary the new version, stop the rollout when the canary fails.
Soundbite: "Unstreamed work retries under a budget; streamed work needs an explicit continuation or partial-error contract."
9. Prove the Design With the Actual Traffic
- The replica count is arithmetic on assumed rates. The design isn't finished until a load test with the real model confirms it.
Load-test
- The actual prompt and output distributions
- Long-prefill interference
- Stale capacity heartbeats
- Overload
- Cancellation
- Loss of a worker and of a zone
Track
| Metric group | What to track |
|---|---|
| Latency | p50 and p95 TTFT and TPOT |
| Queueing | Queue wait and service time, separately |
| Throughput | Prefill and decode throughput |
| Memory | Prefix-cache hit rate, KV occupancy and preemptions |
| Contracts | Cancellation delay, explicit failures |
| Outcome | Goodput |
The falsifying metric
- Goodput is the number that would prove the design wrong.
- If throughput rises while goodput falls, the fleet is finishing more work too late.
Soundbite: "If throughput rises while goodput falls, the fleet is finishing more work too late."
Quick Recall: Lines to Say in the Interview
- "A GPU is a stateful server with a memory budget."
- "Prefill sets first-token time, decode sets streaming speed, and the KV cache decides how many requests fit."
- "First token under 500 ms at p95 at 1,000 rps is a constraint; 'fast' is a preference."
- "0.15 replica-seconds, about 214 replicas at 70%; Little's Law says about 110, so compute binds."
- "Admission is the only place load is refused."
- "The router decides where, never how; the replica has the final KV check."
- "Two random choices tolerate stale registry data; round-robin ignores memory."
- "Retries are capped at about 10% of traffic and keyed by request ID."
- "Goodput, not raw throughput, proves the design."
Technical deep dives
The goal: the mechanisms behind follow-up questions: KV arithmetic, then the four related prompts (one GPU, 100,000 rps, a junior design review, a latency diagnosis).
30-Second Cheat Sheet
- KV per token:
2 × 32 × 8 × 128 × 2 = 131,072bytes = 128 KiB. Anchor sequence ~160 MB; 64 of them ~10 GB; an 8,000-token sequence ~1 GB. - Context length divides concurrency, so the router tracks free KV, not request counts.
- Paged KV in 16-token blocks; share only identical prefixes; preempt, never crash when the pool fills.
- One GPU: size-or-timeout flush (100 or 20 ms), futures by request ID, queue bounded at two batches (200), then 503.
- 100,000 rps: price the request shape first; fleets range ~2,570 to ~21,400 replicas. Then cells, token admission, backpressure, headroom.
- Junior review: lead with static batches, the unbounded FIFO and round-robin. Three ranked fixes, not eleven findings.
- Latency stack: ask which latency first. Frozen screen → prompt, queue, prefill. Drags → output, batch, decode. Gap at the end → post-processing.
1. KV Arithmetic, Paged Allocation and Preemption
- The KV cache, not compute, usually caps how many sequences fit on a GPU.
- Every token, prompt or generated, adds a key and a value vector per layer. They stay resident until the sequence ends.
The assumed architecture
- These are assumptions. A different attention design or cache datatype changes the result.
| Input | Assumed value |
|---|---|
| Layers | 32 |
| KV heads (grouped-query attention) | 8 |
| Head dimension | 128 |
| Bytes per value (fp16) | 2 |
Per token
2 (keys and values) × 32 layers × 8 KV heads × 128 dimensions × 2 bytes = 131,072 bytes = 128 KiB
Grouped-query attention (GQA) = several query heads share one key-value head. That's why the count is 8, not the full number of query heads, and it shrinks the cache.
Scale it
| Sequence | KV needed | What fits |
|---|---|---|
| Anchor: 1,250 tokens (1,000 in, 250 out) | about 160 MB (156 MiB) | |
| Sixty-four anchor sequences | about 10 GB | Fits beside 16 GB of fp16 weights on an 80 GB card |
| One 8,000-token sequence | about 1 GB | A ~50 GB KV pool holds only about 50 sequences |
- Context length divides concurrency. That's why the router must track free KV, not request counts.
Paged allocation
- Reserving each sequence's max length up front wastes most of that memory, because most sequences stop early.
- Paged attention allocates KV in small fixed-size blocks on demand. vLLM's default block holds 16 tokens.
- Blocks need not be contiguous, so fragmentation mostly disappears.
- Blocks can be shared: requests with an identical system prompt point at the same prefix blocks. That's prefix caching at the serving layer.
- Share only identical prefixes.
Preemption
- When the pool fills anyway, the scheduler chooses a victim.
| Option | How | Where |
|---|---|---|
| Recompute | Preempt the lowest-priority or youngest sequence; recompute its KV later | vLLM V1's default |
| Swap | Move it to CPU memory | Engines that support it (vLLM's older V0 engine offered swap) |
| Never | Let an allocation failure crash the replica | Turns one long prompt into an outage for the 64 callers sharing the GPU |
- These engine behaviours are the source's captured references, checked in September 2026. Confirm the block size and preemption options of the runtime you actually deploy.
Soundbite: "128 KiB a token: 160 MB for the anchor, 1 GB at 8,000 tokens. Context length divides concurrency."
2. One GPU With Synchronous Callers
- The anchor with the distribution removed: one GPU, up to 100 inputs per batch, callers who block until they get an answer.
- The design shrinks to intake → batcher → GPU → back to the right caller.
Trace one call
- The HTTP handler assigns a request ID, parks a future for it and enqueues the input.
- A batcher thread flushes at 100 inputs or when the oldest has waited, say, 20 ms, so a lone request at quiet times isn't stuck waiting for company.
- The GPU worker runs the batch.
- The demultiplexer resolves each future by request ID, and the handler returns.
- A timeout on the future turns a stuck batch into an error rather than a hung connection.
Future = an object the handler waits on until a result is filled in.
Say the arithmetic
| Step | Value |
|---|---|
| Full batch of 100 takes (assumed) | 200 ms |
| Max throughput | 100 ÷ 0.2 s = 500 rps |
| At 400 rps | GPU about 80% busy, if batch time scales roughly with batch size |
| Caller latency | batching wait + queue time + 200 ms |
| Open connections (Little's Law) | 400 rps × ~0.3 s ≈ 120: trivial until overload, when it grows without limit |
- Caveat: if a smaller batch takes nearly as long as a full one, the GPU is busier than 80%. Measure batch time against batch size before trusting the figure.
- Queues start to form in bursts.
Bound the queue
- Bound it, for example, at two batches (200 requests). Beyond that, 503 with Retry-After.
- Two batches means a new arrival waits at most about two batch times before its own batch runs.
- Pick the bound from the latency callers can tolerate; two isn't universal.
The follow-up that changes the answer
- Variable-length output? A static batch of 100 finishes at its longest member.
- Move to continuous batching, even on one GPU. The number of devices doesn't remove the longest-sequence problem.
Soundbite: "Size-or-timeout flush, futures by request ID, a queue bounded at two batches, then 503."
3. One Hundred Thousand Requests Per Second
- At this scale the request shape decides everything. Price it before drawing anything.
- Same replica-seconds method, same assumed rates, same 70% target.
| Request shape | Input / output tokens | Replica-seconds each | Replicas at 100,000 rps and 70% |
|---|---|---|---|
| Chat answer | 1,000 / 250 | 0.15 | ~21,400 |
| Short completion | 200 / 20 | 0.018 | ~2,570 |
| Scoring, one token out | 500 / 1 | 0.0254 | ~3,630 |
Work two rows
- Short completion:
200 ÷ 20,000 + 20 ÷ 2,500 = 0.010 + 0.008 = 0.018. - Scoring:
500 ÷ 20,000 + 1 ÷ 2,500 = 0.025 + 0.0004 = 0.0254.- It emits one token yet costs more than a short completion: its longer prompt makes prefill dominate.
- Fleet column:
× 100,000 ÷ 0.7.
Challenge the mix, not the count
- The spread is almost an order of magnitude: about 2,570 to about 21,400 replicas.
- The air-gapped chapter's advice: expect an absurd replica count from some mixes, and challenge the mix instead of defending the count.
- These are planning comparisons on assumed rates, not purchase counts.
Four things the architecture adds
| Addition | What it does |
|---|---|
| Cells | Independent cells of a few hundred replicas, each with its own router and registry, behind a global load balancer across cells and regions. A bad deploy or hot tenant damages one cell, not the service |
| Admission by tokens | At 100,000 rps, request counts lie. Charge each tenant's bucket by estimated tokens; shed lowest priority first |
| Backpressure across layers | Cells report saturation upward; the global balancer shifts traffic before a cell's queue deepens |
| Headroom over autoscaling | New replicas often take minutes to provision and load: autoscaling follows the daily curve, reserved headroom absorbs bursts and failures |
- Prefix caching and short output caps are the cheapest capacity at this size: they cut replica-seconds per request directly.
Soundbite: "What is each request? Chat and short completion differ almost tenfold in fleet size."
4. Review a Junior Design
- Not a design question. It hands over a design and asks what to change, so the anchor becomes the rubric.
The order
- Open with what works.
- Clarify the requirements the design assumed.
- Name the top three risks by severity, rather than every flaw you can find.
- The table is the checklist to search with, not the script to read aloud.
| Look for | Why it breaks | Change it to |
|---|---|---|
| Static batches for generative output | Short answers wait for the longest in the batch | Continuous batching |
| Flush only when the batch is full | At low traffic, a request waits forever for company | Size-or-timeout flush |
| One global FIFO queue, unbounded | Overload becomes timeouts for everyone; no fairness | Bounded per-tenant admission, 429 early |
| Round-robin routing | Ignores memory; long prompts pile onto one GPU | Route by free KV, power of two choices |
| Sizing by GPU count | No link between traffic and capacity | Token work per request, Little's Law cross-check |
| Health check is a TCP ping | A hung GPU stays in rotation | Readiness plus a one-token probe |
| Unlimited retries | Retry storm when a zone degrades | Retry budget, jitter, request_id dedupe |
| No request ID through the pipeline | Responses can reach the wrong caller | Demux by request_id end to end |
| No cancellation | Abandoned requests burn GPU time | Propagate disconnect, free KV |
| Tokenizing on the GPU thread | CPU work stalls the most expensive resource | Tokenize at the gateway |
| One latency metric | Queue wait looks like a slow model | Separate TTFT, TPOT, queue wait and service time |
FIFO = first in, first out. TCP = the protocol that gives an ordered, reliable byte stream between two machines; a TCP ping proves the host answers, and a hung GPU still answers.
Lead with the first three rows
- Each one breaks the service for everyone:
- Static batches waste most of the GPU on variable output.
- An unbounded global FIFO turns overload into universal timeouts with no fairness.
- Round-robin ignores the memory that actually limits placement.
- Then inspect the rest: size-only flush, weak health checks, unlimited retries, missing request IDs, no cancellation, tokenisation on the GPU thread.
Deliver it as a conversation, not a verdict
- Three ranked fixes, each with the failure it prevents → shows seniority.
- Eleven findings read aloud → shows only that the list was memorised.
Soundbite: "Three fixes, ranked: continuous batching, bounded token-weighted admission, routing by free KV."
5. Walk the Latency Stack
- The prompt asks for the full stack: tokenisation, network, batch size, KV cache and post-processing.
- The Observability and Production Diagnosis case answers it from the application's traces. This section answers it from inside the serving layer.
- First ask which latency is slow: first token, per token or total. Each points at different layers.
| Layer | Symptom | Likely cause | Check |
|---|---|---|---|
| Tokenization | Slow before the request reaches a queue | Long inputs tokenized on a starved CPU pool | Gateway span time; CPU saturation |
| Network | Slow for one region or client | Cross-region hop, TLS setup, a buffering proxy | Client-to-gateway span; TTFT by region |
| Queue wait | TTFT slow only at peak; p99 up, p50 flat | Utilisation past the knee | Queue wait against service time |
| Batch size | TPOT slow while throughput looks healthy | Batches too large for the per-token SLO | TPOT against running sequences |
| Prefill | TTFT slow on long prompts | Prompt growth, prefills stalling decode | TTFT by input tokens; chunked prefill on or off |
| KV cache | Latency spikes, preemptions | Pool full; low prefix-cache hit rate | KV use, preemption count, prefix hit rate |
| Decode | Starts fast, then drags | Output length grew | Output tokens per request |
| Post-processing | Gap after the last token | Safety filter, schema validation, detokenization | Span after final token |
TLS = the encryption that protects data in transit (the S in HTTPS). p99 = the value 99% of requests beat.
The rule that carries most diagnoses
| What the user sees | Points at | Check |
|---|---|---|
| Frozen screen (slow first token) | The prompt, the queue or prefill | Client and network, CPU tokenisation, queue wait, long-prompt prefill, KV preemption |
| Starts fast, then drags (slow per-token) | Output length, oversized batches, decode saturation or prefill interference | Output tokens, TPOT against running sequences |
| Gap after the last token | Detokenisation, safety or schema post-processing, or a buffering proxy | Span after final token |
The peak-only follow-up
- p50 flat, p99 rising only at peak → queueing.
- Separate queue wait from service time, then tighten admission and shed non-interactive traffic.
- Changing the model doesn't fix a buffering proxy or a starved CPU tokenizer.
Soundbite: "Which latency is slow? A frozen screen and a dragging answer point at different layers."
6. References and Source Notes
- The source fact-checked these references on 27 September 2026.
| Reference | Claim it supports |
|---|---|
| NVIDIA H100 datasheet | The assumed 20,000 tokens/s prefill for an 8B model needs H100-class compute |
| Hugging Face tokenizers: Decoders | Streaming decode must buffer partial characters |
| Agrawal et al. 2024, Sarathi-Serve | A long prefill stalls co-batched decodes; chunked prefill fixes it |
| vLLM docs: Optimization and Tuning | vLLM V1 preempts by recompute by default; chunked prefill |
| Kwon et al. 2023, PagedAttention | KV memory caps concurrency; max-length reservation wastes memory; paged, non-contiguous blocks |
| vLLM API: CacheConfig | Default KV block size of 16 tokens |
| Mitzenmacher 2001, The Power of Two Choices in Randomized Load Balancing | Two random choices spread load almost as well as full information |
| Mitzenmacher 2000, How Useful Is Old Information? | Two choices tolerate stale load data |
| Thinking Machines 2025, Defeating Nondeterminism in LLM Inference | Greedy output can differ across batch sizes and kernels |
| NVIDIA blog: Reducing cold-start latency with Run:ai Model Streamer | Weight loading alone can take seconds; provisioning is what takes minutes |
| Azure SDK blog: Load models up to 6x faster with Run:ai Model Streamer | Faster weight streaming for cold starts |
| vLLM docs: OpenAI-compatible server | The engine aborts a request when the client disconnects |
| vLLM issue #10087 | The abort breaks when middleware fails to pass the disconnect on |
Where the design comes from
- General serving practice: continuous batching, paged attention and the engines that use them.
- The site's air-gapped design case: the replica memory budget and sizing formula.
- The site's cost and latency material: the prefill, decode, Little's Law and goodput arithmetic.
- Internal companion notes not part of the captured page:
- An additions file: the two phases, Little's Law, the utilisation knee, goodput and cancellation.
- A decomposition-questions file: "which latency is slow?".
- A cost-drivers file: cold starts.
- Their claims are kept where the page stated them; the notes themselves couldn't be checked.
- Hardware figures: peak BF16 compute and memory bandwidth from NVIDIA's H100 and A100 specifications.
- Status codes: RFC 6585, section 4 and RFC 9110, section 15.6.4.
Quick Recall: Lines to Say in the Interview
- "131,072 bytes, 128 KiB a token, with eight KV heads under grouped-query attention."
- "An 8,000-token context needs about 1 GB, so a 50 GB pool holds about 50 sequences."
- "Paged KV in 16-token blocks; share only identical prefixes."
- "When the pool fills, preempt and recompute; never crash the replica for 64 callers."
- "One GPU: 100 inputs or 20 ms, a queue of two batches, then 503 with Retry-After."
- "Scoring emits one token yet costs more than a short completion, because prefill dominates."
- "Challenge the request mix instead of defending the replica count."
- "Lead the review with static batches, the unbounded FIFO and round-robin."
- "p50 flat and p99 up only at peak means queueing, not a slow model."
Quick review
One sentence: tokenize and admit before GPU work, route by free KV, schedule continuously, stream by request ID, cancel abandoned work and handle GPU failure with a bounded, honest retry policy.
30-Second Cheat Sheet
- Ask first: tokens in and out at p50 and p95, interactive or batch, TTFT or TPOT, variable output, peak and tenants, the mid-stream failure contract.
- The path: gateway → token-weighted bounded admission → router by free KV → continuous batch → prefill and decode on paged KV → demux by ID → stream.
- The anchor sum: 0.15 replica-seconds → ~214 replicas at 70%; ~7,000 streams ÷ 64 slots ≈ 110, so compute binds.
- KV: ~128 KiB a token → ~160 MB an anchor sequence, ~1 GB at 8,000 tokens.
- Placement: KV memory, not request count.
- Failure: unstreamed → retry under a budget; streamed → explicit continuation or partial error.
- Overload: refuse early with bounded queues; optimise goodput, not raw throughput.
- All rates are illustrative H100-class assumptions, not benchmarks.
1. Ask First and Draw the Path
Ask first
- Input and output tokens at p50 and p95?
- Interactive or batch?
- Is the target TTFT (time to first token) or TPOT (time per output token)?
- Does output length vary?
- Peak rate, tenants and priorities?
- What's the contract after a mid-stream failure?
The whiteboard path
gateway tokenises and assigns an ID → token-weighted bounded admission → router by free KV → replica continuous batch → LLM prefill and decode on paged KV → demultiplex by ID → stream
- Health checks evict sick GPUs.
- A disconnect cancels the sequence and frees its KV.
2. Recall the Arithmetic and Five Rules
The assumed anchor arithmetic
| Item | Value |
|---|---|
| Replica-seconds per request | 1,000/20,000 + 250/2,500 = 0.15 |
| Compute-bound fleet | 1,000 rps × 0.15 ÷ 0.70 ≈ 214 replicas |
| Slot-bound fleet | about 7,000 in-flight streams ÷ 64 slots ≈ 110 replicas |
| Which binds | Compute |
| KV per token | about 128 KiB |
| KV per anchor sequence | about 160 MB |
| KV at 8,000 tokens | about 1 GB |
- The rates are illustrative H100-class assumptions, not benchmarks.
Five rules
- Prefill sets TTFT; decode sets TPOT and total time.
- Static generative batches wait for the longest output; continuous batches release finished sequences.
- KV memory, not request count, decides GPU placement.
- Unstreamed failed requests retry under a budget; streamed ones need an explicit continuation or partial-error contract.
- Refuse early with bounded queues, and optimise goodput, not raw throughput.
3. Recall the Variants and Close
| Variant | What to say |
|---|---|
| One GPU | Size-or-timeout batch of 100, request-ID futures, a queue bounded at about two batches |
| 100,000 rps | Price the request shape first, then independent cells, token admission and global backpressure |
| Junior-design review | Lead with static batches, the unbounded FIFO and round-robin routing |
| Latency diagnosis | Ask which latency first, then split queue and prefill from decode and post-processing |
| Cost | Measure, route, bound, cache safely, proven by goodput per GPU-hour |
Sixty-second close: "Tokenize and admit before GPU work, route by free KV, schedule continuously, stream by request ID, cancel abandoned work and handle GPU failure with a bounded, honest retry policy."
Flashcard Drill
Quick Recall: Lines to Say in the Interview
- "Which latency matters: first token, per token or total?"
- "What does the caller see if a GPU dies mid-stream?"
- "0.15 replica-seconds, about 214 replicas; about 110 by slots, so compute binds."
- "128 KiB a token: 160 MB for the anchor, 1 GB at 8,000 tokens."
- "KV memory, not request count, decides placement."
- "Continuous batches release each sequence the step it finishes."
- "Refuse early with bounded queues; optimise goodput, not raw throughput."
- "Cost is measure, route, bound, cache safely, proven by goodput per GPU-hour."
Where next
- Revise the concepts