Serving people who wait: latency, GPU memory and autoscaling
- Split a streamed answer's wait into time to first token and time per output token, and report each as a percentile
- Work out how many conversations fit on one GPU from the weights and the KV cache each one holds
- Explain why a decode step costs about the same for 1 sequence as for 64, and find the largest batch that meets a per-token target
- Keep a long prompt from freezing everyone with chunked prefill, and skip a shared prompt's prefill with a prefix cache
- Size a fleet with Little's law, and scale it on queued requests and cache use rather than on how busy the GPUs look
Sizing a token service, the way the design round asks
A prep site's guide lists designing a token-generation service for 100,000 requests a second for Anthropic (1 source), and another lists GPU scheduling and autoscaling for a ChatGPT-style service for OpenAI (1 source). Both start from the same numbers: how many conversations one GPU holds, how fast it decodes them, and how many GPUs the traffic needs. This lesson's practice problem computes them, in three levels:
kv_bytes_per_token(model)andsequences_that_fit(model, gpu, context): the cache one token holds, and how many conversations fit in a GPU's memory after the weights.step_ms(model, gpu, batch, context)andlargest_batch(model, gpu, context, target_ms): one decode step's time, and the biggest batch that meets a per-token target.gpus_needed(model, gpu, context, target_ms, rate, first_token_s, output_tokens): the fleet a traffic rate needs, from Little's law.
Call Returns kv_bytes_per_token(qwen)57,344 bytes sequences_that_fit(qwen, h100, 2000)477 conversations largest_batch(qwen, h100, 2000, 15)305, the batch a 15 ms target allows gpus_neededfor 100,000 requests a second1,662 H100s
The lesson follows an outdoor shop's support assistant on one H100: the two clocks of a streamed answer, the memory budget, the batch trade, long prompts, and a fleet that follows traffic. Eight steps end with a small task in the editor.
A streamed answer has two clocks
An outdoor shop sells tents, tarps and lanterns, and its website has a support assistant. A customer types a question, and the assistant answers from the shop's own instructions and catalog. Every request looks about the same:
The shop runs an open model, Qwen2.5-7B-Instruct, on one rented H100 GPU. This lesson times those requests, works out how many fit on the GPU at once, and sizes a fleet for far more traffic. Anthropic's inference roles optimize latency and throughput (1 source), and Netflix hires engineers who build high-traffic services for online inference (1 source).
The first token waits for the whole prompt, and every later token waits for one step
A streamed answer is timed by two clocks. The time to first token (TTFT) runs from sending the request to the first token: Anthropic's docs define it as the time to generate the first token, from when the prompt was sent. The time per output token (TPOT) is the average gap between the tokens after that: the last token's time minus the first's, over the gaps between them. DistServe, a paper on serving, splits the work the same way: TTFT belongs to the prefill phase and TPOT to the decoding phase.
Here's one of those requests, timed token by token. latency_split returns both clocks, and you'll write it two steps from now.
# the assistant's 250-token answer
token_times = [0.35 + 0.03 * i for i in range(250)]
# sent at 0.0 s
ttft, tpot = latency_split(0.0, token_times)
print(f"first token after {ttft:.2f} s, then one every {tpot * 1000:.0f} ms")
print(f"last token at {token_times[-1]:.2f} s")
The first token arrives at 0.35 s and the rest follow 30 ms apart. When does the 250th token arrive?
An answer's first token arrives in 0.3 s, but the answer takes 12 s to finish. Where do you look first?
On a laptop CPU, reading the prompt was 45 times cheaper per token than writing the answer
The two phases cost very different amounts per token. A small model, timed on a laptop, shows how different.
# 512 prompt tokens
prompt = torch.randint(0, 1000, (1, 512))
# prefill: one forward pass over all of them
logits, caches = model(prompt)
token = torch.randint(0, 1000, (1, 1))
# decode: one token, against the cache
logits, caches = model(token, caches)
These two calls were timed on a GPT built from the kv-cache lesson's cached attention, 8 layers of width 512, about 26.8 million parameters, on one laptop CPU with 4 threads. The medians of three runs:
Prefill took 92 ms for all 512 prompt tokens. Each decode step took 8.1 ms for one token.
Prefill pushes all 512 tokens through each weight matrix in one pass, as one big matrix product. Decode pushes one token through the same matrices, so it does a sliver of the arithmetic for the same trip through the weights. The kv-cache lesson showed why: decode waits on memory, not on arithmetic.
That's why the first clock is short for a long prompt and the second clock adds up. On a GPU the gap is wider still.
Stream the tokens, so reading starts with the first one
Streaming decides when the customer starts reading.
Same model, same answer, same 7.82 s. Streaming moves when the reading starts.
Without streaming, the server holds the answer until the last token, and the customer stares at a spinner for 7.82 s. With it, each token goes out as soon as it's decoded. Anthropic's API streams with server-sent events, a long HTTP response that the server keeps writing to, when a request sets stream to true. OpenAI's guide puts the reason plainly: "Streaming lets the user start reading before generation finishes."
With streaming on, which clock does the customer notice first?
Report each clock as percentiles
This is a simulated day of 1,000 requests, not a measured one: a random queue wait, and one customer in five pastes a 9,000-token order history into the chat.
import random
rng = random.Random(7)
# seconds, one per request
ttfts = []
for _ in range(1000):
# time in the queue, 50 ms on average
wait = rng.expovariate(1 / 0.05)
# one in five pastes an order history
prompt = rng.choice([1860, 1860, 1860, 1860, 9000])
# prefill: 30 microseconds a prompt token
ttfts.append(wait + prompt * 0.00003)
mean = sum(ttfts) / len(ttfts)
print(f"mean {mean:.3f} s")
print(f"p50 {percentile(ttfts, 50):.3f} s, p95 {percentile(ttfts, 95):.3f} s, p99 {percentile(ttfts, 99):.3f} s")
The median TTFT comes out near 0.1 s. Where does the mean land?
The weights take a fixed share, and each conversation's cache takes the rest
The numbers come from the model card: 7.61 billion parameters, 28 layers, and 28 query heads sharing 4 key and value heads. The config file gives a hidden size of 3,584, so each head is 3,584 / 28 = 128 numbers wide. NVIDIA lists 80 GB of memory for the H100 SXM.
# Qwen2.5-7B-Instruct
params = 7.61e9
# bf16, a 16-bit number format: 2 bytes a value
bytes_per_value = 2
layers, kv_heads, head_dim = 28, 4, 3584 // 28
weights_gb = params * bytes_per_value / 1e9
# a key and a value, every layer
kv_per_token = 2 * layers * kv_heads * head_dim * bytes_per_value
# one 2,000-token conversation
kv_per_seq_gb = kv_per_token * 2000 / 1e9
# keep 10 GB for activations
room_gb = 80 - weights_gb - 10
print(f"weights {weights_gb:.1f} GB, cache {kv_per_token:,} bytes a token, {kv_per_seq_gb:.3f} GB a sequence")
print(f"{room_gb:.1f} GB of room holds {int(room_gb // kv_per_seq_gb)} sequences")
After the 15.2 GB of weights and a 10 GB reserve, how many 2,000-token conversations fit in the H100's 80 GB?
Longer conversations take more of the room
The cache grows with every token, so longer conversations take more of the room.
for context in (2000, 4000, 8000, 32000):
fits = int(room_gb // (kv_per_token * context / 1e9))
print(f"{context:6,} tokens each: {fits:3} sequences")
Customers start pasting order histories, and conversations grow from 2,000 tokens to 8,000. What happens to the 477?
What a bigger batch costs each user, and what it buys
Every decode step starts by reading the model's weights from the GPU's memory.
The H100 reads memory at 3.35 TB/s, which is 3.35 GB a millisecond. How long does one read of the model's 15.2 GB of weights take?
Going from 1 sequence to 64 multiplies the arithmetic by 64. How much longer does the step take?
Move the batch and watch which limit binds
Try the trade on the shop's GPU.
- Step
- 6.7 ms
- Each user
- 148 tok/s
- All users
- 9,504 tok/s
- Fit in memory
- 477
Slide the batch to the right at 2,000 tokens, and the KV cache bar grows until it meets the reserve at 477. Each user's speed falls slowly while the total climbs. Then switch to 32,000 tokens: 29 conversations fill the same memory, and the total tops out near 1,400 tokens a second.
A per-token target caps the batch, unless memory caps it first
Say the shop promises answers at 15 ms a token or faster, about 67 tokens a second. That's a per-token target, and it's the step time.
largest_batch tries each batch from 1 up to the number that fit in memory, and keeps the biggest whose step meets the target, or 0 when none does.
# 2,000 tokens a conversation, and 477 of them fit
print([largest_batch(QWEN, H100, 2000, target, 477) for target in (15, 30, 4)])
Which batch sizes come back for targets of 15 ms, 30 ms and 4 ms?
Treat these numbers as the best case, then measure
The step formula counts only the two unavoidable jobs. A real server also launches kernels, schedules requests, samples tokens and moves results to the CPU, so its steps run longer. Memory gets wasted too: the PagedAttention paper found that cache memory managed inefficiently "can be significantly wasted by fragmentation and redundant duplication, limiting the batch size." Its fix, paging, raised throughput 2 to 4 times over earlier servers at the same latency.
Use the formula for what it's good at: telling you which limit binds and roughly where. Then load-test the real server at a few batch sizes and plan from the measured curve.
In the editor, write step_ms(model, gpu, batch, context, utilization) and largest_batch(model, gpu, context, target_ms, fits) for any model and GPU. It prints the step at batch 64, then the batch each of three targets allows.
A long prompt in one step stalls every answer in progress
A customer pastes an 8,000-token order history while 64 others are mid-answer. A server that batches by step runs the new prompt's prefill inside one step, and nobody gets a token until that step ends.
# ms for one prompt token
prefill_ms = 2 * params / (989e12 * 0.5) * 1000
print(f"{prefill_ms * 1000:.1f} microseconds a prompt token")
print(f"8,000 tokens in one step: {8000 * prefill_ms:.0f} ms, while 64 users wait")
Prefill costs about 31 microseconds a prompt token here. How long do the 64 users wait for their next token?
Chunked prefill rides along with the decode steps
Cut the prompt into chunks, and prefill one chunk in each decode step. The step still reads the weights once, so the chunk's arithmetic rides along on a read the decoders were paying for anyway. Sarathi-Serve, the paper behind the idea, calls the result stall-free schedules, and vLLM ships it as chunked prefill.
import math
def step_with_chunk(batch: int, context: int, chunk: int) -> float:
"""One step that decodes batch sequences and prefills chunk prompt tokens."""
memory_ms = (weights_gb + batch * kv_per_token * context / 1e9) / 3.35
math_ms = 2 * params * (batch + chunk) / (989e12 * 0.5) * 1000
return max(memory_ms, math_ms)
for chunk in (256, 512, 2048):
ms = step_with_chunk(64, 2000, chunk)
steps = math.ceil(8000 / chunk)
print(f"chunks of {chunk:4,}: {steps:2} steps of {ms:4.1f} ms, the new prompt waits {steps * ms:3.0f} ms")
With chunks of 512 tokens, what do the 64 decoding users see?
A prompt every request shares is cached once
Every request to the assistant opens with the same 1,800 tokens of instructions and catalog.
# the assistant's instructions and catalog, then the question
shared, own = 1800, 60
print(f"prefill without the cache {(shared + own) * prefill_ms:.1f} ms, with it {own * prefill_ms:.1f} ms")
The 1,800 tokens of instructions and catalog are the same in every request. If their cache is kept, how much prefill is left?
Conversations in flight are the arrival rate times how long each one lasts
Start with how many conversations the shop holds at its busiest.
# requests a second at the shop's peak
rate = 5
# first token, then 249 more, 30 ms apart
seconds_each = 0.35 + 249 * 0.03
print(f"{rate * seconds_each:.0f} sequences in flight")
Five requests arrive each second, and each one lasts 7.82 s from sending to its last token. On average, how many are in progress at once?
Scale on requests waiting and cache in use, not on how busy the GPU looks
How busy a GPU looks says little about how full it is.
Busy is the share of time the GPU is running a step, about all of it at both batches. Cache is the batch's caches over the 54.8 GB of room: 0.9 GB at batch 8, 45.9 GB at batch 400.
A GPU that's decoding is busy every millisecond, whether the batch holds 8 sequences or 400, because each step reads all the weights either way. So the usual busy-time metric reads near 100% at both moments, and autoscaling on it would scale up a server that's almost empty.
Scale on what tracks the room left. vLLM exports both: vllm:num_requests_waiting, the requests waiting to be processed, and vllm:kv_cache_usage_perc, the share of the cache in use. The engineers serving ChatGPT named the same pair: the combination of batch size and KV cache utilization was the primary metric they focused on (1 source). Add capacity when the queue holds requests for longer than the TTFT budget allows, or when the cache stays above a target like 70%.
New GPUs take minutes to arrive, and sometimes none come
Traffic can change faster than new machines arrive.
Traffic doubles in one minute, and a new GPU takes ten minutes to start serving. What serves the extra customers in the meantime?
Each GPU holds 477 conversations and runs 70% full. How many GPUs do 5 and then 100,000 requests a second need, at 7.82 s each?
A worked example: a token-generation service for 100,000 requests a second
The prompt, from a prep site's Anthropic question list: design a scalable system for a token-generation service that handles up to 100,000 requests per second (1 source).
1. Clarify. Token can mean a model's output or an access token for an API. Ask. Here it's model output, so the next questions size it:
- Which model? Assume one the size of the shop's, 7.61 billion parameters in bf16.
- How long are the prompts and the answers? Assume the shop's: 1,860 tokens in, 250 out, 2,000 tokens of cache each.
- What do users expect? Streaming, a first token within 0.35 s, and tokens no slower than 30 ms apart.
- Is it steady or spiky? Plan for 100,000 as the peak.
Of these assumptions, which one moves the GPU count the most if it doubles?
Size the fleet from the step at a full batch
3. Size it. A 30 ms target lets memory set the batch at 477, and the step at that batch decides how long each answer lasts.
# every sequence that fits
batch = 477
# seconds a token at that batch
step = step_ms(QWEN, H100, batch, 2000, 0.5) / 1000
seconds_each = 0.35 + 249 * step
print(f"each answer takes {seconds_each:.2f} s, so {100_000 * seconds_each:,.0f} are in flight")
print(f"{gpus_for(100_000, seconds_each, batch, 0.7):,} GPUs at 70% full")
At a full batch each token takes 20.9 ms, not 30. Will the fleet be bigger or smaller than the 2,343 GPUs worked out at 30 ms?
The design, in the order you present it
4. The design. Present it in the order a request travels, then the loop that sizes the pools.
- A gateway checks the API key and applies per-customer limits on requests and on tokens, so one customer can't take the fleet.
- A router picks a GPU for each request. It routes by model, and by prompt prefix where it can, so requests that share a system prompt land where its cache already sits.
- Each GPU runs continuous batching from the batch-inference lesson, admits a new request only while its cache has room, and prefills long prompts in chunks.
- Tokens stream back to the client over server-sent events as each step produces them.
- An autoscaler reads requests waiting and cache in use from every GPU, and adds capacity ahead of the daily peak.
Name what breaks first, and how you'd know
Then say what breaks, starting with a GPU that dies mid-answer.
A GPU dies with 477 streams in progress. What can the service do for those requests?
The pipeline got slow. Split the time before you change anything
A prep site's Anthropic list asks how you'd debug a slow inference pipeline (1 source). Don't guess at the model. Split a slow request's time into its parts, and find the one that grew:
Each branch has its own fix, so the split is the debugging. A prompt change that made answers 40% longer looks exactly like a slower model in the total, and nothing like one in the split.
Fewer bytes per weight make every memory-bound step faster
Store the weights in 8 bits instead of 16, and every step reads half the weight bytes.
# 8 bits is 1 byte a weight
weights_8bit_gb = params * 1 / 1e9
# batch 1: the weights and one 2,000-token cache
read_gb = weights_8bit_gb + kv_per_token * 2000 / 1e9
print(f"weights {weights_8bit_gb:.1f} GB, a batch-1 step reads {read_gb:.1f} GB in {read_gb / 3.35:.1f} ms")
weights 7.6 GB, a batch-1 step reads 7.7 GB in 2.3 ms
That's 2.3 ms against 4.58 ms in 16 bits, and the 7.6 GB the weights free holds more conversations. The catch is accuracy: measure the quantized model on your own evals before it serves anyone.
Speculative decoding checks several guessed tokens in one step
A step that reads all the weights can check more than one token.
A decode step is mostly the weights read. Checking 5 drafted tokens in one step costs about as much as writing how many?
Separate machines for prefill and decode
Prefill is arithmetic and decode is reading, and on one GPU they get in each other's way. DistServe runs them on separate GPUs and hands each conversation's cache from the first to the second. Each pool then gets the batch size and the GPU count that suit its own target, at the cost of moving every cache across the network once.
Streaming to many users is a connection problem too
Streams also hold connections and cache slots, even after the reader leaves.
A customer closes the tab halfway through an answer. What should the server do with the generation?
GPUs for a ChatGPT-style service need pools, priorities and preemption
The GPU scheduling question (1 source) adds what one model hides. Keep a pool per model, sized by its own traffic. Give interactive requests priority over batch work, and let a full GPU pause a batch sequence to admit an interactive one. Move capacity between pools on a daily forecast, since a GPU can take minutes to load a different model.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.A decode step takes 4.6 ms for 1 sequence and 6.7 ms for 64 on the same GPU. What explains the small difference?
2.Which pair of metrics should trigger adding GPUs to an LLM serving pool?
3.When the service is busy, users see answers freeze mid-sentence for a fraction of a second. What's the likely cause?
4.Conversations on the shop's GPUs grow from 2,000 tokens to 8,000, with the same traffic and answer lengths. Roughly how many GPUs does the fleet need now?
5.You switch the weights of the 7.6 billion parameter model from 16 bits to 8, keeping the cache in 16. At batch 1, what happens to a decode step?
Where this shows up
The reports behind this lesson, each with its source.
Serving ChatGPT (as of Feb 2024): GPU RAM, not compute, was the most frequent bottleneck for LLM operations.
The primary serving metric was batch size combined with KV cache utilization.
GPU scarcity meant there were no GPUs to autoscale into (as of Feb 2024).
Staff+ Software Engineer, ML Inference Path (Safeguards) optimizes inference latency and throughput for real-time safety evaluations.
“Optimize inference latency and throughput for real-time safety evaluations while maintaining high reliability standards”
Software Engineer 4/5, Model Serving Systems (AI Platform) asks for high-traffic distributed services for online ML inference.
“You have experience building high-traffic distributed services and infrastructure for online ML model inference”
Practice
Sources (19)
- Reducing latency · Anthropic, Claude Platform Docs · Nov 19, 2026
“This metric measures the time it takes for the model to generate the first token of the response, from when the prompt was sent.”
- DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving · arXiv 2401.09670 (OSDI 2024) · Jan 18, 2024
“time to first token (TTFT) for the prefill phase and time per output token (TPOT) of each request for the decoding phase”
- Latency optimization · OpenAI API docs · Nov 19, 2026
“Streaming lets the user start reading before generation finishes.”
- Latency optimization · OpenAI API docs · Nov 19, 2026
“If an answer starts quickly but takes too long to finish, inspect what the model generates.”
- Streaming messages · Anthropic, Claude Platform Docs · Nov 19, 2026
“When creating a Message, you can set "stream": true to incrementally stream the response using server-sent events (SSE).”
- NVIDIA H100 Tensor Core GPU · NVIDIA, data center product page (spec table: H100 SXM, H100 NVL) · Nov 19, 2026
“GPU Memory 80GB 94GB GPU Memory Bandwidth 3.35TB/s 3.9TB/s”
- NVIDIA H100 Tensor Core GPU · NVIDIA, data center product page (spec table: H100 SXM, H100 NVL) · Nov 19, 2026
“BFLOAT16 Tensor Core * 1,979 teraFLOPS 1,671 teraFLOPS ... With sparsity”
- Qwen/Qwen2.5-7B-Instruct · Qwen team, Hugging Face model card · Nov 19, 2026
“Number of Parameters: 7.61B Number of Paramaters (Non-Embedding): 6.53B Number of Layers: 28 Number of Attention Heads (GQA): 28 for Q and 4 for KV”
- Qwen/Qwen2.5-7B-Instruct config.json · Qwen team, Hugging Face · Nov 19, 2026
“"hidden_size": 3584”
- Optimization and Tuning · vLLM documentation (latest) · Nov 12, 2026
“This feature helps improve both throughput and latency by better balancing compute-bound (prefill) and memory-bound (decode) operations.”
- Optimization and Tuning · vLLM documentation (latest) · Nov 12, 2026
“Chunked prefill allows vLLM to process large prefills in smaller chunks and batch them together with decode requests.”
- Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve · arXiv 2403.02310 (OSDI 2024) · Mar 4, 2024
“Sarathi-Serve introduces chunked-prefills which splits a prefill request into near equal sized chunks and creates stall-free schedules that adds new requests in a batch without pausing ongoing decodes.”
- Automatic Prefix Caching · vLLM documentation (latest) · Nov 12, 2026
“caches the KV cache of existing queries, so that a new query can directly reuse the KV cache if it shares the same prefix with one of the existing queries”
- Efficient Memory Management for Large Language Model Serving with PagedAttention · arXiv 2309.06180 (SOSP 2023) · Sep 12, 2023
“When managed inefficiently, this memory can be significantly wasted by fragmentation and redundant duplication, limiting the batch size.”
- Efficient Memory Management for Large Language Model Serving with PagedAttention · arXiv 2309.06180 (SOSP 2023) · Sep 12, 2023
“Our evaluations show that vLLM improves the throughput of popular LLMs by 2-4 ... with the same level of latency compared to the state-of-the-art systems”
- Production Metrics · vLLM documentation (latest) · Nov 19, 2026
“vllm:num_requests_waiting Gauge Number of requests waiting to be processed.”
- Production Metrics · vLLM documentation (latest) · Nov 19, 2026
“vllm:kv_cache_usage_perc Gauge KV-cache usage. 1 means 100 percent usage.”
- Fast Inference from Transformers via Speculative Decoding · arXiv 2211.17192 (ICML 2023) · Nov 30, 2022
“We demonstrate it on T5-XXL and show a 2X-3X acceleration compared to the standard T5X implementation, with identical outputs.”
- DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving · arXiv 2401.09670 (OSDI 2024) · Jan 18, 2024
“DistServe improves the performance of large language models (LLMs) serving by disaggregating the prefill and decoding computation.”