Large Language ModelsInference & Performance Optimization

How do you make shared KV-cache reuse safe across adapters, model versions, and tenants in distributed LLM serving?

Question 292 of 309 · Updated

On this page

The production problem#

A shared KV cache can remove repeated prefill work across replicas. A worker computes the key/value tensors for a prompt, stores them in a shared cache tier, and another worker can retrieve those tensors rather than recomputing the prefix. This is especially useful when replicas serve the same long system prompts, documents, or conversation prefixes.

But identical token IDs do not necessarily mean identical KV state, and identical KV state does not necessarily mean two tenants are allowed to share it.

Consider two workers running the same base model:

  • Worker A serves adapter legal-v3.
  • Worker B serves adapter medical-v2.
  • Both receive the token sequence [101, 205, 991, ...].
  • A shared cache derives its key only from those token IDs and a coarse model name.

Worker B can now retrieve tensors produced under the legal adapter and continue decoding with the medical adapter. The request may complete normally, but its prefix representation was computed under the wrong weights. This is a silent correctness failure, not simply a cache hit-rate problem.

There are two separate questions every cache lookup must answer:

  1. Computational compatibility: Would these exact cached tensors be valid for this request's model execution?
  2. Sharing authorization: Is this requester permitted to reuse the cached state, even if the tensors are computationally compatible?

A safe design encodes both answers into the cache identity.

1. Understand the provenance of a KV block#

A KV block is the result of running a particular token prefix through a particular computational configuration. A production cache key therefore needs more than the token sequence.

A practical provenance descriptor can include:

  • Base model immutable revision or weight digest, not just a friendly model name.
  • Adapter identity and immutable adapter revision, including adapter composition and scaling configuration.
  • Relevant execution configuration: architecture/config revision, positional-encoding or RoPE settings, attention implementation when it changes tensor semantics, and any model-side behavior that affects the KV values.
  • KV representation: dtype, quantization format, scale metadata, layout, head mapping, block format, and serialization version.
  • Tokenizer and tokenization revision where token IDs or special-token interpretation can differ.
  • Multimodal inputs and preprocessing identity when image/audio/video embeddings contribute to the cached state.
  • Parallelism/sharding layout or worker compatibility domain when the stored representation is not portable across layouts.
  • Tenant or trust-domain salt that defines who is allowed to share.
  • Cache schema / connector protocol version.

Not every deployment needs every field in every key. The rule is: if changing a dimension can change the cached bytes, their interpretation, or the permission to reuse them, that dimension must be represented in the cache contract or proven equivalent by an explicit compatibility rule.

Do not blindly include volatile fields such as request ID, worker ID, timestamp, or random nonce. Those destroy legitimate reuse. The descriptor should identify stable semantic compatibility, not the individual request.

2. Separate computational identity from sharing identity#

A useful design has two namespaces:

Computational identity identifies the exact producer context that determines the KV tensors. For example:

LaTeX

Sharing identity identifies the trust boundary inside which reuse is permitted:

LaTeX

Then a block key can be derived as:

LaTeX

The parent prefix hash matters because the KV state for a later block depends on the preceding context. Hashing each block independently by its local token IDs is not enough: the same block text after two different histories can have different hidden states.

For systems that intentionally allow cross-tenant sharing of public, immutable prefixes, define a separate explicit public sharing domain. Do not achieve this by omitting the tenant salt globally. Public-prefix reuse should be an opt-in policy with a clear classification and review process.

A descriptor might look like this:

JSON
{ "schema": "kv-provenance-v2", "base_model_digest": "sha256:base-weights-revision", "adapter": { "id": "support-agent", "revision": "sha256:adapter-weights", "composition": "adapter-stack-v4", "scale": "1.0" }, "execution": { "model_config_digest": "sha256:model-config", "rope_config_digest": "sha256:rope-config" }, "kv": { "dtype": "fp8", "quantization_scales_digest": "sha256:scales", "layout": "paged-v3", "serialization": "connector-v2" }, "tokenizer_digest": "sha256:tokenizer", "sharing_domain": "tenant-group-42" }

Use canonical serialization: deterministic field ordering, normalized numeric representations, explicit null/default handling, and a versioned schema. Hashing arbitrary JSON serialization can create accidental misses when two workers serialize equivalent descriptors differently.

3. Why the engine-to-shared-cache boundary is dangerous#

