My account

Batching and caching for LLM serving

One read of the weights can serve many requests, so serving engines run many requests in each step. Continuous batching lets requests join and leave at every step. Paged KV memory wastes little space, prefix caching reuses the work of a shared prompt start, chunked prefill stops long prompts from freezing everyone, and speculative decoding speeds up quiet times. Each trick has a cost, so measure it on real traffic.

Not reviewedWritten with AI helpReading time: 14 minShop assistant examplePython

Author: bezzad

Contents

The problem: a queue in front of an idle GPU

Our first shop assistant server answered one request at a time. At peak, 50 people were chatting. The queue grew to minutes, while the GPU usage graph showed the GPU was busy only part of the time, and its math units were almost idle.

The lesson on how inference works showed why: in each decode step, the GPU reads all 16 GB of weights to write one token per request. Reading them for one request or for 30 costs almost the same. So the first job of a serving engine is to put many requests in each step.

Static batching and its waste

The simple way: collect a group of requests, run them together until all are done, then take the next group.

Static batching: the batch waits for its longest requestSlot 1ADSlot 2BESlot 3CFD, E and F wait until B is done. Empty boxes are wasted GPU work.Continuous batching: requests join and leave at every stepSlot 1ADGSlot 2BHSlot 3CEFA new request starts as soon as a slot is free. No waiting, no empty slots.
Static batching waits for the longest answer. Continuous batching fills a free slot at the next step.
  1. Answers have different lengths. One answer is 20 tokens, another is 500.
  2. The batch waits for the longest one. Finished slots stay empty. That is wasted GPU work.
  3. New requests wait until the whole batch is done, so time to first token gets long.

Continuous batching

Modern engines decide at every step which requests run. This is called continuous batching (some engines call it in-flight batching).

  1. When a request finishes, its slot is free at the next step.
  2. A new request joins right away. Its prefill runs, then it decodes with the others.
  3. The GPU stays full as long as there is work, and nobody waits for an unrelated long answer.

Engines such as vLLM, SGLang and TensorRT-LLM all work this way. You rarely build it yourself. But you must understand it, because its settings decide your latency and cost.

Paged KV memory

Each request’s KV cache grows by one token per step, and we do not know how long an answer will be. Early servers reserved one big block of memory per request for the maximum length. Most of it stayed empty.

PagedAttention, introduced with vLLM, borrows an idea from operating systems:

  1. The KV cache is split into small pages, each holding the keys and values of a few tokens.
  2. A request gets a new page only when it needs one. Little memory is wasted.
  3. Pages do not need to be next to each other. The engine keeps a table for each request.
  4. Pages can be shared between requests that start with the same tokens. That makes the next trick cheap.

When memory is full anyway, the engine must pause (preempt) some requests and later recompute or reload their cache. Users see this as a sudden wait. Watch the KV cache usage and the number of preemptions.

Prefix caching

Many prompts start the same way. Every shop assistant prompt starts with the same 3,000 tokens of shop rules, and every turn of a chat repeats the history of the turns before.

Prefix caching: the same start is computed onceShop rules, 3,000 tokensKV pages made once, sharedChat 1: its own pagesChat 2: its own pagesChat 3: its own pagesEach page holds the KV cache of a few tokens. Shared pages are reused, not copied.
Shared pages for the same prompt start are computed once. Each chat adds only its own pages.
  1. The engine keeps the KV pages of earlier prompts for a while.
  2. A new prompt that starts with exactly the same tokens reuses them, and runs prefill only for the new part.
  3. Time to first token drops, and the GPU does less work.
  4. It must be an exact prefix. One different token early in the prompt, like the current time, breaks everything after it.

So write prompts in this order: the parts the same for everyone first, then the parts the same for this chat, then the new question last.

def build_prompt(user, history, question):
    return (
        SHOP_RULES                          # same for everyone
        + f"Customer name: {user.name}\n"   # same for this chat
        + format_history(history)           # old turns do not change
        + f"Customer: {question}\nAssistant:"
    )

With several replicas, the cache lives on each GPU. A router that sends the same chat to the same replica keeps the hit rate high. (See the lesson on running serving in production.)

Chunked prefill

A 90,000-token prompt needs a huge prefill. If it runs in one step, every other request in the batch waits, and their streams freeze for seconds.

  1. Chunked prefill splits long prefills into pieces.
  2. Each step has a token budget, for example a few thousand tokens. The step mixes decode tokens of running chats with one chunk of the long prompt.
  3. Running chats keep streaming, and the long prompt still finishes, just spread over more steps.
  4. The budget is a trade-off. A bigger budget finishes long prompts sooner but makes each step longer.

Speculative decoding

When the GPU is not busy, each decode step is mostly waiting for memory. Speculative decoding uses that spare math:

  1. A cheap drafter guesses the next few tokens. For example a small model, extra prediction heads, or matching text from the prompt.
  2. The main model checks all guesses in one step. It keeps the guesses that match what it would have written, plus one token of its own.
  3. The output follows the same distribution as the main model alone. It is a speed trick, not a quality trade.
  4. It helps at small batches and when guesses are often right. At busy times the GPU is already doing a lot of math, and wrong guesses become wasted work.

Measure the acceptance rate on your real traffic, for each language and task, and check the gain at both quiet and busy hours.

The settings that decide your trade-off

Setting (names differ by engine) Higher means Lower means
Max running requests in a batch More throughput, slower tokens for each user Faster tokens, more queueing
Max tokens per step (prefill budget) Long prompts finish sooner, steps are longer Smoother streaming, slower first token for long prompts
Max context length Supports long chats, fewer chats fit in memory More chats fit, long chats must be cut or summarized
Number of speculative tokens More gain when guesses are good Less waste when guesses are bad or the GPU is busy

There is no best value. Pick targets for time to first token and time per token, then load test to find the settings that meet them with the most throughput.

Common mistakes

Mistake Result Right way
One request at a time Long queue, idle GPU. A serving engine with continuous batching.
Changing text at the start of the prompt Prefix cache hit rate near zero. Stable parts first, new parts last.
Unlimited prompt length, no chunked prefill Streams freeze when a long prompt arrives. Chunked prefill, limits, or separate replicas for long prompts.
Turning on speculative decoding everywhere Lower throughput at busy hours. Measure at real load, use it where it helps.
Maximizing throughput only Every user gets slow tokens. Tune to latency targets, then maximize throughput.

Summary in six lines

  1. One read of the weights can serve many requests, so batch them.
  2. Continuous batching adds and removes requests at every step.
  3. Paged KV memory wastes little space and lets requests share pages.
  4. Prefix caching reuses a shared prompt start: keep stable text first.
  5. Chunked prefill keeps streams smooth when long prompts arrive.
  6. Speculative decoding helps at quiet times; every setting is a trade-off to measure.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.