Bounding Cache Affinity in a Self-Hosted Inference Fleet
Route self-hosted LLM requests with bounded queue delay, tenant isolation, worker epochs, safe admission, and trustworthy cache telemetry.
On this page
A replica can be the best place to reuse a prompt and a poor place to accept the next request.
That tension is the starting point for a cache-aware inference router. I would give cache affinity a limited opportunity to influence placement, then require the destination to admit the work. A remembered cache location should never become a permanent claim on a worker.
Consider a hypothetical release-readiness assistant. It reviews a versioned release manifest, reads deployment evidence through tools, and produces a short decision for an engineer. Several turns reuse the same instructions and manifest. The organization operates its own model-serving fleet, and each tenant has a separate data boundary.
The design below concerns replicas serving the same approved model configuration. Choosing a model for a workflow is an earlier decision; building a stable prompt supplies reusable input. Here the question is how to place that input without allowing cache preference to defeat capacity policy.
Make placement a revocable decision
A useful placement contract separates authority, estimates, and final admission:
| Input | Responsible component | Meaning |
|---|---|---|
| Approved serving pool | Authentication and deployment policy | Where this request may execute |
| Compatible serving revision | Model registry | Which workers implement the requested configuration |
| Predicted queue delay | Load adapter | An estimate of waiting before service |
| Reusable prefix length | Cache directory | Advisory evidence about this particular input |
| Admission response | Destination scheduler | Whether the worker accepts the work now |
Only approved, compatible destinations enter the placement calculation. A large cache overlap cannot make another region or tenant pool eligible.
NVIDIA Dynamo's routing documentation provides one concrete implementation reference: its selector uses cache overlap together with projected active work. It also separates selecting workers from transferring KV state. Those are useful architectural boundaries, even when the serving stack differs.
The examples here are custom policy sketches, not replacement implementations of Dynamo or an engine scheduler. Existing serving gateways are worth evaluating before building a router. For example, SGLang Model Gateway exposes a cache-aware policy alongside other balancing policies. Check the exact behavior and supported topology in the version deployed.
Choose cache scope before looking for matches
The cache directory needs a notion of compatibility stronger than a human-readable model name.
I would namespace directory entries by the serving configuration that determines reusable state: model artifact revision, tokenizer and chat-template revision, adapter identity where applicable, and the engine's cache-format compatibility. The trusted gateway also supplies a cache-sharing scope derived from the authenticated principal and policy.
An index lookup then compares the effective model input, including relevant multimodal identity. vLLM's prefix-cache design illustrates why: block identity incorporates preceding context, token IDs, and extra inputs such as adapters and multimodal hashes. Its documented full-block behavior also means a shared token count need not equal the reusable count. Other architectures and engine versions can have different reuse boundaries.
A whole-transcript hash is insufficient for discovering a growing shared prefix. When a new turn extends the transcript, the complete hash changes. Use the engine's compatible prefix representation, a prefix index, or a deliberately bounded approximation. Do not silently substitute semantic similarity for exact reusable state.
Keep three identifiers distinct: a cache namespace, a content-derived prefix identity, and an ephemeral lookup ID that correlates one directory query with its response. The lookup ID in the TypeScript example is only that correlation value.
Privacy also changes the namespace. vLLM's security guide documents timing inference through shared prefix caches and recommends secret cache salts scoped to the required isolation boundary. The gateway should supply and protect such controls; callers should not choose another tenant's scope or salt.
A router namespace alone does not isolate the engine's cache. Enforce the sharing policy in the backend too. Opaque fingerprints can still expose correlations, so restrict directory access and avoid prompt fingerprints, tenant secrets, and raw text in ordinary metric labels.
Give locality a queue budget
A simple policy can make the affinity trade-off explicit:
- Remove destinations that cannot accept this request or whose load observations are too old.
- Find the smallest predicted queue delay among the remaining destinations.
- Keep only destinations within a configured delay allowance of that minimum, and within an absolute queue limit.
- Prefer the largest credible prefix reuse inside that shortlist; break ties using queue delay.
The allowance is a product and workload policy. It is not a universal constant or a guarantee of actual waiting time.
For illustration, suppose a cold worker has a predicted queue delay of 12 ms and a warm worker has 37 ms. An allowance of 30 ms permits the warm worker to compete. If that worker instead predicts an 80 ms queue delay, it falls outside the shortlist. These are invented policy inputs, not measured fleet results.
For a short prompt, I would use zero allowance or require evidence that meaningful prefill work can be avoided. A class with substantial shared input might justify a larger allowance after replay and canary measurements. This heuristic bounds extra *predicted queue delay*; it does not minimize total latency mathematically.
type CacheHint = { lookupId: string; scope: string; epoch: string; reusedTokens: number; ageMs: number; synchronized: boolean;};type Replica = { id: string; epoch: string; revision: string; ready: boolean; admissible: boolean; queueMs: number; loadAgeMs: number; hint?: CacheHint;};type PlacementRequest = { lookupId: string; scope: string; revision: string; inputTokens: number;};type PlacementPolicy = { maxQueueMs: number; affinitySlackMs: number; maxLoadAgeMs: number; maxHintAgeMs: number;};function chooseReplica( request: PlacementRequest, replicas: Replica[], policy: PlacementPolicy,): { id: string; expectedReuse: number; extraQueueMs: number } { const nonnegative = (n: number) => Number.isFinite(n) && n >= 0; if (!Number.isSafeInteger(request.inputTokens) || request.inputTokens < 1 || !request.lookupId || !request.scope || !request.revision || !Object.values(policy).every(nonnegative)) { throw new Error("invalid-placement-input"); } if (new Set(replicas.map(r => r.id)).size !== replicas.length) { throw new Error("duplicate-replica"); } // Authorization and region filtering happen before this function. const eligible = replicas.filter(r => r.ready && r.admissible && r.revision === request.revision && nonnegative(r.queueMs) && r.queueMs <= policy.maxQueueMs && nonnegative(r.loadAgeMs) && r.loadAgeMs <= policy.maxLoadAgeMs ); if (!eligible.length) throw new Error("no-admissible-replica"); const minimumQueue = Math.min(...eligible.map(r => r.queueMs)); const shortlist = eligible.filter(r => r.queueMs - minimumQueue <= policy.affinitySlackMs ); const ranked = shortlist.map(r => { const h = r.hint; const usable = h && h.synchronized && h.lookupId === request.lookupId && h.scope === request.scope && h.epoch === r.epoch && nonnegative(h.ageMs) && h.ageMs <= policy.maxHintAgeMs && Number.isSafeInteger(h.reusedTokens) && h.reusedTokens >= 0 && h.reusedTokens <= request.inputTokens; return { r, reuse: usable ? h.reusedTokens : 0 }; }).sort((a, b) => b.reuse - a.reuse || a.r.queueMs - b.r.queueMs || a.r.id.localeCompare(b.r.id) ); const selected = ranked[0]; return { id: selected.r.id, expectedReuse: selected.reuse, extraQueueMs: selected.r.queueMs - minimumQueue, };}The transport layer must validate the complete input schema before constructing these typed values. Load and cache hints come from trusted adapters, not client-provided claims. admissible reflects the current capacity policy, including relevant prefill, decode, and memory constraints; a request-count-only signal can hide very different workloads.
A hint is usable only if it belongs to this lookup, sharing scope, and worker incarnation, and the directory view is synchronized and fresh. When hints are absent or unusable, every reuse score becomes zero and queue delay decides. Stale load is treated differently: this sketch excludes the destination. If no candidate remains, apply the service's bounded deferral or rejection policy rather than dispatching blindly.
The code intentionally does not implement a distributed reservation or deadline enforcement. Queue predictions can be wrong. A production adapter should include locally dispatched work that engine telemetry has not acknowledged yet, and calibrate queue estimates against observed waits.
Keep cache knowledge behind an epoch and a cursor
A directory built from worker events needs a recovery contract. A pod name or network address is not enough: a restarted process may have the same address and an empty cache.
Associate cache knowledge with a worker incarnation obtained from trusted discovery. Within that incarnation, apply a source-defined ordered event stream. A duplicate can be ignored. A gap means the directory no longer knows which entries were removed, so positive cache evidence should become unusable until recovery.
The following reducer models that contract. Block keys are opaque, namespace-scoped identities supplied by an adapter; this set is not itself a longest-prefix matcher.
from dataclasses import dataclass, field@dataclassclass CacheView: epoch: str sequence: int = -1 usable: bool = False blocks: set[str] = field(default_factory=set) @staticmethod def _check_sequence(sequence: int) -> None: if type(sequence) is not int or sequence < 0: raise ValueError("sequence must be a nonnegative integer") def snapshot(self, epoch: str, sequence: int, blocks: set[str]) -> bool: self._check_sequence(sequence) if (epoch != self.epoch or sequence < self.sequence or (self.usable and sequence == self.sequence)): return False # The adapter supplies a complete view at this sequence. copied = set(blocks) self.blocks = copied self.sequence = sequence self.usable = True return True def delta( self, epoch: str, sequence: int, added: set[str], removed: set[str], ) -> bool: self._check_sequence(sequence) if epoch != self.epoch or sequence <= self.sequence: return False continuous = self.usable and sequence == self.sequence + 1 self.sequence = sequence if not continuous: self.usable = False self.blocks.clear() return False self.blocks.difference_update(removed) self.blocks.update(added) return TrueAn adapter must serialize snapshot installation and delta application, define the snapshot's exact cursor, and retain or replay subsequent events. A snapshot older than the highest observed sequence cannot repair the view. After discovery reports a new incarnation, create a new CacheView; late events from the old process cannot populate it.
These cursor and snapshot fields describe a required adapter contract, not a claim that every engine exports this API. A sequence assigned only after events arrive cannot detect events lost upstream. If the event source cannot establish continuity, use its supported recovery mechanism or fall back to conservative, explicitly approximate hints.
Even a synchronized event view is not a cache reservation. A worker may evict blocks between lookup and execution. Track freshness independently, invalidate evidence on observer failure, and bound directory memory. Dropping an index entry should reduce optimization opportunities without affecting the request's input.
Close the race at admission
Two routers can choose the same warm destination before either sees the other's dispatch. Fresh telemetry alone cannot prevent this.
The destination scheduler must enforce its own resource limits. Depending on the serving platform, the gateway may obtain a short-lived admission reservation or send directly to an endpoint that can refuse excess work. Account for outstanding dispatches and release reservations on completion, cancellation, and lease expiry.
If admission fails, refresh the relevant observations and allow only a bounded re-selection within the request deadline. Do not bounce indefinitely between warm workers. Backpressure and tenant concurrency limits still apply before cache preference.
A stale hint should cause extra computation, not missing input. For a stateless inference request, send the complete required context so the engine can recompute on a miss. If an API supports server-held conversation state, its state availability and authorization contract needs separate treatment; a prefix hint is not a substitute for that contract.
After streaming begins, transparently restarting generation can duplicate visible output or produce a different continuation. Preserve attempt identities and make restart behavior explicit. Any subsequent tool effects still need their own idempotency boundary.

*Flow: authorized request and current load select a compatible worker; cache locality influences placement only within the queue budget. The destination must still admit the full request.*
The directory influences placement. The admission boundary decides whether that placement can proceed. Execution observations then reveal whether the predicted reuse materialized.
Plan fleet changes around cold capacity
Scaling creates capacity before it necessarily creates useful cache locality. New workers can remain underused if a router always prefers established holders. Conversely, moving all traffic immediately can create a burst of repeated prefill.
I would reserve a controlled share of suitable traffic for cold capacity and watch actual admission and latency. Replicating a popular prefix across more workers can be worthwhile when contention outweighs the additional memory and warm-up work. That is a measured capacity choice, not a cache-hit target.
Rollouts need two distinct transitions. A new serving revision starts a separate compatibility namespace. A new process within the same revision starts a separate incarnation. Draining removes a worker from new placement even if it still advertises valuable cached state.
Keep a cold-path operating plan: lower admitted concurrency, defer background work, shorten optional context only through an evaluated application policy, or reject before queues become unbounded. Do not assume a warm cache will survive a regional recovery or a large rollout.
Remote cache tiers and disaggregated serving add transfer costs and compatibility requirements. A remote hit may need loading or copying before it helps. The selection policy should distinguish local reuse, transferable state, and unavailable state rather than treating them as equivalent.
Measure the placement decision and the serving outcome separately
Cache reuse saves repeated input processing. vLLM's feature documentation explicitly limits APC's direct benefit to prefill rather than generating new output tokens. A workload dominated by long generation may therefore see little end-to-end benefit from a higher reuse fraction.
I would instrument three views:
| View | Measurements | What it tests |
|---|---|---|
| Placement | Candidate count, selected queue estimate, extra predicted delay, hint age, hint source, rejection reason | Whether policy followed its limits |
| Serving | Actual queue duration, time to first token, input tokens actually reused, remaining prefill work, output duration | Whether the estimate helped execution |
| Fleet and product | Admission failures, deadline misses, completion quality, worker imbalance, successful work per GPU-hour | Whether the system improved |
These are proposed measurement concepts, not promised engine metric names. Map them through versioned adapters and keep router estimates separate from backend observations.
For token-weighted reuse, divide the sum of confirmed reused input tokens by the sum of input tokens over attempts with valid counters. Show telemetry coverage beside that ratio. Unknown counters are not zero, and missing observations must not disappear from the coverage denominator. Include failed and retried attempts in resource accounting.
Track predicted reuse exceeding confirmed reuse as an optimism signal. Segment by hint source, incarnation changes, prompt-size class, and deployment revision. A directory with frequent optimistic hints needs investigation even if its own lookup-success rate is high.
Measure actual queue delay against its prediction as well. A strict allowance over badly calibrated estimates is weak protection. Trace high-cardinality attempt and worker identities with access controls; keep aggregate metric dimensions bounded. The AI telemetry data boundary applies to these traces too.
Validate under contention and broken observations
A useful test matrix exercises decisions that look attractive to the cache policy but should be refused:
- A worker restarts behind the same address; old hints must lose their value.
- A removal event is missing; the directory must stop presenting synchronized evidence until repaired.
- A hot prefix attracts many concurrent requests; worker admission and per-tenant limits must hold.
- The directory becomes unreachable; inference should follow the documented load-only fallback if fresh load remains available.
- Both load and directory observations are stale; the gateway must defer or reject according to policy.
- An adapter, template, or isolation scope changes; incompatible entries must not be reused as matching evidence.
- Cancellation or admission refusal occurs; outstanding capacity accounting must eventually clear.
For performance evaluation, replay a representative arrival process, prompt-length distribution, shared-prefix distribution, output lengths, and tenant mix. Compare the existing load policy against affinity variants on the same model and hardware. Separate cold starts from steady state, account for cache contamination between variants, and retain failures and timeouts in the results.
Shadow placement can expose decisions and skew without executing a second inference request. It cannot establish the latency of the unchosen worker. Use controlled serving experiments for that question, then canary with rollback thresholds tied to deadlines, admission failures, fairness, and cost per completed task.
The TypeScript example was executed against eligibility, stale-hint, scope, restart, and queue-bound checks, including 500 generated candidate pools. The Python reducer passed five unit tests covering ordering, snapshot recovery, incarnation changes, missing baselines, and invalid cursors. These checks validate the sketches' logic; no GPU fleet benchmark, serving-engine integration, or throughput improvement is claimed.
Keep affinity subordinate to the service contract
For small prompts, infrequent reuse, or modest traffic, an existing load policy may already meet the service objectives. A cache directory adds another observer, recovery path, and operational dependency. Add it when repeated prefill is a measured constraint.
For a fleet with substantial reusable context, begin with an explicit scope, compatible identity, bounded affinity allowance, and destination admission. Then make the estimates accountable to serving observations. That produces a placement policy operators can disable or tune without changing the application's correctness contract.
Primary references
- vLLM: Automatic Prefix Caching, feature behavior and limits.
- vLLM: Prefix-cache implementation design.
- vLLM: Security and cache salting.
- NVIDIA Dynamo: KV-aware routing.
- SGLang: Model Gateway.
Technical documentation checked on October 22, 2026. Engine APIs, cache compatibility, and telemetry fields should be checked against the pinned deployment version.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article