Count prefix cache hits with a token trie and block granularity
Requests often share a system prompt or a chat history. A prefix cache keeps the KV cache of earlier requests so a new request can skip recomputing its shared prefix. Caches store KV in fixed-size blocks, so only whole blocks can be reused. This is simulated with plain Python here.
Write prefix_cache_hits(requests, block_size). requests is a list of token-id lists, processed in order. For each request:
1. Find the longest prefix it shares with ANY earlier request (use a trie of all earlier requests).
2. Its hit count is that length rounded down to a multiple of block_size.
3. Insert the full request into the trie.
Return the list of hit counts, one per request. The first request always gets 0.
def prefix_cache_hits(requests, block_size)Example
block_size = 4, requests = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 9], [1, 2, 9]] gives [0, 4, 0]: the second shares 6 tokens (one full block), the third shares 2 (no full block).
Understand the idea
Many requests start the same way, for example the same system prompt. A prefix cache keeps the attention keys and values from earlier requests so a new request can skip recomputing the shared start. The cache stores them in fixed-size blocks, so only complete blocks count as reusable. A trie, a tree where each path is a token sequence, lets you compare a new request against all earlier ones in a single walk. Worked example: block_size 2, requests [5, 6, 7, 8], [5, 6, 7, 1], [9, 9], [5, 6, 7, 8, 4]. Request 1: nothing earlier, 0. Request 2: shares 3 tokens, rounded down to 2. Request 3: shares nothing, 0. Request 4: shares all 4 tokens with request 1 (not just with the previous request), so 4. Answer [0, 2, 0, 4]. Rule: walk the trie as far as the request's tokens match, hits = matched length // block_size * block_size, then insert the full request. Comparing only with the previous request misses hits. Prefix caching is a key feature of serving engines like vLLM and SGLang.