Batching, decoding and serving caches
hard 7 minServing combines admission control, prefill, autoregressive decoding and memory management.
Video lesson · Chapter 1 of 4
A short request overtakes a long one
Theory
Read or listen first. About 3 min.
What it is
Serving combines admission control, prefill, autoregressive decoding and memory management. Continuous batching lets active requests share compute as their lengths diverge. Prefix reuse and speculative decoding can save different kinds of work under different conditions.
Why it exists
Record the distribution of input lengths, output lengths and arrival bursts. A benchmark of a single short prompt may hide queueing, expensive prefills and memory contention that dominate a real service.
A second request arrives while the first is decoding
Inside this chapter
Chapter sources- Speculative Decoding
- Speculative decoding has a smaller draft model propose several tokens and a target model verify them. With the proper acceptance and correction rule, sampling preserves the target distribution. Speed depends on acceptance rate, verification cost and workload. When drafts diverge, extra model calls can outweigh saved serial steps.
Decoding is serial: the large model must produce token n before token n plus 1. A cheap draft model guesses several tokens ahead, and the target model checks all of them in a single forward pass. Each draft token is accepted with probability min(1, p over q), comparing target and draft probabilities; at the first rejection a replacement is sampled from the leftover distribution, which keeps the output distributed exactly as the target alone would produce. The speed-up depends on how often the draft agrees with the target.
Example. A draft model proposes four tokens and the verifier accepts the first two. The remaining draft suffix cannot simply be emitted unchanged.
Another example. A code-completion service sees high acceptance on boilerplate and low acceptance on unusual logic. Logging the mean accepted length per request type shows where speculation pays and where it only adds draft calls.
Draft four, keep two, correct one
One target pass yielded three tokens here. If every draft token is accepted, the target also adds one bonus token. - Ollama (Local Runner)
- Ollama packages local model serving behind a convenient interface. Check the exact model tag, quantization and available memory. Local data handling can simplify some workflows, but the machine still needs authorization, resource limits and a policy for logs if multiple people use the service.
A local runner downloads a packaged model, picks a quantised variant and serves it over a local API, which makes experiments quick. The tag decides which weights and quantisation you get, so an unpinned name can change underneath you. Concurrency changes the picture: two long prompts need two KV caches, and a shared machine needs the same access control and log policy as any other service.
Example. Load a pinned model tag locally. Run two concurrent long prompts and record peak memory as well as the single-request latency.
Another example. A team shares one workstation running a local model for code review. Pinning the tag, capping concurrent requests at two and turning off prompt logging keeps results reproducible and keeps source code out of logs.
Shell# pin an exact tag, not just the model nameollama pull <model>:<pinned-tag># run a prompt, then check what is loaded and its memoryollama run <model>:<pinned-tag> "Summarise this note"ollama psPlaceholders shown. Repeat the memory check with two long prompts running at once. - Serving with vLLM
- vLLM schedules many requests while managing KV-cache blocks efficiently. Throughput depends on how requests share compute and memory, not just raw model speed. Benchmark mixed prompt lengths and cancellation behavior, and report tail latency together with successful tokens per second.
Reserving one contiguous cache region per request for the maximum length wastes most of it, because most requests stop early. Paged allocation hands out small fixed-size blocks on demand and keeps a per-sequence table, the way an operating system pages memory, which lets the scheduler fit more concurrent sequences. Throughput then depends on the traffic mix: long prompts take big prefill chunks and many blocks. Report time to first token, inter-token latency at the tail, and successful tokens per second together.
Example. Measure two workloads with equal request counts but very different prompt lengths. Compare queue delay, cache utilization and time to first token.
Paged KV cache: logical blocks map to any free physical block
Cache grows block by block as tokens arrive, so little memory is reserved and wasted for sequences that end early. - TGI (Text Generation Inference)
- Text Generation Inference is a serving stack with its own model compatibility, batching and streaming behavior. Evaluate the documented lifecycle and supported hardware for a new deployment. An integration test should check context limits, errors and finish reasons, in addition to measuring throughput. Hugging Face currently lists TGI in maintenance mode.
Any serving stack has its own model coverage, batching policy and streaming format, so evaluate it against your lifecycle, not only its throughput. The paths that break in production are the unhappy ones: a client that disconnects mid-stream, a prompt over the context limit, a finish reason of
lengththat the caller mistakes for a complete answer. Because the project is in maintenance mode, weigh the long-term support story for new deployments.Example. Test a TGI deployment with a cancelled stream. Confirm the caller sees cancellation and that the serving slot becomes available to another request.
A streamed request's lifecycle
An integration test should drive the Cancelled path and confirm the slot is freed for the next request. - Continuous Batching
- Continuous batching revisits the active batch as generation progresses. Finished sequences free capacity for waiting requests before the whole original batch completes. Long prefill operations can still affect inter-token latency. Measure both queue time and decode cadence under mixed traffic.
Static batching fixes the batch at the start, so short requests finish and leave their slots idle until the longest one ends. Continuous batching re-evaluates membership after every decode step, retiring finished sequences and admitting waiting ones. The catch is prefill: admitting a request with a long prompt makes that step heavier, which delays the next token for everyone already streaming. Many servers split long prefills into chunks to smooth this out.
Example. A three-step request and a one-step request start together. After step one, a new request can occupy the freed slot while the longer one continues.
A (3 steps) and B (1 step) start together, C waits
Decode step Static batching Continuous batching 1 A, B A, B 2 A, idle slot A, C (admitted into B's slot) 3 A, idle slot A, C 4 C starts C continues or finishes The scheduler re-forms the batch every step instead of waiting for the slowest member. - KV-Cache Explained
- During decoding, a KV cache stores key and value tensors for earlier positions so each new token need not recompute them. Memory grows with active sequence length, layer count and KV heads. Eviction or preemption policies matter when many users send long prompts simultaneously.
Keys and values for past positions do not change once computed, because a causal model never lets earlier tokens see later ones. Caching them turns each decode step into a small amount of new work plus a read of the cache. The price is memory that grows with every token of every active sequence, multiplied by layers and KV heads. When the cache fills, the server must queue, preempt or evict, and those policies decide tail latency under load.
Example. For an active sequence twice as long, cached KV payload approximately doubles at the same model configuration. Other memory costs need not double.
Another example. A support chat that keeps the full 6,000-token history per session holds roughly three times the cache of one that summarises down to 2,000 tokens, at the same model configuration.
Prefill once, then append one row per token - 1Prefill the promptcompute K and V for all prompt tokens
- 2New token arrivescompute only its q, k, v
- 3Append k, v to cacheone more position per layer
- 4Attend over the cacheq reads every cached position
- 5Sample next tokenthen repeat
Repeat: back to Prefill the promptWithout the cache, every step would recompute keys and values for the whole prefix.
- Prompt Caching
- Prefix caching reuses computation for an identical eligible prefix. Put stable instructions before request-specific fields when the provider supports it. A changed token early in the prefix can reduce reuse. Keep cache identity isolated across incompatible model versions, tenants and sensitive contexts.
Prefix caching stores the computed attention state for a run of tokens and reuses it when a later request begins with exactly the same tokens. Order the prompt so stable parts come first: system instructions, tool definitions, shared documents, and only then the user's message. A timestamp or user ID near the top defeats the cache. Cache keys must also respect boundaries, so entries never cross model versions, tenants or sensitive contexts.
Example. Two requests share 900 leading tokens and differ afterward. Prefix reuse may save work on the compatible prefix while their distinct suffixes still run.
Another example. A contract assistant puts a 3,000-token clause library before each user question. Moving the user's name from the first line to the end lets every request reuse the library prefix.
Shared 900-token prefix, different suffixes
A single changed token early in the prefix breaks the match from that point onward.
How it works
Step through the idea, or press Play.
Two sequences. A needs 3 steps · B needs 1
Understand it
Worked example
A second request arrives while the first is decoding
- 1
A needs 3 steps · B needs 1
The scheduler can admit and retire requests at different times. Prefill builds a prefix cache while decode extends each active sequence.
- 2
Step 1 processes A and B
B completes after one step. Continuous batching can reuse the freed capacity for a waiting request rather than waiting for A.
- 3
Retain A · release B
Paged allocation reduces some fragmentation. A future request benefits from prefix caching only when its prefix is eligible and compatible.
Follow the handoffs
- 1Retire finished sequencesB completes after step 1
- 2Release their KV blocksB's blocks return to the pool
- 3Admit waiting requestsif blocks and slots allow
- 4Prefill new arrivalsreuse an eligible prefix
- 5Decode one token eachA and the newcomer advance
Admission depends on free cache blocks as much as on batch slots.
Bigger batches help
- Total tokens per second
- GPU utilisation under steady traffic
- Cost per generated token
Bigger batches can hurt
- Inter-token delay for each stream
- Time to first token when prefills pile up
- Tail latency once the cache fills
Summary
The whole topic in one minute.
High throughput can coexist with long waits or slower individual decode steps. Measure latency separately from aggregate capacity.
Record the distribution of input lengths, output lengths and arrival bursts. A benchmark of a single short prompt may hide queueing, expensive prefills and memory contention that dominate a real service.