Forward Deployed EngineeringAI EngineeringMulti-turn Prefix Caching

Prefix caching in a multi-turn chatbot: how do client-side and server-side caching cut redundant compute, and what breaks correctness?

Question 68 of 73 · Updated

On this page

Interview-ready answer#

In a multi-turn chatbot, most of the input on turn N is often the same prefix that the model already processed on turn N−1. Prefix caching exploits this overlap. The client or application maintains the canonical conversation history, while the inference server can retain compatible attention key-value (KV) states for previously processed tokens.

The distinction matters: storing conversation text on the client reduces repeated state reconstruction and may reduce network traffic if the API supports incremental conversation references. It does not automatically eliminate GPU computation. The inference server must actually reuse compatible model state to avoid processing that prefix again.

For correctness, reuse only an exact, authorized token prefix under the same model computation, including relevant positions, attention semantics and model configuration. If a user edits an earlier message, regenerates an answer, changes the system prompt or switches model versions, reuse only the still-valid common prefix. Everything after the divergence must be recomputed. A cache miss should affect performance, not the meaning of the conversation.

1. Client-side state versus inference-side state#

LayerWhat it retainsWhat it avoids
Chat clientMessage tree, turn IDs, selected branch, local draftReconstructing UI state and conversation history
Application serverCanonical authorized transcript, message revisions, tool outputs, conversation handlesRepeated history assembly, and sometimes retransmission
Model inference serverCompatible per-layer KV tensors, block metadata and potentially reusable output stateRedundant prefix prefill
Response cachePreviously generated answer for a specific request identityGeneration on a valid answer-cache hit; different correctness requirements

A server-issued conversation handle can make the application send only the latest turn instead of the full history, when the service supports that interface. The server still needs a reliable way to reconstruct the authorized prompt and decide whether inference state is reusable. A browser's localStorage, a saved conversation ID or an HTTP cache does not establish a KV-cache hit.

If the model runs directly on a client device, a local inference engine can own and reuse actual KV state. In that case the same model-state compatibility rules apply; this is not merely client-side transcript caching.

2. Reuse across turns and branches#

Loading diagram…

Consider a canonical serialized conversation represented by token segments S (system instructions), U1 (first user turn), A1 (assistant answer), and U2 (second user turn).

RequestReusable prefix, assuming matching token boundaries and computation
S + U1 + A1 + U2S + U1 + A1, if those tokens have cached state
Edit U2 to U2′S + U1 + A1
Regenerate A1S + U1, up to the first token that changes
Edit U1 to U1′S, up to the actual divergence
Change SOnly the compatible initial tokens before the first difference

The segments are illustrative; implementations must compare the actual tokenized prompt, including role separators, special tokens and assistant-generation markers. Tokenization of appended text is not universally equivalent to tokenizing each segment separately. Also, a generated token may have been sampled but not yet processed into KV state, so the reusable prefix is limited to tokens actually represented in the cache.

A conversation tree allows branches to share immutable cache blocks before divergence. Use reference counting or copy-on-write for shared state. Never mutate a shared prefix block in place when another branch still references it.

3. Why exact prefix matching is necessary#

For a standard causal decoder with fixed model configuration, the state at an earlier position depends on that position and preceding tokens, not later appended tokens. Therefore, the earlier state can be reused for a longer sequence with an identical compatible prefix.

The cache identity must account for all inputs that affect the reused computation:

  • Effective model checkpoint, adapters, tokenizer and chat-template version.
  • Canonical tokens, positions, attention masks and relevant position-encoding configuration.
  • Additional conditioning, such as multimodal embeddings, when applicable.
  • Tenant or approved sharing scope, and authorization or retention boundaries.
  • Compatible KV representation, numerical precision and execution-engine configuration.

With absolute positional embeddings or rotary position embeddings (RoPE), blindly reusing a token span shifted to different positions is not generally safe. Exact prefix reuse at matching positions is different from arbitrary substring reuse. Specialized engines may support validated position transformations or other reuse schemes, but do not assume they apply to a generic cache.

Likewise, inserting a tool result, removing a message during context compaction or replacing an earlier document snapshot changes downstream state. Recompute the suffix after the first incompatible position. Changes in temperature or top-p generally do not alter already computed KV states for a fixed token sequence in ordinary inference, but they may change the subsequent generated tokens. Response-cache identity has stricter requirements than KV-cache identity.

