More and more design interviews include an LLM feature: a support chatbot, a document assistant, a code helper. The interviewer then asks "how many GPUs?", "why is the first word slow?" or "how do you cut the bill in half?". You can answer these without being a machine learning engineer. You need a small mental model: text becomes tokens, the model has a limited context, generation is one token at a time, a memory called the KV cache decides how many users one GPU can serve, and batching shares the GPU between users. This lesson builds that model and includes a sizing example.
1. Tokens
A model does not read letters or words. A tokenizer cuts text into tokens, pieces from a fixed list of about 100,000 entries. Common words are one token. Rare words, names, numbers and code split into several.
- Rule of thumb for English: 1 token is about 4 characters or 0.75 words. So 1,000 words is about 1,350 tokens.
- Other languages and code use more tokens for the same meaning, so the same message costs more and runs slower.
- Everything is priced and limited in tokens, not characters or requests. Count with the model's own tokenizer, not by guessing.
- Input and output are counted separately. The prompt (system instructions, chat history, retrieved documents, the question) is input. The reply is output. Providers charge more for output tokens, usually several times more. Section 5 shows why.
2. The Context Window
The context window is the most tokens the model can handle in one request: input plus output together. A request must fit this budget:
system prompt + history + retrieved documents + question + reserved reply <= context window
- Reserve the reply first. If the window is 8,192 tokens and you allow a 500-token reply, the prompt can use at most 7,692.
- History grows every turn. A chat sends the whole conversation again each time. With 200 input and 300 output tokens per turn, turn 10 sends about 4,700 tokens and the total sent over 10 turns is about 25,000, not the 2,000 you might expect. Trim old turns or replace them with a short summary.
- Big context is not free. It costs money, time and GPU memory (sections 3 and 4). Quality can also drop for facts buried in the middle of a very long prompt. Send what is needed, not everything you have.
3. How Generation Works
The examples in this lesson use one model and one GPU. They are typical, not exact, so treat them as assumptions to confirm with a load test:
- Model: 8 billion parameters, so the weights take 16 GB. It has 32 layers and 8 key-value heads of size 128 (the box below explains these terms).
- GPU: 80 GB of memory, 3.35 TB/s of memory speed, about 990 trillion calculations per second. We price it at a made-up $3 an hour.
- Request: a 2,000-token prompt and a 500-token reply.
Background note: What "an 8-billion-parameter model" means
A model is a very large list of numbers plus a fixed recipe that uses them. Think of a huge mixing board with billions of knobs. Training turns each knob a little at a time until the model predicts text well. After training the knobs are frozen, and every request only uses them.
- Parameter (or weight). One knob: a single decimal number, such as 0.0173 or -1.42. The two words mean nearly the same thing here. "8 billion parameters" means 8,000,000,000 such numbers.
- Stored in 16 bits (2 bytes) each. A computer stores every number in some number of bits. 8 bits make 1 byte, so 16 bits are 2 bytes. 8 billion numbers × 2 bytes = 16 billion bytes = 16 GB. That is what "the weights take 16 GB" means: the model's file, and the GPU memory it needs, are 16 GB. Storing each number in 8 bits halves this to 8 GB, and 4 bits halves it again (quantization, section 8).
- Layers. The model is a stack of 32 blocks. The text passes through block 1, then block 2, up to block 32, and each block refines what the model "understands" about every token. Each layer has its own share of the 8 billion numbers.
- Key-value heads of size 128. In every layer, each token looks back at the earlier tokens. To make this possible, every token leaves two short lists of numbers in each layer: a key (a label for what the token holds) and a value (what it passes on). A head is one separate way of looking. This model has 8 of them in each layer, and each key or value list has 128 numbers.
The key-value numbers are what the KV cache stores, so they set its size: 2 (key and value) × 32 layers × 8 heads × 128 numbers × 2 bytes = 131,072 bytes, or 128 KiB for every token. You do not need to know why the model has 32 layers or 8 heads. You need only these two sizes: 16 GB of weights that every decode step must read, and 128 KiB of cache that every token adds.
Every request has two phases:
- Prefill reads the whole prompt at once. All 2,000 tokens are processed in parallel, so this phase is limited by calculation speed. It takes about 65 ms here, which is about 30,000 prompt tokens per second. It sets the time to the first token.
- Decode writes the reply one token at a time, because each token depends on the one before. Every step must read all 16 GB of weights from memory to produce a single token. So this phase is limited by memory speed: 16 GB ÷ 3.35 TB/s is about 4.9 ms per step. One user alone gets about 205 tokens per second, and the calculating units are nearly idle.
That gap explains most of LLM serving. The GPU can do about 300 calculations in the time it takes to read one byte, but decode uses only a few. The fix is to share each read of the weights between many users. That is batching (section 5).
flowchart LR
C[Client] --> G[Gateway: auth and token limits]
G --> Q[Queue and router]
Q --> P[Prefill: whole prompt at once]
P --> D[Decode: one token per step]
D -- "stream each token" --> C
P -.-> K[(KV cache)]
D <-.-> K
4. The KV Cache
To write the next token, the model must look at every earlier token. Recomputing all of them at each step would be far too slow. So the model saves the key and value lists (see the box above) of every earlier token, in every layer. This store is the KV cache. It lives in GPU memory.
Each token costs 128 KiB of cache (worked out in the box above), for every token of every active conversation. The weights are a fixed 16 GB. The cache grows with users and context length. After the weights and a 15% safety margin, the GPU has 80 × 0.85 − 16 = about 52 GB left for cache:
| Context per chat | Cache per chat | Chats that fit in 52 GB |
|---|---|---|
| 2,250 tokens (our average) | 0.29 GB | 176 |
| 8,192 tokens | 1.07 GB | 48 |
| 32,768 tokens | 4.29 GB | 12 |
| 131,072 tokens | 17.2 GB | 3 |
One 131,000-token request uses as much cache as about 58 average chats. This is why long context is expensive even when a model allows it, and why interviewers ask "what limits users per GPU?". The answer is KV cache memory. Four techniques shrink or manage it:
- Grouped-query attention (a model design choice) uses 8 key-value heads instead of 32, so the cache is 4 times smaller. Our model already does this.
- Paged cache (as in vLLM) gives memory out in small blocks as a reply grows. Reserving the maximum length (say 8,192 tokens) for every request would fit only 48 chats instead of 176.
- Prefix caching keeps the cache of a shared prompt start, such as the system prompt, and reuses it. A request skips that part of the prefill.
- Context limits. Cap the prompt and the reply length so one request cannot take the whole cache.
5. Batching
Each decode step reads the weights once, no matter how many chats are in the batch. So adding chats is almost free for the weights. Only the cache reads grow. With a step time of (16 GB + 0.29 GB per chat) ÷ 3.35 TB/s, a few batch sizes give:
| Batch | Step time | GPU tokens/s | Per user tokens/s | Cost per 1M output tokens |
|---|---|---|---|---|
| 1 | 4.9 ms | 205 | 205 | $4.07 |
| 8 | 5.5 ms | 1,455 | 182 | $0.57 |
| 32 | 7.6 ms | 4,204 | 131 | $0.20 |
| 128 | 16.1 ms | 7,969 | 62 | $0.11 |
This is the central trade-off. A bigger batch gives lower cost and higher total speed, but each user waits longer per token. Going from batch 1 to batch 32 cuts the cost 20 times while each user still gets 131 tokens per second, far faster than anyone reads (about 5 to 6 tokens per second). So set a batch cap from your latency target. The figures are an upper bound that assumes the GPU reads memory at full speed. Real systems reach less, so measure with a load test.
- Continuous batching. Old static batching waited for every request in a batch to finish. Continuous (in-flight) batching lets new requests join and finished ones leave at every step, so the GPU stays full. Servers such as vLLM and TensorRT-LLM do this.
- Prefill interrupts decode. A 65 ms prefill pauses the other chats for 65 ms. Chunked prefill splits big prompts into pieces and mixes them with decode steps.
- Why output costs more than input. Prefill is fast and shared: about $0.027 per million prompt tokens here. Decode at batch 32 is $0.20 per million, about 7 times more. Output tokens also hold cache memory for the whole reply.
6. Latency
Two numbers describe an LLM response:
- Time to first token (TTFT): time in the queue plus the prefill (and network). The user sees nothing until this ends.
- Time per output token (TPOT): the step time at the current batch. It sets how fast text streams.
The total is TTFT + output tokens × TPOT. For our request at batch 32: 65 ms + 500 × 7.6 ms is about 3.9 seconds. That sounds slow, but with streaming the user sees the first words in about 100 ms and reads while the rest arrives. Stream with server-sent events (see the real-time lesson). Measure TTFT and TPOT at p50 and p99 separately.
Queueing matters too. As load rises, waiting grows by 1 ÷ (1 − utilization): 2 times at 50%, 5 times at 80% (the numbers lesson). Plan GPUs at about 70%, not 100%.
7. Worked Example: Sizing a Support Chatbot
A chatbot gets 500,000 requests a day. Each has a 2,000-token prompt and a 500-token reply. Peak is about 4 times the average.
- Per day: 500,000 × 2,000 = 1 billion input tokens, and 500,000 × 500 = 250 million output tokens.
- Rate: 500,000 ÷ 86,400 = 5.8 requests per second on average, so about 23 at peak. That is 46,000 prompt tokens and 11,600 output tokens per second at peak.
- GPU time at peak: prefill needs 46,000 ÷ 30,800 = 1.5 GPU-seconds each second. Decode at a batch cap of 32 needs 11,600 ÷ 4,204 = 2.75. The total is 4.25 GPUs of work.
- Headroom: at 70% utilization, 4.25 ÷ 0.7 = 6.1 GPUs. For a lost zone out of 3, multiply by 1.5: 9.1, so 10 GPUs, spread 4, 3 and 3. If the zone with 4 is lost, 6 GPUs remain at about 71%.
- Memory check: a batch of 32 chats needs 32 × 0.29 = 9.4 GB of cache, far below the 52 GB available. So the batch cap, not memory, is the limit here.
- Cost: 10 GPUs × $3 × 24 hours = $720 a day, which is $0.00144 per request.
Utilization drives cost. A fully busy GPU spends 65 ms + 500 ÷ 4,204 s = 0.18 s per request, which costs $0.00015. We pay $0.00144, which is 9 times more. The reason is that average demand is only 1 ÷ 4 of peak, so the 10 GPUs are busy about 11% of the day.
Loading a 16 GB model takes minutes, so autoscaling GPUs is slow. A common design is a small fixed GPU pool for base load and a paid API for bursts. At hypothetical API prices of $0.50 per million input and $1.50 per million output tokens, the same day costs 1,000 × $0.50 + 250 × $1.50 = $875.
8. Cutting Cost and Latency
- Shorter prompts and replies. Trim history, retrieve fewer documents, and set
max_tokens. Output tokens are the expensive ones. - Prompt caching. Put stable text (instructions, shared documents) first and the changing part last. A cache hit skips the prefill for the shared start, and many providers charge less for cached input.
- Response caching. If the same question comes again, return the saved answer. A semantic cache matches similar questions, but it can return a wrong answer, so use it only where that is acceptable.
- A smaller model, or routing. Send easy questions to a small model and hard ones to a big one. Fall back to the big model when the small one is unsure.
- Quantization. Store weights in 8 or 4 bits. Fewer bytes to read means faster decode, with a small quality loss. At batch 1, 8-bit is about twice as fast, and the gain shrinks at large batch because cache reads do not change.
- Speculative decoding. A small model drafts several tokens and the big model checks them in one step. It helps latency at low batch sizes.
- Batch jobs. Work that is not urgent (summaries, embeddings) can run off-peak or through a batch API at a lower price.
9. Serving Design Basics
- Rate limit by tokens, not requests. One 100,000-token request does the work of dozens of chat requests. Limit tokens per minute for each user, and count the reserved reply.
- Route by load and cache. Round robin ignores how full each GPU's cache is. Send requests to the replica with the shortest queue, and keep a conversation on one replica so its cache can be reused.
- Cancel when the client leaves. If the user closes the page, stop generating and free the cache. Otherwise you pay for text nobody reads.
- Shed load early. Put a limit on the queue and return a clear error when it is full (the resilience lesson). A long queue turns into timeouts for everyone.
- Timeouts and fallbacks. Set a limit on TTFT and total time. On failure, retry once, fall back to another model, or return a safe message.
10. Common Pitfalls
- Counting characters or words, not tokens.
- Forgetting that history is sent again each turn. Cost grows faster than the number of turns.
- Ignoring the reply when budgeting context. The prompt fills the window and the answer is cut off.
- Sizing from the average load, or planning GPUs at 100%. Peak is about 4 times higher, queueing delay explodes near full load, and a GPU cannot be added in seconds. Plan for peak at about 70%.
- Thinking memory is only the model weights. The KV cache decides how many users fit.
- Giving a single "latency" number. Track TTFT and TPOT, p50 and p99.
11. Interview Questions This Lesson Prepares You For
- What is a token, and what is the context window? A token is a piece of text, about 4 characters in English. Context limits, latency and price are all counted in tokens. The context window is the most tokens (input plus output) one request can hold, so reserve the reply and trim or summarize old turns.
- Why is the first token slow and the rest fast? The first token needs prefill, which processes the whole prompt before any output appears. Later tokens each need one decode step, which is much shorter. A long prompt makes TTFT longer, so trim prompts and use prompt caching.
- What is the KV cache and why does it limit users per GPU? It stores the key and value vectors of every earlier token so the model need not recompute them. It takes about 128 KiB per token for an 8B model, and it grows with each user's context. After the weights, the remaining GPU memory divided by the cache per chat gives the number of chats.
- How does batching cut cost, and what does it cost in return? Each decode step reads the weights once for all chats in the batch, so cost per token falls sharply (20 times from batch 1 to 32 in our example). The price is a longer step time, so each user gets fewer tokens per second. Set the batch cap from the latency target.
- How many GPUs do you need for 500,000 chats a day? Start with per-day tokens, convert to peak per second (4 times the average), add prefill time and decode time at a batch cap, divide by 70%, and add zone-loss headroom. Say the per-GPU speeds are assumptions from a load test.
- Self-host or use an API? An API has no idle cost and scales at once. Self-hosting wins when load is high and steady, so GPUs stay busy. For spiky load, run a small fixed pool and send bursts to an API.
- You must halve the cost of an LLM feature. What do you try? First shorter prompts and replies, then prompt and response caching, then routing easy requests to a smaller model, then quantization and batching. Measure quality after each change.