Chapter 08

Prefix caching

Same beginning, one copy.

two prompts · page = 128 tokens herereq Asystem prompt · 512 tokensqA · 140req Bsystem prompt · 512 tokensqB · 90= 4 + 2 pages= 4 + 1 pagesSSSSSSSSS = the same 512 tokens'k and v, stored twiceA: 3, 9, 16, 22 | 31, 37B: 46, 52, 59, 65 | 73

Two requests arrive with the same first 512 tokens: the same system prompt. Same tokens at the same positions give exactly the same k and v. Paged as before, each gets its own copy: the same numbers written twice.

← KV memory
01 / 08
The prefix arithmetic, once

Position ii‘s key and value are functions of tokens 1..i1..i, so two requests can share cache exactly for their longest common prefix mm and nothing past it. A shared prefix of ss tokens across rr requests costs ss tokens of cache instead of rsr \cdot s, and a newcomer prefills PmP - m tokens:

TTFTmax ⁣(tmem,  2(Pm)ttok)\text{TTFT} \approx \max\!\left(t_{\text{mem}},\; 2(P - m)\,t_{\text{tok}}\right)

In a chat of TT turns with question qtq_t and answer ata_t, prefill without caching sums to t(qt+u<t(qu+au))\sum_t (q_t + \sum_{u<t}(q_u + a_u)) and with it to tqt\sum_t q_t. SGLang’s RadixCache is the tree, reference counts pin the pages of running requests, eviction is least-recently-used over unreferenced nodes, and schedule_policy=lpm orders the waiting list by matched length.