Guide

Prefix caching

Shared prefixes

The start of a prompt is its prefix. Many requests share one:

  • A support bot puts the same 2,000-token system prompt (its instructions) before every question.
  • Many users ask about the same long document.
  • In a chat, each new turn resends all the earlier turns.

Without help, the engine runs prefill on the same prefix again and again.

Reusing the KV cache

Prefix caching keeps the KV cache of a prefix after its request ends. When a new request starts with the same tokens, the engine reuses those keys and values and only prefills the new part. That saves GPU work and cuts time to first token (TTFT). The answer is the same as without the cache. A request that finds its prefix is a cache hit; one that doesn't is a miss.

Exact match from the start

Each token's keys and values depend on every token before it, because attention looks back. So reuse needs the exact same tokens from the very first one. Change one word at token 10, and everything after it must be prefilled again. Put the parts that never change first, and the parts that change, like the date, last.

The radix tree

A radix tree (prefix tree) stores cached prompts so ones that start the same share a branch. For a new request, the engine walks down the tree along its tokens until they stop matching. That point is the longest cached prefix. SGLang calls this RadixAttention. Other engines find the match in other ways, but the idea is the same.

Eviction and churn

Cached prefixes use KV memory that running requests need. When memory runs short, the engine evicts unused prefixes, often the least recently used (LRU) first. If many different prefixes come and go, each is evicted before anyone reuses it. That is churn, and the hit rate stays low.

Remember

  • Many prompts start the same way.
  • Reusing a prefix's KV cache skips its prefill and cuts TTFT.
  • Reuse needs the same tokens from the start; put stable parts first.
  • A radix tree finds the longest cached prefix fast.
  • Limited memory means eviction; heavy churn means few hits.