Many serving stacks have a local prefix cache and an external/shared KV tier. The local engine may know the adapter ID, active model revision, tenant salt, or cache format. The connector may receive only a token-derived key and a model label.

That is a provenance-loss boundary.

A safe API should pass a typed provenance descriptor from the engine to the connector for both lookup and store. Do not calculate a rich key during lookup and a weaker key during store. The same canonical key builder must be used for:

  • local cache lookup;
  • shared-cache lookup;
  • cache write;
  • replica-to-replica transfer;
  • cache restore after worker restart;
  • cache invalidation and migration.

The shared cache must not trust a caller-supplied opaque key without validating that the descriptor is allowed for that model and tenant. The connector should also reject unknown schema versions and unsupported representations rather than guessing.

4. A numerical example: why a coarse key is a correctness bug#

Assume two adapters share a 7B base model and both receive the same 8,192-token prompt.

  • Adapter A produces 8,192 tokens' worth of KV state.
  • Adapter B receives the same token IDs.
  • A coarse shared key uses only base model name plus prompt hash.
  • The cache reports a hit for B, avoiding 8,192 tokens of prefill.

The apparent hit rate improves, but the cache has returned A's representation to B. If the adapter changes attention-side projections, the cached K/V tensors can differ. B's subsequent attention reads a prefix encoded under A's adapter. The result is not equivalent to running B from scratch.

Suppose the faulty path yields 64% task accuracy while the clean uncached B path yields 94% on a controlled evaluation set. The 30 percentage-point drop is not a latency trade-off; it is a cache-key correctness failure. These numbers are an illustrative incident scenario, not a universal expected effect.

Now add tenant isolation. Suppose two tenants use identical model and prompt inputs. Even if the KV bytes are computationally identical, one tenant may have included confidential context in its prompt. A cache hit timing difference can reveal whether a guessed prefix is already cached. A shared salt or namespace prevents a tenant outside the trust group from observing that reuse.

5. Safe lookup and store flow#

A robust request path looks like this:

  1. Resolve the model to immutable base-weight and configuration revisions.
  2. Resolve the adapter stack to immutable IDs, revisions, ordering, and scaling.
  3. Resolve the tenant's cache-sharing domain from trusted server-side authorization, not from an untrusted request field.
  4. Determine the exact KV dtype, quantization scales, layout, and serialization contract.
  5. Canonicalize and hash the provenance descriptor.
  6. Derive the prefix block key using the descriptor, parent-prefix hash, and block token IDs.
  7. Query local cache, then shared cache.
  8. Validate the returned entry's descriptor, schema, checksum, tensor shape, dtype, and layout before attaching it to the request.
  9. On a miss, compute the block and store it under the same provenance-aware key.
  10. Emit hit/miss and compatibility telemetry without logging raw prompts, salts, API keys, or tenant secrets.
PYTHON
def build_provenance(request, trusted_tenant_context, model_registry): model = model_registry.resolve_immutable(request.model) adapter = model_registry.resolve_adapter_stack(request.adapters) return canonicalize({ "schema": "kv-provenance-v2", "base_model_digest": model.weights_digest, "model_config_digest": model.config_digest, "adapter_stack_digest": adapter.stack_digest, "adapter_revisions": adapter.revision_digests, "adapter_scales": adapter.scales, "tokenizer_digest": model.tokenizer_digest, "rope_config_digest": model.rope_config_digest, "kv_format": model_registry.kv_format_for(request), "sharing_domain": trusted_tenant_context.kv_sharing_domain, }) def lookup_block(tokens, parent_hash, provenance, shared_cache): descriptor_hash = stable_hash(provenance) key = stable_hash({ "schema": provenance["schema"], "descriptor": descriptor_hash, "parent": parent_hash, "tokens": tokens, }) entry = shared_cache.get(key) if entry is None: return None if entry.provenance_hash != descriptor_hash: raise CacheCompatibilityError("KV provenance mismatch") validate_checksum(entry) validate_tensor_metadata(entry, provenance) return entry

The code is conceptual. Real connectors need authenticated metadata, bounded parsing, collision-resistant hashes, concurrency control, and explicit tensor-format adapters. A checksum detects corruption; it does not prove that the entry is semantically compatible. That guarantee comes from the provenance descriptor and trusted key derivation.

6. Tenant isolation is an authorization property#

A tenant salt is not an API key and should not be accepted directly from a user as proof of access. The serving gateway should map an authenticated principal to a server-controlled sharing domain.

