Route requests to replicas by shared prompt prefix
Why it matters Prefix-aware routing in front of a fleet of LLM servers raises KV cache hit rates for shared system prompts and multi-turn chats.
A replica that already served a prompt with the same prefix can reuse its cached KV and skip that prefill. A prefix-aware router sends requests where the longest match is, but falls back to load balancing when the match is too short to matter.
Write route_requests(prompts, n_replicas, min_match). prompts is a list of token lists, handled in order. Each replica remembers every prompt sent to it and its load (number of requests sent so far). For a prompt, the match on a replica is the longest common prefix length with any prompt it has seen. If the best match across replicas is at least min_match, pick among replicas with that best match the one with the lowest load, then the lowest index. Otherwise pick the lowest-load replica, then the lowest index. Return the list of chosen replica indices.
def route_requests(prompts, n_replicas, min_match)Example
prompts [[1, 2, 3], [9, 9], [1, 2, 4], [7]], 2 replicas, min_match 2 gives [0, 1, 0, 1].
Understand the idea
Imagine three cooks who each remember the dishes they made today. If an order starts like one a cook already prepared, that cook can reuse the half-done prep. But if the overlap is one onion, it is not worth overloading him. Worked example: replica 0 has seen [1, 2, 3]. New prompt [1, 2, 4] shares 2 tokens; with min_match 2 it goes to replica 0. Prompt [7] shares nothing, so it goes to the least loaded replica. Rule: best = max over replicas of LCP; if best >= min_match choose argmin load among replicas with best match, else argmin load overall, ties to the lowest index. Serving gateways use this to send chat turns and agent calls with long shared system prompts to the GPU that already holds that prefix in its KV cache.