Systemsfor Aravinda
0 / 78 core
Week 8 · Modern systems

Serving LLMs

2.5 hours · core path

Read first: Latency numbers that matter, Caching, Load shedding

In one sitting

A generation request is a compute-heavy prefill followed by a decode that emits one token at a time and is limited by memory bandwidth. The KV cache stores attention keys and values and grows with batch size, sequence length, and layers, so GPU memory is the real constraint. Time to first token and tokens per second are different measurements, and a prompt that does not fit the batch has to wait or be refused.

A model server is a memory scheduler that happens to multiply matrices. The chip can do the math. The request fails, or everyone else slows down, when the attention state for the batch does not fit in GPU memory. Treat that memory as the scarce resource, the way you would treat a connection pool or a lock, and the rest of the serving design follows.

Core concepts

A request has two phases, and they hurt for different reasons.

Prefill reads the prompt and runs attention over it. This phase is compute-heavy. It produces the first output token and fills the cache the decode phase will reuse. A long prompt is a long prefill. The user sees none of that work until the first token arrives.

Decode then emits one token at a time. Each new token attends to every token already in the sequence. The math per token is small. The data moved per token is the whole cache. Decode is memory-bandwidth-heavy: the device spends the step pulling keys and values through memory so it can do a little arithmetic. Adding a faster matrix unit does not, by itself, make a bandwidth-bound decode faster.

The KV cache is that stored state. K and V are the attention keys and values. The cache exists so decode does not recompute the prompt on every token. It grows with three things you can point at:

  • batch size, how many sequences are resident together
  • sequence length, how many tokens each of those sequences has already accumulated, prompt plus generated tokens
  • layers, because each layer keeps its own keys and values

Hold the other two fixed and double one of them, and that request’s cache doubles. This is a shape, not a benchmark. Call the bytes for one token at one layer C. C depends on the model you loaded. You do not need its value to see the bill:

cache ≈ C × layers × (sum of sequence lengths in the batch)

If every sequence has length S and the batch holds B of them, the sum is B × S. A single prompt of length 8S costs the same cache as eight short sequences. GPU memory, not the API in front of the server, is what runs out. Weights occupy a fixed amount once the model is loaded. The cache is the part that moves as traffic and prompts change. When the sum no longer fits, you cannot admit the next sequence, no matter how idle the arithmetic units look.

Reservation waste. If you hand each request one contiguous block sized for the longest sequence you might ever generate, a short reply still held the max. The unused tail is fragmentation. PagedAttention, the allocator vLLM uses, pages the KV cache the way an operating system pages virtual memory. A sequence receives another page when it grows. Waste shrinks to the unused tail of the last page, instead of a hole the size of the maximum length. You can still run out of pages. Paging changes fragmentation. It does not cancel the product of batch, sequence, and layers.

Continuous batching. Static batching picks a group of requests and runs until the longest one finishes. A one-token reply sits in that group beside a long generation and cannot free its slot early. The idea in the Orca paper is to change membership at each step: when a sequence finishes, its slot can take a new request at the next step, and a new arrival does not wait for the slowest member of a closed group. Short requests stop blocking on long ones. The long one still holds cache pages for its whole life, so the scheduler can add a request only when pages remain.

Quantization stores weights, and sometimes the cache, in fewer bits. You spend quality to spend less memory. The room you get back can hold a larger batch or a longer sequence. Whether the quality loss matters is an eval question, a set of tasks with known outcomes, not a feeling about the demo. Do not attach a throughput number or a quality percentage to a named model unless you measured that pair.

Two SLIs. Time to first token is queueing plus prefill, up to the first token the user can read. Tokens per second is how fast decode emits after that. A chat box that sits blank is a time-to-first-token failure even if, once started, the stream is fast. A long answer that trickles is a decode failure even if the first token was quick. A single “throughput” graph smears them together. Latency numbers that matter still apply: the user experiences the hop they wait on, and a queue in front of a busy GPU is that hop.

The cache is a kind of caching with an awkward eviction story. Reusing pages for a shared prefix skips a repeated prefill, and those pages are then unavailable to someone else. Drop the prefix and every request pays prefill again. You are spending GPU memory to save compute, which is the same family of choice as any other cache, with a much smaller device behind it.

