Prefix Caching
Correct prefix reuse, its prefill savings, capacity and isolation trade-offs, and a measured timing side channel in a scoped block cache.
Suppose a 512-token prefix is already in the cache and a request adds 32 new tokens after it. In this chapter’s local GPT-2 experiment, that request reached its next-token logits in about 22 milliseconds. Without the cached prefix, the same prefill took about 37 milliseconds.
The same cached state also produced a measurable timing signal. In 40 quiet-machine trials, every probe that hit a prefix cached in a shared scope was faster than every probe against a cold cache. That measurement is strong for this controlled set-up. It is not a demonstrated attack success rate against a production API.
Those two results are the same fact seen from two sides. A cache hit is faster because the service has kept state from an earlier request, so the speed-up is also information about that state. If requests from different tenants may use the same prefix-cache identity, a tenant who can guess a prefix may be able to tell a hit from a miss by timing its own request. When each tenant had its own scope, the measured timings overlapped with the cold condition and the pairwise discrimination statistic was 0.554, close to 0.5. That establishes a useful boundary under the tested conditions, not proof of indistinguishability against all attacks. And isolation has a cost: in the synthetic workload, how much reuse it gives up depends strongly on the cache’s capacity.
By the end of the chapter you should be able to build and test a scoped, reference-counted prefix index on PagedAttention’s KV blocks, and to report four things separately: whether reuse changes the result, how much prefill time it saves, how often it hits under limited capacity, and what it leaks. The chapter tests last-logit equivalence against full prefill, measures local prefill savings, simulates reuse under constrained capacity, and tests one timing side channel. It also separates the prototype’s caller-supplied scope from the authentication, identity validation, eviction and deletion controls a multi-tenant service would need.
Where this sits
Key-Value Caching established that cached state is valid only when the computation that produced it is equivalent; its prefix_key(manifest, tokens) helper describes the intended artefact-aware identity contract, rather than enforcing it in every cache implementation. PagedAttention supplied block tables, reference counts and copy-on-write. Continuous Batching showed how a scheduler interleaves requests. This chapter asks a new question of those mechanisms: when unrelated requests begin with identical tokens, which computed prefix blocks may they reuse, and across which trust boundaries?
The Inference Lab increment is a prefix index. Chained SHA-256 hashes map completed token blocks to physical KV blocks. The index pins one reference to every block it registers; later sequences adopt matching blocks without copying their contents; unused entries are evicted in least-recently-used (LRU) order. A separate TokenLevelCache simulates capacity-limited reuse without model tensors. These are reference implementations and experiments, not an integrated, authenticated serving service.
For the Pi series, repeated instructions, tool schemas and conversation history can become a substantial prefill cost. A long-lived agent may recover that cost through prefix reuse, but only while the exact prefix and execution identity remain stable. An agent service with several users must also decide whether their KV state is allowed to influence one another’s latency. Performance optimisation and isolation policy are therefore part of the same serving contract.
What can be shared
Start with two requests that begin with the same 300-token system prompt and then ask different questions. During prefill, the model computes a key and a value for every position. The question is whether the keys and values for the first 300 positions of the second request would be the same as those already computed for the first.
Causal attention answers it. At position \(i\), each layer attends only to positions up to \(i\). So, with the same effective input, model parameters and execution configuration, the hidden state at position \(i\), and therefore the KV tensors computed from it, cannot depend on any token after \(i\). The two requests diverge only after position 300; nothing before that point can see the divergence. Two requests with the same complete prefix can consequently reuse KV state for that prefix.
This is a mathematical property of causal attention, subject to a numerical-equivalence check in the actual backend. It is not a licence to reuse a matching piece of text that appears after different preceding content. A fragment in the middle of a prompt ordinarily attends to everything before it, so after different preceding context it needs recomputation or a specially validated reuse method. Prefix caching is about prefixes.
What “the same prefix” has to mean
The visible prompt text is not enough to decide that two prefixes are the same. A cached key or value is determined by everything that went into computing it:
- The effective token and input-embedding sequence. Exact token IDs and order are required; for multimodal models, images and other modalities must be represented by trustworthy content identities, not merely matching text placeholders.
- Position and attention context. Position IDs, RoPE configuration, attention masks, sliding-window rules and other stateful attention choices can change the result even for matching token strings.
- The model artefact and numerical path. Checkpoint weights, adapters, relevant runtime transformations, precision and quantisation, and any execution settings that affect the resulting KV state must be captured in an artefact/configuration identity.
- Prompt processing. Tokenizer and chat-template versions, special tokens and tool/message formatting affect the effective input. The strongest check hashes the effective inputs after these transformations.
- The trust boundary. A tenant- or user-scoped secret must distinguish parties that are not authorised to share cache-hit information, independently of whether their computation happens to be identical.
The last item is different in kind from the others. The first four decide whether reuse would give the right answer. The fifth decides whether reuse is permitted, even when the answer would be identical.
I call the non-token part of this identity the scope. In the prototype, the scope is a plain string, accepted from the caller and hashed into each block’s key. The prototype neither constructs the scope from an artefact manifest nor verifies who supplied it. A safe service should derive or validate execution identity and isolation identity from trusted configuration and authenticated principals, not accept an arbitrary client-chosen shared scope. It should version the identity format, canonicalise its encoding, and invalidate entries when a relevant dependency changes.
A key that includes its history
The cache works in blocks of 16 tokens, the PagedAttention block size. The obvious key for a block is a hash of its 16 token IDs. That key is wrong, and seeing why explains the design.
Take two prompts. The first is block A followed by block B; the second is block C followed by the same tokens B. If the key for the second block were a hash of B’s tokens alone, both prompts would produce the same key for their second block, and the second prompt could adopt the first prompt’s KV state for it. But those KV values were computed while attending to A, not C. The key has silently merged two different histories.
The prototype prevents this by chaining. Each block-level key is a SHA-256 digest over a string encoding of the scope, the preceding block’s digest and this full block’s token IDs:
The unit test shows exactly that: a second block with the same local tokens but a different preceding block has a different chained key, while the unchained construction aliases the two histories. The test proves that the unchained design would alias two different histories; it does not execute an end-to-end model corruption attack using that mistaken key. Key-Value Caching’s separately recorded stale-prefix experiment illustrates the possible numerical consequences of reusing incompatible KV state, but its logit errors and token agreement are not measurements of this chapter’s hash-key defect. SHA-256 also makes accidental hash collisions implausible, but the prototype does not specify a canonical length-delimited, cross-language key encoding or a cryptographic threat model.
vLLM’s documented automatic prefix caching also hashes full blocks using their parent hash, block tokens and relevant extra identities such as adapters or multimodal content. Its documentation describes SHA-256 as a default and an optional cache salt applied at the first block, after which the hash chain propagates the distinction. This book’s reference implementation includes the scope in every block hash instead. These are related designs, not evidence of identical eviction, authorisation or multi-tenant security. For deployments, the current vLLM security guidance explicitly treats cache salting as a mitigation rather than an isolation boundary and recommends enforcing tenant separation at the gateway or instance level.
The mechanism
The prototype extends the PagedAttention pool with four operations (lookup, adoption, registration and eviction) plus an admission-time attempt to free blocks. A request looks for a cached prefix and adopts what was found, then attempts to free needed blocks by eviction before computing the suffix and registering completed blocks. The descriptions below are of the current prototype, including its deliberately conservative rule about the final token.
Lookup. Hash the prompt’s full blocks in order, then walk the index until the first missing block. The walk stops there, so the index cannot reuse blocks beyond a missing parent even if their hashes remain resident. One more rule limits how far lookup may go. The model must still produce logits for the last prompt position, and in this KV-only interface the only way to get them is to compute at least that position fresh. So longest_prefix deliberately leaves at least one prompt token uncached:
usable = (len(tokens) - 1) // block_size
For a prompt of exactly four blocks (64 tokens), \((64 - 1) // 16 = 3\), so this implementation reuses at most three blocks even if all four are cached. This is a limitation of the current KV-only interface, not a universal constraint of prefix caching: an engine that safely caches the necessary final logits or handles the last-token case differently can use another policy.
Adopt. PrefixIndex.adopt adds an owner reference to each matched physical block and installs those blocks in the new sequence’s block table. It does not copy the KV tensors or recalculate their contents; the new sequence simply points at memory that already holds them. This is safe only while the index entry is correct for the request’s trusted execution identity and trust scope, and the prototype’s caller-provided string does not establish those preconditions by itself.
Register. After the suffix has been computed, PrefixIndex.register walks the completed full blocks and records any keys not already in the index, incrementing each block’s reference count to represent the index’s own ownership. A partial trailing block remains owned by the request and is not registered. Registration happens after a successful prefill. It is not a transaction spanning lookup, allocation, model execution and cleanup, so concurrent registrations and model-execution failure paths are outside the tested contract.
Evict. When more free blocks are needed, ensure_free asks the index to release the oldest entries whose physical blocks have no reference except the index’s. A block pinned by an active sequence cannot be evicted. The index does not automatically evict descendants when an ancestor is removed. Since lookup stops at the first missing block, those descendants can no longer be reached as part of a complete prefix, yet they continue to occupy cache capacity.
The tests establish basic reference-count safety, LRU ordering and eventual release after explicit sequence freeing and index eviction. They do not establish transactional failure recovery, concurrency safety, bounded memory pressure or secure erasure.
It changes nothing
The first thing to check about a cache is that it does not change the answer.
In the recorded GPU experiment, eight requests shared a 300-token system prefix and then added 20, 27, 34, … up to 69 request-specific tokens. The first request, 320 tokens long, found an empty cache and reused nothing. Each of the next seven reused 288 tokens, which is 18 full 16-token blocks.
Why 288 and not 300? Eighteen blocks cover positions 1 to 288. The nineteenth block would cover positions 289 to 304, but only its first 12 tokens belong to the shared prefix; the rest are the first request’s own suffix. That block’s key therefore differs from the key the next request computes, and lookup stops before it. The shared prefix’s remaining 12 tokens do not form a reusable full block before the divergent suffix.
Against independent full prefill, the maximum absolute difference in the final-position logits was \(7.6 \times 10^{-5}\), and all eight next-token argmax choices agreed. This supports next-token parity for this checkpoint and these prompts. It is not proof of bitwise KV equality, full-logit-tensor equality, or correctness under every adapter, mask, position scheme or model update. CPU unit tests cover the analogous mechanisms on a small model.
What it saves
The local benchmark compares two sequential requests that share a prefix of \(P\) tokens and then have different 32-token suffixes. The first request fills a fresh cache (the miss); the second reuses its registered prefix blocks (the hit). Each condition used 18 paired trials with the first 3 discarded, leaving 15 per length. The times include synchronous Python dispatch, index work and model prefill, but not network transport, queueing or a full decode stream. The numbers are medians of the recorded runs:
| Cached prefix | Miss | Hit | Speed-up |
|---|---|---|---|
| 128 tokens | 22.1 ms | 22.1 ms | 1.00 |
| 256 tokens | 25.4 ms | 22.3 ms | 1.14 |
| 512 tokens | 37.1 ms | 22.0 ms | 1.68 |
| 768 tokens | 57.3 ms | 22.2 ms | 2.58 |
What differs between the columns is how much is computed. Whatever the prefix length, a hit computes only the 32-token suffix; a miss computes the whole prompt. In the recorded medians, the hit time stayed close to 22 ms in all four cells, while the miss time grew with prompt length. At 128 cached tokens the two medians were effectively identical (22.1 versus 22.1 ms); at 768, the median saving was about 35.1 ms.
It would be too strong to call 22 ms a universal GPU launch floor. It is the observed cost of this particular suffix-prefill path, including its Python and allocator overhead. The evidence shows a crossover in this local workload, not that short prefixes can never benefit from caching.
For a different model or kernel, the saving depends on the marginal prefill work actually skipped, the layout and size of the remaining suffix, cache lookup overhead, and whether the saved compute is on the critical path. It is not generally equal to the stand-alone prefill time of the cached tokens, because prefill cost is shape-dependent and the two executions share some overhead. Nor does it follow that the longest prefix should always win eviction priority: a shorter, frequently reused prefix can save more aggregate time per occupied cache byte. A production policy should estimate expected reuse benefit per scarce KV block, then measure the effect on admission and TTFT.
How often it hits
Saving 35 ms on a hit matters only if hits happen. How often they do depends on the order in which requests arrive and on how much cache there is to hold prefixes between them. To isolate that trade-off, TokenLevelCache models a block-hash index with an LRU capacity limit, without storing KV tensors or running a scheduler. It inserts the full blocks of each observed prompt and counts the blocks reusable from the start of each later prompt. Its results are simulation outputs, not measured hit rates of the GPU implementation under load.
The synthetic workload imitates a small multi-tenant agent service:
- 120 synthetic sessions are assigned among 5 tenants. Each picks one of 8 system prompts of 512 tokens, with popularity proportional to \(1/k\), and receives 1 to 6 turns.
- Each submitted prompt concatenates the system prompt, the synthetic prior conversation and 90 new user tokens. After each request, 90 generated-reply tokens are appended to the session history for its next prompt, but their KV blocks are not registered by the cache model at generation time.
- Sessions are interleaved by a seeded random generator. The recorded run comprises 437 requests and 395,914 prompt tokens, or about 906 tokens per request. Neither the popularity curve nor the timing of sessions is calibrated to a production trace.
The reported token hit rate is the total number of prompt tokens matched in complete reusable prefix blocks, divided by the total number of prompt tokens presented. It is not the fraction of requests with a hit, GPU memory utilisation, bytes saved, or the proportion of time eliminated. With the same eight system prompts available to all tenants, the deterministic token-level model gives:
| Cache size | One shared scope | One scope per tenant |
|---|---|---|
| 1,024 tokens | 8.0% | 2.7% |
| 4,096 tokens | 38.2% | 15.1% |
| 16,384 tokens | 66.4% | 46.5% |
| 65,536 tokens | 81.1% | 77.9% |
These four cache sizes illustrate different operating points of this specific access trace; they should not be read as universal cache-sizing thresholds. Three patterns are visible in the table, and a control scenario adds a fourth.
Capacity matters for the tested trace. At 1,024 tokens, only 64 blocks are resident and the hit rate is low. With 65,536 tokens (4,096 blocks), the shared-scope trace reaches 81.1%; increasing capacity further to 262,144 tokens produces the same 81.1% in the recorded model. To give those sizes a physical meaning: for GPT-2 with 12 layers, 12 heads and head dimension 64 in fp32, a KV token occupies 73,728 bytes (72 KiB), so 65,536 tokens correspond to 4.5 GiB of logical KV block payload before allocator, index and runtime overhead. This is a capacity conversion, not an observed GPU allocation in the simulation.
Isolation costs reuse when tenants otherwise share prefixes. At 4,096 tokens of cache capacity, one shared scope gives 38.2% token reuse and separate tenant scopes give 15.1%, a 23.1 percentage-point difference (about 2.5 times as much reuse in the shared case). At 65,536 tokens the figures are 81.1% and 77.9%, a 3.3-point difference. The mechanism is visible in the set-up: separate scopes duplicate physically identical prompts across tenants, because reuse is forbidden across the boundary. These values depend on the synthetic popularity, interleaving and eviction model. They do not price the privacy risk, and they do not imply that removing isolation is an acceptable optimisation.
Without cross-tenant shared content, an isolation key need not reduce reuse. In a second synthetic scenario, every tenant receives distinct system-prompt token sequences. Shared and per-tenant scopes then produce identical reported rates at each cache size, because this trace creates no cross-tenant prefix matches to lose. That is a useful control, not a guarantee that real tenants have no overlapping content or that shared-cache timing has no other interference channels.
The 81.1% is a property of the trace, not a ceiling. It comes from the generated trace and this simplified cache. The model registers prompt blocks but not KV blocks from generated replies as those replies are produced. Later conversation prompts include those reply tokens, so the missing registration can reduce potential reuse. Adding decoded blocks, however, would also consume capacity and change LRU eviction, so the net hit-rate change cannot be inferred without running a new simulation. The token cache also does not account for blocks pinned by running requests, physical allocation pressure, eviction costs or actual prefill-time savings.
What it gives away
A prefix-cache hit reduces work, and so may reveal an observable timing difference to another caller. Whether that becomes a privacy vulnerability depends on four things: who can choose the tested prefix, who can access the same cache identity, what they can observe, and the noise and rate limits of the serving path.
The local experiment models a caller trying to determine whether a particular 512-token prefix was cached before its probe. For each of 40 retained trials per condition, the program creates a fresh local cache, optionally lets a first request (the “victim”) register the prefix, and then times the probe’s prefill. A probe in the same scope can reuse those blocks; a probe in a different scope cannot. This is an in-process timing experiment with a known candidate prefix. It is not a remote request against an external service, a reconstruction of private prompt contents, or a demonstrated rate of successful guesses against real users.
| Condition | Median first-token time | Range |
|---|---|---|
| Victim used the prefix, attacker in the same scope | 22.6 ms | 21.6 – 27.9 ms |
| Victim used the prefix, attacker has their own scope | 36.2 ms | 35.5 – 37.7 ms |
| Nobody used the prefix | 36.4 ms | 35.4 – 40.5 ms |
The first row is a cache hit and looks like the hit column of the previous section. The second and third rows are both misses, and their ranges overlap: from the attacker’s side, a victim in another scope was hard to distinguish from no victim at all in these trials.
The recorded distributions did not overlap for the shared-scope hit and the cold probe: the slowest hit was 27.9 ms, below the fastest cold probe at 35.4 ms. To put a number on separation, the chapter’s auc helper takes every pairing of one time from each condition (40 × 40 = 1,600 pairs) and counts the fraction ordered as expected, counting ties as half. A value of 1.0 means every pair is ordered as expected; 0.5 is what two indistinguishable distributions would give. It is 1.00 for shared-scope hit versus cold, and 0.554 for isolated-scope versus cold.
This statistic describes separation of these 40-by-40 sample pairs. It does not mean an attacker has certainty, and a value near 0.5 is not itself a significance test or proof that all information channels are closed. Larger or noisier systems require fresh attack and control measurements.
Three qualifications belong with this result: the measurement environment, the isolation boundary, and the attacks not exercised.
A favourable measurement environment, not a production attack. The probe ran within one process, on a GPU without concurrent serving traffic, against a 512-token prefix whose uncached prefill was about 14 ms slower. Network transport, queuing, warmed state, other tenants and different backend kernels could change both distributions. We did not measure their effect. A larger model could have a larger absolute miss penalty, but that is a hypothesis here, not an extrapolated attack success rate. The experiment also assumes the attacker already knows the candidate prefix; discovering unknown prompts is a different, untested task.
Isolation must be imposed by a trusted boundary. The local PrefixIndex treats scope as an opaque caller-provided string. Passing distinct strings prevents hits between these two identities in the test, but the code does not authenticate tenants or stop a caller from claiming another tenant’s scope. vLLM’s documented cache_salt similarly segregates prefix hashes when different secret salts are supplied, but vLLM’s security guidance explicitly cautions that salting is not full tenant isolation. A service should derive an unguessable salt from authenticated principal identity, enforce access control, and use a separate process or deployment where stronger isolation is required. A predictable tenant label or a client-selected salt is not a security boundary.
Other channels remain untested. The prototype does not measure adversarial eviction, denial of service, interference through shared scheduling, cache lifetime, sanitisation on block reuse, memory inspection, or deletion guarantees. A caller might compete for capacity or observe effects besides an exact-prefix hit, but this chapter did not demonstrate those attacks. Physical KV storage can be derived from sensitive prompts even when only hashes are used as index keys; retention and deletion therefore need their own enforceable policy and tests.
Provider caching
Hosted APIs expose prompt caching as an interface, not as a physical block allocator. Anthropic’s current documentation supports automatic caching with a top-level cache_control field and explicit breakpoints on selected content blocks. It documents a default five-minute lifetime, an optional one-hour lifetime, exact matching of the cacheable prefix across tools, system and messages, model-dependent minimum lengths, and accounting for cache writes and reads in response usage. It also describes organisation-level separation and platform-dependent workspace isolation: the Claude API, Claude Platform on AWS and Microsoft Foundry use workspace isolation, while Amazon Bedrock and Google Cloud have organisation-level isolation. Those are provider-published interface statements; this book has not audited the service internals or independently tested the isolation guarantees. Consult the current provider documentation before implementing policy or prices.
For a caller, the useful contract is which content must match, how a cache breakpoint or automatic placement is selected, how long the entry can be reused, and which usage counters distinguish a write from a read. A hit does not expose the provider’s storage format, block size, tenancy mechanism or physical KV layout. A practical experiment should record the provider and model version, cache settings, effective prompt order, observed read/write tokens, costs and TTFT; it should not infer internal block tables from API timings alone.
Inference Lab increment
The Lab now has:
block_hash,chain_hashes(scope, tokens, block_size)and the deliberately incorrectunchained_hashes, with a unit test demonstrating a history alias under the unchained construction.PrefixIndex.longest_prefix,adopt,register,evict,ensure_free: a reference-counted KV block index whosescopeparameter is supplied by its caller. Basic LRU, no-eviction-while-pinned and explicit cleanup are tested; authenticated scope construction and transactional failures are not.prefill_with_prefix_cache, which reuses a matched full-block prefix and computes the remaining prompt positions on the real GPT-2 reference path.TokenLevelCache,agent_workload,simulate_hit_rateandauc, for capacity/isolation scenarios and pairwise timing discrimination.- The runnable
ttft,hitrate,sidechannelandexactnesscommands. Their reports distinguish measured GPU timings from purely synthetic token-hit rates.
The rule this chapter adds to Key-Value Caching and PagedAttention is: a reusable KV block needs both an exact execution identity and an authorised sharing identity. A correct hash chain establishes that a key depends on the whole input history. It cannot verify that the caller supplied the right model manifest, or that the caller is entitled to join another tenant’s scope. A cache can therefore be computationally correct and still create a privacy problem. Report hit rate, saved prefill time, memory occupancy and cross-scope timing leakage separately, rather than treating any one of them as proof that the cache is safe or efficient.
Limits of this chapter’s evidence
Set-up.
- One GPT-2 checkpoint and one local execution path. The latency measurements used the hand-written fp32 paged forward; other kernels, GPUs, model sizes and longer contexts were not measured.
- Untrusted scope input. The code does not bind a scope to authenticated identity, manifest, tokenizer, adapter, attention configuration or quantisation state. Security claims require that integration.
Measurements.
- Limited correctness checks. Eight full-model prompts were compared only at the final-position logits and next-token argmax. Small-model CPU tests exercise the index; they are not an exhaustive proof over runtime configurations.
- One controlled timing channel. Forty samples per condition after warm-up, one 512-token candidate, no concurrent load, network or attacker search. No uncertainty interval or replication across independent environments.
- Synthetic hit-rate workload. One seeded sequence of 437 requests, Zipf-popular system prompts and fixed 90-token turns/replies. No production traffic, time-based eviction, live-request pinning or decoded-block registration is simulated.
Implementation.
- Eviction and failure gaps. Simple LRU does not enforce prefix-ancestor retention, TTL, quotas, atomic multi-operation rollback or secure deletion.
- No multimodal implementation or poisoning/DoS evaluation. These remain design and security work, not established results.
Scope.
- Provider API evidence is documentary. Anthropic’s published caching and isolation semantics are not independently verified here.
What you should now be able to do
- Explain why causal KV state is reusable for a matching complete prefix, but not ordinarily for matching text fragments after different preceding context.
- Derive a chained block key and identify the model/configuration and trust-domain fields its scope must bind.
- Implement and test lookup, adoption, registration, reference-counted eviction and the prototype’s final-token rule.
- Distinguish next-token numerical parity from bitwise equality, full-generation parity and production robustness.
- Report saved prefill time and token hit rate as different metrics with different denominators.
- Predict how capacity, prompt popularity, eviction and tenant isolation can alter reuse in a synthetic trace.
- Interpret a timing AUC as finite-sample discrimination, and explain why an arbitrary caller-supplied scope is not an isolation boundary.
- Distinguish provider API caching semantics from unobserved implementation details.
In this chapter’s implementation, prefix reuse changes only prefill: once a request starts generating, it still makes one model call per new token. Speculative Decoding turns to that loop and asks whether a smaller model’s guesses can reduce the number of sequential calls to a larger one and what it takes to keep the output faithful to the larger model.
Key terms
- Prefix cache: reusable KV state for a complete initial sequence of effective model inputs.
- Chained block hash: an identifier for a full token block that includes its parent-prefix identity.
- Execution identity: the weights, configuration, effective inputs and numerical context needed to decide whether cached computation is reusable.
- Isolation scope: a trusted boundary defining which principals may share cache-hit information.
- Cache salt: a secret value incorporated into the hash chain to separate identities; useful mitigation, not a complete tenant boundary.
- Token hit rate: tokens in reusable matched prefix blocks divided by all prompt tokens presented.
- LRU: an eviction order based on most recent access; it need not preserve useful ancestor chains unless designed to do so.
- Timing side channel: inference about hidden state from latency differences between chosen inputs.
- AUC / pairwise discrimination: the probability, estimated from sample pairs, that the chosen timing order distinguishes two conditions.
- Cache breakpoint: an API-specified position up to which the provider may cache a matching prompt prefix.
Reader exercises
- Extend the token-level simulator to register generated-reply blocks; rerun all capacities and measure both the hit-rate change and any extra evictions. Do not assume the change is positive.
- Change
PrefixIndex.evictto preserve ancestor reachability or reclaim unreachable descendants. Test the resulting useful hit rate per physical block. - Compare a single shared system prompt across five tenants under a shared scope and authenticated per-tenant scopes; report the privacy-policy trade-off separately from capacity savings.
- Repeat the controlled timing experiment with concurrent load and report confidence intervals, AUC and false-positive/false-negative rates at a fixed decision threshold. Keep it on a system you own or are authorised to assess.
- Construct a canonical scope from the From Training to Execution artefact manifest, tokenizer/template version, position/mask settings and an authenticated tenant secret; test that changing quantisation or an adapter invalidates reuse.
- Add a TTL and per-tenant quota, then test expiration, isolation, final-reference release and secure data handling after block reuse.
- Compute an expected-value caching policy: saved prefill milliseconds per cache byte times predicted reuse probability. Compare it to raw longest-prefix-first and LRU under the book’s seeded trace.
- For the Pi agent pipeline, identify the exact prefix boundary across repeated system instructions, tool definitions and conversations; state which user data must never be reused across tenants.
References
Three primary research papers underpin the chapter’s design, serving trade-offs and privacy assessment:
- SGLang: Efficient Execution of Structured Language Model Programs — introduces RadixAttention to reuse KV state across related program calls; relevant to the prefix-index design, not a performance claim reproduced here.
- Preble: Efficient Distributed Prompt Scheduling for LLM Serving — shows why the value of reusable prefixes depends on scheduling and placement across servers; neither distributed placement nor its reported gains were tested in this chapter.
- Auditing Prompt Caching in Language Model APIs — studies cache-related timing variation and potential cross-user privacy implications in hosted APIs; the local 40-trial demonstration here is independent and narrower.
Implementation and provider documentation, rather than additional original experiments:
- vLLM: Automatic Prefix Caching and vLLM security guidance — chained full-block hashes, salting, collision considerations and the limits of salting as a tenant isolation mechanism.
- Claude prompt caching — automatic/explicit breakpoints, time-to-live, usage fields and documented platform-specific scope. These are externally specified API contracts, not proof of underlying storage.
Evidence in this chapter
| Claim | Category and evidence boundary |
|---|---|
| A causal model can reuse KV state for an equivalent complete prefix | Established principle, conditional on the same effective computation and positions |
| Parent-chained block identities prevent the tested history alias | Algorithm and unit test; no full-model unchained-key exploit was executed |
| Exactness experiment: worst final-position logit error 7.6e-5, eight matching next-token choices | Book GPU result, eight GPT-2 prompts; not bitwise or end-to-end-generation proof |
| Local cached-prefix prefill: 512+32 tokens, 22.0 ms hit versus 37.1 ms miss | Book GPU result, 15 retained paired trials; no network or queueing |
| Reuse by cache size: shared scope 8.0% to 81.1%, per-tenant scope 2.7% to 77.9% | Seeded 437-request token-level simulation; not measured GPU service hit rates |
| Shared-scope timing AUC 1.00 and isolated-versus-cold AUC 0.554 | Book result, 40 samples per condition, quiet one-process setting; not attack certainty or security proof |
The prototype’s scope identifies authorised tenants |
Not established: scope is caller-supplied and not authenticated in the code |
| Full-prefix final-token recomputation is required for all caches | Not established: a constraint of this KV-only reference path |
| Production-style isolation and multi-tenant deletion, quotas, TTL, failure rollback | Not implemented or measured |
| Provider breakpoints, TTLs, usage and workspace rules | Provider documentation only, subject to version and platform |
| Larger-model gains, real traces, distributed prefix-aware scheduling | Research direction; not measured in this chapter |