4. Tested Python: scoped, block-aligned prefix matching#

A simple reference implementation finds the number of contiguous reusable tokens, rounded down to complete cache blocks. Here each cached or requested entry is an immutable (token_id, position_id) pair. Scope is trusted, server-constructed compatibility metadata. The example assumes standard causal attention with fixed compatible computation and that every entry in cached has actually been materialized.

PYTHON
def reusable_tokens(cached_scope, request_scope, cached, requested, block_size=1): if type(block_size) is not int or block_size < 1: raise ValueError('invalid block size') if cached_scope != request_scope: return 0 n = 0 for old, new in zip(cached, requested): if old != new: break n += 1 return n // block_size * block_size

For example, cached token IDs [10, 20, 30, 40] at positions 0–3 and requested IDs [10, 20, 30, 99] have a three-token common prefix. A cache using complete two-token blocks may reuse only the first two tokens with this policy; the remaining tokens must be processed again. A different position ID or incompatible scope terminates or prevents reuse, respectively.

Executed verification: Python 3.13.5 passed 5,777 checks: 5,766 exhaustive combinations of two binary token sequences of lengths zero through four, three block sizes and matching or different scopes; six individual scope-field invalidations; one position mismatch; and four invalid block sizes. An independent oracle enumerated matching complete prefix lengths.

The reference function is O(min(cached length, requested length)) in time and O(1) in auxiliary space. Production engines commonly use hash-indexed blocks or radix trees to find shared prefixes efficiently. They must handle collisions safely and include parent-prefix identity, rather than treating an identical local block as sufficient evidence of an identical earlier context.

This helper tests eligibility logic only. It does not implement attention, allocate KV tensors, check actual authorization or guarantee numeric equivalence. A complete cache hit also needs the output state required to obtain the next-token logits; if only KV tensors are retained, the engine may need to reprocess the last token or otherwise reconstruct the required state without duplicating its cache entry.

5. What breaks correctness in production?#

FailureCorrect response
A client sends an outdated conversation revisionReject the conflict or rebuild the explicitly selected authorized branch
A model checkpoint or adapter changesDo not reuse incompatible inference state
Messages are edited, truncated or reorderedMatch the new canonical token prefix and recompute the remainder
Positions, attention masks or external conditioning differRequire verified compatibility or cold prefill
Cache eviction occurs while a request is using a blockPin or reference-count active blocks; recover safely on a miss
Another tenant supplies an identical-looking prefixEnforce the approved sharing scope and authorization before lookup or use
Document permission or retention policy changesRecheck authorization and enforce applicable invalidation and deletion rules

The client must not be allowed to assert its own trusted cache identity or claim ownership of a server cache handle. Authorize access to the conversation and relevant evidence on every request. Shared-prefix caching can also expose timing side channels, even when the caller receives no other tenant's raw tokens. Use conservative isolation for sensitive workloads.

Prefix caches consume finite memory, so use bounded capacity and suitable eviction, for example recency-aware eviction combined with block reference counts. Evict inactive entries without changing the authoritative transcript. If a worker restarts or an entry expires, reconstruct the state from the same authorized prompt instead of silently dropping history. A cache is an optimization, never the source of truth.

6. Verify the optimization before rollout#

Measure warm versus cold time to first token, reused token counts, suffix prefill length, eviction rate, cache occupancy and tenant-level behavior. A high request hit rate can still hide low token reuse if most hits cover only a short prefix.

Test cold and cached execution against the same canonical inputs. Compare next-token logits or probabilities with an appropriate numerical tolerance, then check deterministic decoding where supported. Floating-point implementation differences can prevent bitwise equality, and stochastic decoding is not expected to reproduce identical outputs merely because the KV state is equivalent. Test branches, edits, truncation, model switches, concurrent requests, eviction and permission changes. Require no unauthorized reuse and no silently altered conversation semantics.

FDE-0046 discusses cache economics and FDE-0056 compares evidence-selection architectures. The key lesson here is maintaining coherent inference state across conversational revisions: reuse exactly what remains valid, and recompute everything else.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models