flowchart LR
  prompt[Prompt] --> prefill[Prefill]
  prefill --> cache[KV cache]
  cache --> decode[Decode one token]
  decode --> token[Output token]
  decode --> cache

Every output token returns to the cache. Sequence length is a running sum, so a request that fit at prefill can fail to fit later.

A worked example

You run one model server for a product that is mostly short chats, plus an agent that sometimes pastes a whole log into the prompt. You will not quote a tokens-per-second figure for the model. You will quote slots, because slots are what memory limits.

Assumptions, said out loud:

  • 1,000,000 requests a day reach this server.
  • The peak is 4 times the average. Peak factor is an assumption. A planning range people state is 2× to 5×. You picked 4×.
  • A typical short request occupies a batch slot for 3 seconds. That is an assumption about your prompts and your answer lengths, not a published speed for a named model.
  • One device has room for 16 of those short sequences at the same time. That is an assumption about this model and this memory size, expressed in short sequences so you never invent a byte count.
  • You currently have 4 devices.
1 day = 86,400 s
interview shortcut ≈ 100,000 s
1,000,000 / 86,400 ≈ 11.6 requests/s ≈ 12/s

assumption: peak is 4× the average
peak arrival ≈ 4 × 12 = 48 requests/s

assumption: a short request holds a slot for 3 s
slots to keep up ≈ 48/s × 3 s = 144

assumption: 16 short sequences fit on one device
devices to keep up ≈ 144 / 16 = 9

you have 4 devices → 64 slots
completion rate ≈ 64 / 3 s ≈ 21 requests/s
arrival 48/s exceeds 21/s
queue grows by about 48 − 21 = 27 requests each second the peak holds

Little’s law is the line 48 × 3 = 144: average concurrency is arrival rate times time in the system, and here you used service time, which is valid only when the queue is not growing. It is growing. Those 27 new waiters per second sit in front of prefill. Their time to first token includes the wait. Tokens per second on the four devices can look healthy the whole time, because every slot is full. The dashboard of decode speed will not page you. The blank chat boxes will.

Now the long prompt. Cache is proportional to sequence length, layers and C held fixed. A prompt of length 8S costs the cache of eight length-S chats.

16 short sequences at length S occupy 16 × S token-slots
one prompt at 8S occupies 8 × S token-slots
that single prompt is half of a full short batch

if 12 short sequences are already resident, free room is 4 × S
the long prompt needs 8 × S
it does not fit in this batch

Continuous batching does not make this fit. It only lets you try again at the next step, when some short sequence has finished and returned pages. If you force the long prompt in by shrinking the short batch, you drop the completion rate below the 21 requests/s you already could not sustain, and the long prefill occupies the device while it runs. Decode for the sequences that remained is waiting on that compute. Time to first token for the long request is its queue time plus that prefill. Time between tokens for everyone sharing the device stretches while the prefill runs.

You have three honest moves. Wait until pages free, and accept the queue. Reject the oversized prompt with a fast error and ask the caller to shorten it. Or shed load earlier, before the queue exists. Load shedding here means a bound on waiting requests and a floor of free pages below which you stop admitting. An unbounded queue is a memory leak of prompts on the CPU side, and it turns a short peak into minutes of time to first token after the peak has ended. While the peak holds, 27 extra requests per second is 1,620 requests in one minute. You do not drain that by decoding faster inside a batch that is already full. You drain it by having the slots, or by refusing work.

Quantization is a fourth move with a different trade. Fewer bits in the weights can leave more of the device for pages, so the “16 short sequences” assumption might become a larger number. The quality of the answers moves too. Re-run the task set you actually serve before you raise the batch on the strength of a demo. No general percentage belongs in this estimate.

Tradeoffs

Choice What you gain What you spend
Static batching Simple scheduling when lengths match Short requests wait until the longest member finishes
Continuous batching A finished sequence frees its slot at the next step The long sequence still holds pages; admission is a memory check
Paged KV cache Short requests no longer reserve a max-length hole Page bookkeeping, and you still exhaust the device
Quantize weights or cache More sequences or a longer context in the same memory Quality moves, visible only on the tasks you evaluate
Admit a prompt that fills the device That one caller gets an answer The short batch shrinks and other prefills wait
Shed when free pages are low The resident batch stays in a regime you sized Some callers get a fast refusal instead of a slow token

