Life of a Prompt in a Block-Paged LLM Serving Engine
Machine LearningModel answerLast updated
Walk one request through an LLM serving engine that stores attention state in fixed-size memory blocks, covering scheduling, prefill, decode, block tables, memory reclamation and latency trade-offs.
You are asked to explain how a modern LLM serving engine handles a single request from the moment it arrives until the last token is returned. Use an engine built around paged key/value (KV) memory as your reference design.
In your answer, cover:
- How a request is accepted and queued.
- What happens during the prefill phase and how it differs from decode.
- How the attention cache is divided into fixed-size blocks, and how a per-request block table maps logical token positions to physical GPU memory.
- How the scheduler forms batches at every model step (continuous batching) instead of per request.
- Who owns each cache block, when it is released, and what happens when the cache is full.
- How these choices affect throughput, time to first token, and per-token latency.
Expectations
- Talk about the architecture and its invariants, not a specific library version or internal class names.
- State your assumptions where they matter: model size, maximum context length, GPU memory, and the latency goal.
- Mention the clarifying questions you would ask first, for example: typical prompt and output lengths, what the latency target actually measures, whether prompts share prefixes, whether responses are streamed, and what should happen when memory runs out.
Hints
Hint 1
Separate the two phases: prefill processes all prompt tokens in parallel and is compute-bound, while decode produces one token per step per sequence and is memory-bandwidth-bound.
Hint 2
Think of the block table like a page table in an operating system: logical block index maps to a physical block id, so a sequence's cache need not be contiguous and waste is limited to the last partially filled block.
Hint 3
The scheduler runs once per model iteration, not once per request. Ask what it must decide each step: which waiting requests to admit, which running ones to continue, and which to preempt when free blocks run out.
Hint 4
Do not forget lifetime: blocks are reference-counted, freed on completion or cancellation, and shared prefixes can be copy-on-write.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
Take a 7B to 70B decoder-only transformer on one or more 80 GB GPUs, with a 4k to 32k context window and streamed output. The goals are high throughput under a time-to-first-token (TTFT) target of roughly a second or less and a steady inter-token latency (ITL) of tens of milliseconds. I would first confirm prompt and output length distributions, whether the SLO is on TTFT, ITL or end-to-end time, whether many requests share a system prompt, and what the overload policy is.
Why KV memory is the core problem
For each token, each layer stores a key and a value vector. A rough size is 2 × layers × kv_heads × head_dim × bytes per token. For a 7B-class model in fp16 this is about 0.5 MB per token, so a 2k-token sequence holds around 1 GB. Output length is unknown in advance. Allocating a contiguous max-length slab per request wastes memory through reservation, internal and external fragmentation, which caps batch size and therefore throughput. Paging fixes this.
Request lifecycle
-
Admission. The API layer tokenizes the prompt, validates length against the context limit, attaches sampling parameters, and places the request in a waiting queue. Backpressure or rejection happens here if the queue is too deep.
-
Scheduling. At every iteration the scheduler looks at running sequences and the waiting queue, and asks the block manager whether enough free blocks exist. A waiting request is admitted only if its prompt blocks (plus a small reserve for growth) can be allocated.
-
Prefill. The whole prompt runs through the model in one forward pass (or in chunks). It is compute-bound, with large matrix multiplications. Keys and values for every prompt token are written into the physical blocks named by the request's block table. The last position's logits give the first output token, so prefill time is essentially TTFT plus queueing.
-
Decode. Each step feeds one new token per running sequence. The step is memory-bandwidth-bound because the model weights and the entire KV history are read to produce a single token. The new token's K/V is appended to the last block; when that block fills, one new physical block is allocated and added to the table.
-
Termination. On end-of-sequence, max-length, a stop string, or client cancel, the sequence's blocks are released immediately and the result stream is closed.
Paged KV and the block table
- GPU cache memory is carved at startup into equal physical blocks, each holding for example 16 tokens of K/V for all layers.
- Every sequence has a block table: logical block
imaps to a physical block id. Blocks are allocated on demand, so waste is bounded by less than one block per sequence (internal fragmentation only) and there is no external fragmentation. - The attention kernel (PagedAttention) receives the block table and gathers K/V through the indirection, so physical blocks can be scattered anywhere.
- Sharing. Blocks carry a reference count. Parallel sampling or beam search shares the prompt blocks; a hash of block contents enables prefix caching across requests. Writing into a shared block triggers copy-on-write of that block only.
Continuous (iteration-level) batching
Static batching waits for the slowest sequence in a batch, leaving the GPU idle as short ones finish. With continuous batching the batch is rebuilt every iteration: finished sequences leave, new ones join, and the batch mixes prefill and decode tokens. Because attention works through block tables, sequences of different lengths need no padding to a common length. Throughput typically improves by multiples over static batching at the same latency target.
Prefill is bursty and long prompts can stall decoders, hurting ITL. Chunked prefill splits prompts into pieces bounded by a per-step token budget so decode steps stay predictable. Some deployments go further and disaggregate prefill and decode onto separate GPU pools.
Running out of cache
When no free block exists for a growing sequence, the engine must pick a policy:
- Preempt by recompute: free a low-priority sequence's blocks (usually the most recently admitted) and re-prefill it later. It is cheap to implement and good for short contexts.
- Preempt by swap: copy blocks to CPU memory over PCIe and restore later. Better for long contexts but bandwidth-limited.
- Admission control: keep a watermark of free blocks so preemption stays rare.
Latency versus throughput
- A larger batch raises tokens per second because weight reads are amortized, but each step takes longer, so ITL rises.
- Admitting more prefill per step lowers TTFT but delays ongoing decodes.
- A bigger block size reduces table overhead and improves kernel efficiency but increases tail waste; 16 is a common compromise.
- Queueing delay dominates TTFT near saturation, so autoscale on queue depth and cache utilization, not just GPU utilization.
Useful metrics are TTFT, ITL, tokens per second, cache block utilization, preemption rate, prefix hit rate and queue length.
Common mistakes
- Describing batching per request rather than per iteration.
- Saying prefill and decode have the same bottleneck.
- Forgetting that the block table adds an indirection cost and that waste is only in the last block.
- Ignoring cancellation and failure paths, which leak blocks if not freed.
- Claiming paging reduces the amount of KV data. It improves utilization of memory, not the number of bytes needed per token.
- Giving no policy for cache exhaustion.