For example:

  • Tenant A's private prompts use salt/domain A.
  • Tenant B's private prompts use salt/domain B.
  • A deliberately shared public system prompt uses a reviewed public domain.
  • Two subsidiaries may share a domain only if the data-sharing agreement and security policy explicitly allow it.

Use high-entropy salts or opaque domain identifiers. Avoid predictable tenant names in externally observable cache keys. Rotate salts when trust boundaries change, and treat rotation as a cache namespace migration: old entries become unreachable and expire through normal retention policy.

Salting reduces cross-domain cache reuse. That is intentional. Do not optimize away the isolation boundary to improve hit rate.

7. Versioning and rolling deployments#

A common operational failure occurs during a rolling deployment:

  • Half the fleet runs model revision M1.
  • The other half runs M2.
  • Both advertise the same friendly model name.
  • The shared cache treats their prefixes as interchangeable.

The same problem appears when a LoRA adapter is updated in place, quantization scales are recalibrated, a tokenizer changes, or a connector changes its serialized tensor layout.

Use immutable digests and a versioned cache schema. During a rollout:

  1. Publish the new model/adapter/config revision.
  2. Start workers that advertise the new provenance identity.
  3. Allow old and new workers to coexist, but never let them reuse incompatible entries.
  4. Measure cache warm-up and hit-rate changes by revision.
  5. Retire old workers and allow old cache namespaces to expire.
  6. Only add an explicit compatibility mapping if it has been validated with tensor-level and output-level tests.

Do not rely on mutable aliases such as latest, production, or a model display name as cache identity.

8. How to test the contract#

Build a differential test matrix. For each dimension, change only that dimension and verify whether reuse is allowed.

ChangeExpected cache behavior
Same model, adapter, KV format, tenant domain, and prefixReuse allowed
Different LoRA adapter revisionMiss / isolated namespace unless a proven compatibility mechanism applies
Different base-weight digestMiss
Different quantization scales or KV dtypeMiss unless a tested conversion path is explicitly used
Different tokenizer or multimodal preprocessing revisionMiss when it changes token/state interpretation
Different tenant sharing domainMiss, even if the bytes would otherwise match
Same public shared-prefix domain and same computational identityReuse allowed by policy
Different connector serialization versionMiss or explicit validated migration

Also test negative cases:

  • A worker omits adapter identity.
  • A connector silently drops tenant salt.
  • A model alias points to a new weight digest.
  • One replica uses stale quantization scales.
  • A cache entry is truncated or has the wrong tensor shape.
  • A malicious client supplies another tenant's sharing-domain value.
  • A rolling deployment sends a request to a worker with a different model revision.
  • A cache key is built with a different canonicalization version.

A useful differential checker asks: Can any supported configuration change the produced KV state while leaving the cache key unchanged? If yes, the contract is incomplete.

9. Production incident: fast but wrong answers after adapter rollout#

Imagine a multi-tenant support platform with 20 replicas and a shared KV tier. A new finance adapter is deployed alongside a support adapter. Both use the same base model and long common system prompt.

The local prefix caches correctly distinguish adapters, but the shared connector hashes only model name and tokens. The first finance request retrieves a support-adapter prefix. TTFT improves, so dashboards initially look healthy. A small evaluation later shows inconsistent policy responses.

Root cause: the connector's cache identity discarded adapter provenance.

Immediate containment:

  • Disable shared-cache reads for the affected adapter path.
  • Rotate or namespace the affected cache keys.
  • Keep local cache behavior only where adapter isolation is verified.
  • Recompute prefixes rather than trusting suspect entries.
  • Audit logs and access patterns for cross-tenant timing exposure.

Permanent correction:

  • Introduce a canonical provenance descriptor.
  • Pass it through both lookup and store interfaces.
  • Include tenant sharing domain and immutable adapter/model revisions.
  • Add differential compatibility tests to CI.
  • Canary the connector with shadow comparisons between cached and uncached outputs.
  • Monitor output-quality deltas as well as cache latency.

Do not simply flush the cache and declare the issue fixed. A flush removes bad entries temporarily; it does not repair a key function that will recreate the collision.

10. Metrics and monitoring#