A timeout around the server has to match the SLI you mean. A timeout shorter than prefill of a legitimately long prompt fails requests that were going to succeed. A timeout so long that it ignores the queue lets a client hold a slot, or a place in line, past the point where the user has left. Set the admission decision from free pages and queue depth, and set the client deadline from the time-to-first-token budget, not from a decode average.

Pitfalls

  • Reporting one throughput number for a named model. Time to first token and tokens per second move for different reasons, and the number was never yours unless you measured it on your prompts.
  • Sizing the batch from the weights alone. Weights are fixed. The cache grows with batch, sequence, and layers, and it is what tips the device over.
  • Treating continuous batching as extra memory. It fills slots sooner. It does not shrink an 8S prompt.
  • Reserving a contiguous max length per request and then wondering why a device full of short chats accepts nothing else. That is fragmentation. Paging fixes the hole, not the sum.
  • An unbounded CPU queue in front of a full GPU. Decode looks busy and healthy while time to first token runs away. Shed, or bound the line.
  • Quantizing and raising the batch without re-running the task set. You bought room by spending quality, and you have not measured that quality.
  • Retrying a slow generation. You now have two prefills for one user, which is the opposite of shedding. Retry only if the wait still fits the budget and the first attempt is cancelled.
  • Letting one agent paste a log that does not fit beside the resident batch, then blaming the model. The prompt was an admission decision.

In the interview

Spend the first five minutes on the split. Prefill is compute over the prompt. Decode is one token at a time and bandwidth over the cache. The cache grows with batch, sequence length, and layers. GPU memory runs out before the API does. Time to first token and tokens per second are two SLIs. Then do the slot arithmetic with a peak you state as an assumption, and show a prompt that costs as much cache as several short ones.

Skip a GPU model name and any tokens-per-second claim you did not measure. Skip kernel trivia. The interviewer who wants a serving design is listening for admission control.

The question that usually follows is the long prompt, or the full batch. Say that it does not fit, that continuous batching only retries at a step boundary when pages return, and that you would rather refuse than stall every resident decode. Name the tradeoff: a fast refusal for the oversized caller, a stable batch for everyone else.

Check yourself

Prefill and decode both run on the same GPU. Why is decode described as memory-bandwidth heavy when each step emits only one token?

Each decode step attends over the whole KV cache and produces a single token. The arithmetic is small relative to the bytes of keys and values moved from memory. A faster matrix unit does not remove that movement. Prefill is the compute-heavy phase because it builds that cache from the prompt.

Layers and per-token cache bytes stay fixed. A batch of 4 sequences of length S is resident. You replace it with a batch of 8 sequences of length 2S. What happens to KV cache bytes?

Cache is proportional to batch times sequence length. The first batch is 4 × S. The second is 8 × 2S = 16S. The cache quadruples. Paging does not change this product. It only stops you from rounding each sequence up to a contiguous maximum.

Seven short requests and one very long request share a static batch. What does continuous batching change, and what does it leave alone?

In a static batch the seven short requests stay until the long one finishes. Continuous batching, the Orca idea, retires them at a step boundary and can put new work in their slots. The long request still occupies cache proportional to its length and its layers for as long as it runs, so the memory limit does not move.

Twelve short sequences fill 12 times S of token-slots, and the device holds 16 times S. A prompt of length 8S arrives. Why is the right move often a refusal rather than squeezing it in?

Free room is 4S. The prompt needs 8S, so it does not fit beside the twelve. Squeezing it in means evicting short sequences or shrinking the batch. Evicted sequences pay prefill again, and a smaller batch completes fewer requests per second. If you were already behind the arrival rate, time to first token gets worse for the whole queue. A fast refusal keeps the resident batch inside the memory you sized.

The device is full and tokens per second look steady, but chats sit blank for many seconds. Which SLI is failing, and which number is misleading you?

Time to first token is failing, and the missing piece is usually queue time in front of prefill. Tokens per second measures decode after a request has a slot. A full, healthy batch produces a calm tokens-per-second line while an unbounded queue adds wait to every new arrival. Bound the queue or shed.

Based on: Orca paper, continuous batching; PagedAttention in vLLM; Little's law.