7 Inference and Serving 4 / 8
  1. In this chapter
  2. Your first inference service
  3. Decoding and Sampling
  4. KV Cache and Inference Performance
  5. Prefix Caching and PD Disaggregation
  6. Model Quantization
  7. LLM Inference Serving
  8. Continuous Batching and PagedAttention
  9. Speculative Decoding
All chapters →

Chapter 7 · Inference and Serving 7.4

Prefix Caching and PD Disaggregation: Pay for Repeated Compute Once

Prefix caching reuses the KV cache of system prompts, shared documents, and chat history across requests (RadixAttention, CacheBlend, LMCache). PD disaggregation places compute-bound prefill and bandwidth-bound decoding on different hardware; DistServe, Splitwise, and Mooncake show when it pays off.

Intermediate 12 min read Updated Companion code ↓

After this page you will be able to

  • Say which requests can share KV cache across requests, and what determines the hit rate.
  • Explain why prefix caching removes most prefill compute, and estimate the savings from a model's parameter count.
  • Compare what RadixAttention, CacheBlend, Prompt Cache, and LMCache each solve.
  • Explain why prefill and decode have different resource profiles, and the gains and costs of PD disaggregation.
  • State when disaggregation does not pay off, and describe compromises like chunked prefill.
On this page
  1. The problem: requests repeat each other’s compute
  2. How prefix caches are organized
  3. RadixAttention: a radix tree of reusable cache
  4. CacheBlend: merge instead of exact-match
  5. Prompt Cache and CacheGen: offline and on-the-wire
  6. LMCache and Mooncake: cache as cluster infrastructure
  7. Hit rate is schedulable: Preble and AdaServe
  8. PD disaggregation: two stages, two resource profiles
  9. When it does not pay off
  10. Experiment: cache reuse versus queueing
  11. Summary and exercises
  12. Quick quiz
  13. Exercises
  14. Further reading
  15. FAQ

If you understand how the KV cache avoids redundant compute within one request, this page covers its two natural extensions: reusing caches across requests (prefix caching), and reorganizing the whole inference cluster around the cache (PD disaggregation). These are the two most important engineering threads in serving systems since 2024.

The problem: requests repeat each other’s compute

Real traffic shares long prefixes far more often than one might expect:

  • Every request of an application carries the same system prompt (tens to thousands of tokens).
  • In multi-turn chat, each turn resends the entire history to the server.
  • Support, coding, and RAG workloads repeatedly reference the same documents or few-shot examples.

Without prefix caching, every request recomputes the shared prefix from scratch. Estimating with an 8B-parameter model (32 layers, 8 KV heads): 32 requests that each carry a 1000-token shared system prompt plus a 200-token unique question need about 616.7 TFLOPs of prefill without caching; computing the 1000-token prefix only once brings it to about 118.8 TFLOPs — an 80.7% saving. The shared prefix’s KV cache is only about 125 MiB (FP16): a small memory cost for a large compute saving.

The same arithmetic, runnable with any model configuration:

N = 8.03e9                      # parameters (~8B)
shared, per_req, B = 1000, 200, 32   # shared prefix / unique part / requests
fpt = 2 * N                     # forward FLOPs per token ≈ 2N
before = B * (shared + per_req) * fpt
after  = (shared + B * per_req) * fpt
print(f"saving {(1 - after/before)*100:.1f}%")   # 80.7%

The widget below turns this arithmetic into something you can compute yourself: drag the shared prefix, the unique per-request part and the request count to watch the saving approach its ceiling S/(S+U), and see how much memory the cached prefix costs.

The estimate assumes a hit skips the prefix prefill entirely. What to store, for how long, and who hits it — that is what prefix-caching systems decide.

Prefix caching: one prefix, one prefill Structure diagram: a prefix of 1,000 tokens (system prompt plus fixed documents) has its KV cache shared across requests and computed once; requests A, B and C each carry a 200-token unique suffix, the prefix part is a cache hit that skips prefill entirely, and only the suffix is still computed. Without caching 32 requests cost 616.7 TFLOPs; with reuse 118.8 TFLOPs, saving 80.7%. Prefix caching: one prefix, one prefill KV cache shared across requests Shared prefix: system prompt + fixed documents (1,000 tok) — KV computed once ~125 MiB of memory Reused: this prefill is skipped Question A (200 tok) Request A Reused: this prefill is skipped Question B (200 tok) Request B Reused: this prefill is skipped Question C (200 tok) Request C No cache: 32 x 1,200 tok → 616.7 TFLOPs; computed once: 1,000 + 32 x 200 → 118.8 TFLOPs (80.7% saved)
32 requests sharing a 1,000-token prefix with 200 unique tokens each (the numbers of the page's example). The dashed green box is the cache hit, skipped entirely; the amber box is the suffix each request still computes.

How prefix caches are organized

RadixAttention: a radix tree of reusable cache

vLLM’s automatic prefix caching matches cached blocks by hash and only hits on exactly aligned blocks. SGLang’s RadixAttention goes further: it organizes the prefixes of all requests into a radix tree whose edges are token sequences and whose nodes hold the corresponding KV cache. A new request walks the tree to match its longest common prefix, reuses the hit portion, and computes only the diverging remainder; when the request finishes, its prefix stays in the tree for later matches, with LRU-style eviction for cold nodes. For chat and shared-system-prompt traffic with messy prefix/substring relationships, a tree hits far more than a flat block chain.

CacheBlend: merge instead of exact-match

In many RAG workloads the repeated “prefix” is system prompt + documents + question, and the documents get reordered or swapped, so a whole-prefix hash never matches. CacheBlend observes that KV cache is mostly sensitive to position in the attention output: concatenating pieces of previously cached KV directly introduces a small attention error, which it corrects by recomputing a few layers and tokens after concatenation — reusing non-exact prefixes at low cost.

Prompt Cache and CacheGen: offline and on-the-wire

Two other directions ask where the cache comes from and how it moves:

  • Prompt Cache (2023) precomputes the KV of long fixed prompts (e.g., few-shot examples) offline and distributes them; users upload only the changing tail and the provider skips the fixed section entirely.
  • CacheGen treats KV cache as data that must be compressed for transport, using a custom codec to shrink it for bandwidth-limited links such as edge-to-datacenter. Its deeper contribution is the framing: KV cache is a portable asset.

LMCache and Mooncake: cache as cluster infrastructure

Once prefill and decode run on different nodes, the cache should not be locked in one GPU’s memory. LMCache abstracts KV cache as an independent store shared across processes and nodes (tiered across GPU, CPU, and disk), readable and writable by engines like vLLM and SGLang. Mooncake (Moonshot AI’s production architecture) goes furthest: a KVCache-centric disaggregated design that co-schedules “where the cache lives, where prefill runs, and where decode runs” as one problem.

Hit rate is schedulable: Preble and AdaServe

Prefix-caching gain depends on hit rate, and hit rate is not purely a property of the workload. Preble routes each request to the node most likely to hold its prefix; AdaServe jointly optimizes request placement and parallelism under SLO constraints, so cache hits and service levels are served together. The general lesson: a caching system is half storage, half scheduling.

PD disaggregation: two stages, two resource profiles

Prefill and decode have almost complementary resource profiles:

StageCompute profileLimited byLatency metric
PrefillProcesses the whole input at once: large matrices, high parallelismCompute (compute-bound)TTFT (time to first token)
DecodeGenerates token by token: small matrices, many stepsMemory bandwidth (bandwidth-bound)TPOT (time per output token)

Colocating them on the same GPUs causes mutual harm: a long prefill stalls every decode on the card (TPOT spikes), and a decode-friendly low-parallelism configuration starves prefill’s appetite for compute. PD disaggregation deploys the two stages on separate instance pools: a request is prefilled on a prefill instance, its KV cache is shipped over the network to a decode instance, and decoding continues there — each side scaled and tuned independently.

Representative systems:

  • DistServe (2024): the systematic case for disaggregation. Using goodput — request throughput under both TTFT and TPOT constraints — it shows that colocation interferes under load, and quantifies the costs (KV transfer, memory redundancy) that separation introduces.
  • Splitwise (2023): the cost view. Prefill instances can use compute-dense hardware while decode instances use memory-bandwidth-rich hardware; disaggregation itself is a money-saving device.
  • Mooncake (2024): a production-grade, KVCache-centric disaggregated architecture for high-concurrency long-context serving.

When it does not pay off

Disaggregation is not free: cross-node KV transfer consumes network bandwidth, scheduling must maintain two pools, and prefix-cache locality can degrade with separation (which is why Mooncake makes the cache layer a first-class citizen). Under light load, uniform request lengths, or tight network budgets, colocation plus chunked prefill (Sarathi-Serve: slice long prefills into small chunks interleaved with decode steps) may be simpler and cheaper. Recent work (e.g., When Does Disaggregation Pay?, 2026) keeps refining the break-even boundary — whether to disaggregate should follow your own workload profile, not architectural fashion.

Experiment: cache reuse versus queueing

Preble treats prefix sharing and balancing compute load as parts of one scheduling problem. A small executable model shows how the goals can conflict. Two workers each process one request at a time. Only the first is warm, and all requests share a prefix. A worker can reuse the prefix after processing a cold request. Fixed hit and miss costs represent service time to first token. The model omits decoding, cross-worker KV transfers, and eviction.

Compare always using the warm worker with choosing the earliest estimated prefill finish. The estimate adds the queue wait and the request’s service time. A queued request can reuse a prefix that an earlier request will warm. The timings and arrivals are synthetic. The code ran on an Apple M2 Max with Python 3.14.3.

from statistics import median

requests = [0, 0, 0, 1, 2, 20]
hit_ms, miss_ms = 4, 11

def replay(cache_only):
    free_at = [0, 0]
    cached = [True, False]
    latency = []
    hits = 0
    for arrive in requests:
        finish = [
            max(arrive, available) + (hit_ms if have_prefix else miss_ms)
            for available, have_prefix in zip(free_at, cached, strict=True)
        ]
        first_to_finish = min(range(len(finish)), key=finish.__getitem__)
        worker = 0 if cache_only else first_to_finish
        hits += cached[worker]
        cached[worker] = True
        free_at[worker] = finish[worker]
        latency.append(finish[worker] - arrive)
    return hits, median(latency), max(latency)

affinity, earliest = replay(True), replay(False)
assert earliest[0] < affinity[0] and earliest[2] < affinity[2]
for name, (hits, p50, worst) in zip(
    ('cache only', 'estimated latency'), (affinity, earliest), strict=True
):
    print(f"{name}: hits={hits}, p50={p50:g} ms, max={worst} ms")
cache only: hits=6, p50=10 ms, max=18 ms
estimated latency: hits=5, p50=9.5 ms, max=13 ms

The widget below draws this replay as a timeline: switch between the two policies and watch which worker serves each request, hit or miss — hits and the slowest latency sit on the left.

In this burst, one cold prefill spreads later work across the workers. The policy registers fewer hits and shortens the worst request. With sufficiently spaced arrivals, the warm worker can finish each request before the next one arrives, and both policies reuse its cache. Compare first-token latency including queue time under bursty and sparse loads, alongside cache hits. A deployment needs estimates of uncached tokens, queue load, memory pressure, and transfer cost. Report cached tokens, TTFT, and goodput under different offered loads.

Summary and exercises

  • Prefix caching turns inter-request prefill redundancy into compute-once: the long shared prefix in the worked example saves about 80.7% of estimated prefill compute, at the cost of cache memory and scheduling complexity.
  • The design space runs from block hashing (vLLM) to radix trees (SGLang RadixAttention) to cluster-wide cache layers (LMCache, Mooncake) — an evolution from single-engine trick to cluster infrastructure.
  • PD disaggregation follows from the complementary resource profiles of prefill and decode; judge it with goodput and cost together, and disaggregate only when your workload says so.

Quick quiz

1. A workload has almost no overlap between request prefixes. What happens if you enable prefix caching for it?

  • The hit rate is near zero, the cache occupies memory for nothing, and prefill compute is barely saved
  • Prefill compute is halved
  • Decode becomes bandwidth-bound

All prefix-caching gain comes from the hit rate. With no shared prefix, stored blocks are never reused; you pay eviction and management overhead only.

2. 32 requests share a 1000-token prefix and each adds 200 unique tokens (8B model). Computing the prefix once saves roughly how much prefill compute?

  • About 20%
  • About 80%
  • About 50%

The arithmetic on this page: 616.7 TFLOPs down to 118.8 TFLOPs, an 80.7% saving. The shared part changes from “times number of requests” to “times 1”.

3. What is RadixAttention’s main advantage over block-hash prefix caching?

  • It compresses the KV cache
  • A radix tree manages partially overlapping prefixes and matches the longest common prefix, hitting more often under complex sharing
  • It needs no eviction policy

A radix tree natively expresses “A is a prefix of B, B is a prefix of C”; flat block chains only hit on strictly aligned whole blocks.

4. What is the fundamental motivation for PD disaggregation?

  • It reduces the total bytes of KV cache
  • Prefill is compute-bound while decode is bandwidth-bound; colocating them interferes, and separation lets each be provisioned for its own profile
  • It makes speculative decoding easier

Separation saves not bytes but resource mismatch: the two SLOs (TTFT and TPOT) are served by two instance types.

5. Which approach relieves long-prefill blocking of decode without disaggregating?

  • Slice long prefills into small chunks scheduled between decode steps (chunked prefill / Sarathi-Serve)
  • Raise the sampling temperature
  • Move the KV cache to CPU

Sarathi-Serve’s chunked prefill removes stalls by scheduling, a compromise under colocation.

Exercises

  1. Estimate your own application with the formula on this page: how long is the system prompt, how long is the conversation history per turn, how many turns per day? How much prefill compute would prefix caching save?
  2. Make a table comparing vLLM automatic prefix caching, SGLang RadixAttention, CacheBlend, and LMCache on three columns: what can be reused, where it is stored, and who can use it.

Suggested answer framework for exercise 1:

Click to expand

With shared prefix length S, unique length U, request count B, and model parameters N, the saving is

1−S+BUB(S+U)=(B−1)SB(S+U)1-\frac{S+BU}{B(S+U)}=\frac{(B-1)S}{B(S+U)}

The larger B and the larger S is relative to U, the closer the saving is to 100%. When S ≪ U (short system prompt, long unique input) the saving approaches zero — look for other optimizations first.

Further reading

FAQ

Are prefix caching and the KV cache the same thing?
No. The KV cache avoids recomputation of past tokens within a single request; prefix caching stores the KV of a prefix in a shared, cross-request store so that later requests carrying the same prefix skip its prefill entirely. One removes intra-request redundancy, the other removes inter-request redundancy.
Which workloads get the highest prefix-cache hit rates?
Applications with a long, fixed system prompt, multi-turn chat (where each turn resends the whole history), RAG traffic that repeatedly references the same documents, and classification tasks with fixed few-shot examples. Traffic with near-zero shared prefix gets almost no benefit — the cache only occupies memory.
Why deploy prefill and decode separately in PD disaggregation?
Prefill processes a long input at once — compute-bound and highly parallel. Decode generates tokens one by one — bandwidth-bound and latency-sensitive. Colocated, a long prefill stalls every decode running on the same GPU (TPOT spikes), and the hardware profile that suits one stage starves the other. Separated, each side is sized, parallelized, and scaled for its own profile, with KV cache shipped over a fast link.
Is PD disaggregation free?
No. It adds cross-node KV transfer, scheduling complexity, and memory redundancy, and it can hurt cache locality. DistServe and Splitwise use goodput — throughput under both TTFT and TPOT constraints — to show when disaggregation wins; Mooncake builds a cache-centric production architecture around it. Under light or uniform workloads, colocation plus chunked prefill (Sarathi-Serve) is often simpler and cheaper.