Track these signals by model revision, adapter family, connector, cache tier, and privacy-safe sharing-domain class:

  • Prefix-cache hit rate and bytes reused.
  • Shared-cache hit rate separately from local hit rate.
  • Prefill tokens avoided and prefill GPU time saved.
  • Lookup latency and end-to-end TTFT.
  • Provenance mismatch rejections.
  • Unknown schema/version rejections.
  • Tensor metadata and checksum failures.
  • Cross-domain lookup attempts and authorization denials.
  • Cache warm-up after deployments and namespace rotations.
  • Cache storage growth by provenance cardinality.
  • Cached-versus-uncached output divergence on controlled shadow traffic.

Alert on any provenance mismatch or cross-domain reuse attempt. Those are correctness/security events, not ordinary cache misses.

A useful efficiency metric is:

LaTeX

A safe cache may have a lower hit rate because it correctly separates adapters, revisions, and tenants. Optimize within valid sharing domains rather than weakening the identity contract.

11. Trade-offs and design choices#

More provenance fields

  • Benefit: stronger correctness and isolation.
  • Cost: more namespaces, lower hit rate, increased metadata and retention.

Tenant-specific salts

  • Benefit: prevents cross-tenant reuse and reduces timing leakage.
  • Cost: repeated public prefixes may be recomputed for each tenant.
  • Practical approach: use explicit public/trusted sharing domains for approved content.

Immutable model digests

  • Benefit: safe coexistence during rollouts and adapter updates.
  • Cost: cold cache after a new revision.
  • Practical approach: warm the new namespace using representative, non-sensitive prompts.

Strict representation matching

  • Benefit: prevents dtype/layout/scale mismatches.
  • Cost: less flexibility across heterogeneous workers.
  • Practical approach: define tested conversion adapters rather than treating formats as interchangeable.

Shared cache versus local cache

  • Shared cache improves fleet-wide reuse but increases the importance of connector contracts and trust boundaries.
  • Local cache is simpler to isolate but loses reuse across replicas.
  • Use both only when the same provenance checks apply at every layer.

12. Implementation checklist#

Before enabling a shared KV tier:

  • [ ] Define computational provenance dimensions for every supported model family.
  • [ ] Define sharing domains from authenticated server-side tenant policy.
  • [ ] Use immutable base model and adapter digests.
  • [ ] Include KV dtype, quantization scales, layout, and serialization version.
  • [ ] Include parent-prefix context in block hashing.
  • [ ] Canonicalize descriptors identically across workers and languages.
  • [ ] Use one key builder for lookup, store, transfer, and restore.
  • [ ] Validate returned metadata and tensor structure before reuse.
  • [ ] Reject unknown descriptor/schema versions safely.
  • [ ] Add differential tests for every dimension that can affect KV state.
  • [ ] Test tenant isolation and timing side-channel controls.
  • [ ] Canary with cached-versus-uncached output comparisons.
  • [ ] Monitor hit rate, prefill savings, mismatch rejections, and quality.
  • [ ] Document namespace rotation and incident response.

13. Common mistakes#

  1. Keying only by prompt tokens and a friendly model name.
  2. Including adapter name but not immutable adapter revision or composition.
  3. Treating equal KV bytes as permission to share across tenants.
  4. Salting local cache keys but dropping the salt in the shared connector.
  5. Using different key derivation logic for cache writes and reads.
  6. Assuming a checksum validates semantic compatibility.
  7. Ignoring KV quantization scales, layout, or serialization changes.
  8. Treating cache flushes as a permanent fix for incomplete keys.
  9. Using user-supplied tenant IDs as authorization.
  10. Optimizing hit rate without measuring output correctness and isolation.

14. Interview-ready answer#

I would treat a shared KV cache as a correctness- and security-sensitive data plane, not just a key-value optimization. The cache key must bind the token prefix to immutable computational provenance—base model revision, adapter stack and revision, execution configuration, tokenizer, KV dtype/quantization/layout—and to a server-controlled sharing domain. Each block key should also include the parent-prefix hash because later KV state depends on the preceding context.

I would pass one canonical, versioned descriptor through the engine-to-connector boundary and use the same key builder for lookup, store, transfer, and restore. On a hit, I would validate the descriptor and tensor metadata before attaching the state. Tenant salts would be derived from authenticated policy, with explicit public sharing domains where reuse is approved. Finally, I would add differential tests that change one provenance dimension at a time, shadow cached and uncached outputs during rollout, and alert on any provenance mismatch or cross-domain access. The goal is not maximum hit rate; it is maximum reuse among requests that are both computationally compatible and authorized to share.

Related questions

Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents