Prefix Sharing Is a Sorting Problem

Rong He proves that choosing the order of reusable prompt pieces (retrieved passages, tool definitions, few-shot examples) to maximize prefix-cache reuse is equivalent to choosing a binary hierarchy over requests, and shows that the single global order used by deployed systems is asymptotically wrong.
Ask this paper
Structure theorem: The minimum prefix-trie cost equals a minimum over binary hierarchies on the requests of the canonical decomposition size of the set of requests that need each chunk. This gives an O(3^m) exact algorithm and maps the two-chunk case to minimum vertex cover.
Global order is wrong: A single global chunk order is optimal only when requests have at most two pieces. On the leave-one-out family it costs Theta(n^2) against a true optimum of Theta(n log n), the merge-sort recursion.
Practical algorithm: Agglomerative clustering by common intersection is a tight 1/2-approximation for the achievable saving and comes within 0.05% of the exact optimum on real retrieval structure.
Measured savings: On BM25 retrieval traces over three BEIR corpora the layout cuts prefill by 17% to 36% against production RAG ordering, and by 13% to 23% when the most relevant passages are pinned in place. Serving requests in the hierarchy's depth-first order lets a cache the size of one request's context reach the unbounded-cache optimum.
Abstract
LLM serving reuses KV cache by exact prefix match, so when a prompt is assembled from a set of reusable pieces -- retrieved passages, tool definitions, few-shot exemplars -- the order chosen for those pieces determines how much computation can be shared. Every deployed system fixes that order by a single global convention. We prove this is optimal only when requests contain at most two pieces, and asymptotically wrong in general. Our main result is a structure theorem: the minimum prefix-trie cost equals min_H sum_x w(x) t_x(H) over binary hierarchies H on the requests, where t_x(H) is the canonical decomposition size of the set of requests needing chunk x. Choosing chunk orders is therefore equivalent to choosing one hierarchy over requests. The identity yields an O(3^m) exact algorithm, identifies the two-chunk case as minimum vertex cover, and shows that on the leave-one-out family the optimum is the minimum external path length of a binary tree -- the merge-sort recursion -- so a global order pays Theta(n^2) against a true cost of Theta(n log n). Agglomerative clustering by common intersection is a tight 1/2-approximation for the achievable saving. On BM25 retrieval traces over three BEIR corpora the resulting layout reduces prefill by 17-36% against production RAG ordering, and the margin widens with retrieval depth as the theory predicts. Serving requests in the hierarchy's DFS order finally lets a cache holding one request's context attain the unbounded-cache optimum exactly, so cache capacity and reorder window act as substitutes.