Skip to main content
← CONCEPTS / AI-MACHINE-LEARNING-SYSTEMS
An end-to-end domain learning journey

Semantic & KV Prompt Caching
for Low-Latency LLM Inference.

Combining L1 exact-hash + L2 HNSW semantic response caching (with cross-encoder verification) and L3 RadixAttention KV-prefix caching eliminates redundant LLM prefill and decode compute, cutting hit latency to < 15 ms and TTFT by 80%+.
Start the journey7 sections· Last modified Nov 26, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Adding a cross-encoder + numeric parity gate stops dangerous semantic false positives while L3 KV reuse cuts TTFT by 80%+ on misses.

TL;DR30-second simplified summary
▾

An L1 Redis SHA-256 lookup resolves exact repeats in < 1 ms. On a miss, an ONNX MiniLM embedding + tenant-filtered HNSW search surfaces semantic matches (>= 0.94) verified by a cross-encoder and numeric parity gate.

True misses route to vLLM/SGLang RadixAttention workers to reuse precomputed KV blocks for shared system/RAG prefixes.

Full walkthrough · 7 stages
01
foundation

Stage 1: Response Caching vs. Prefix KV Caching.

Why this matters: Distinguish full-response semantic caching (skips entire LLM) from KV prompt caching (skips prefill on misses).

Semantic caching stores (query_embedding, prompt_metadata) -> final_completion and bypasses GPU inference completely on hits. KV prompt caching operates inside the inference engine, storing precomputed Key/Value attention tensors for shared prompt prefixes so novel user suffixes skip O(N^2) prefill computation.

FOUNDATION · TWO COMPLEMENTARY CACHES

Response Bypass (L1/L2) vs. Prefill Reuse (L3 KV Prefix)

Incoming LLMRequestIngressL1 Exact + L2SemanticResponse CacheL3 RadixAttentionKVPrefill CacheGPU Suffix DecodeLLM EngineOn miss, match prefix

1.100% Cost Avoidance: L1/L2 hits consume zero GPU FLOPs and return in 10-15 ms.

2.80%+ TTFT Reduction: L3 prefix KV reuse skips prefilling 8K-32K system/RAG tokens on cache misses.

L1/L2 response caches bypass GPU inference on repeated intents, while L3 KV prefix caches skip redundant prefill on novel queries.

02
foundation

Stage 2: L1 Exact Hash & Canonical Prompt Normalization.

Why this matters: Capture deterministic repeats in < 1 ms using canonicalized SHA-256 keys scoped by tenant and model version.

Before spending embedding FLOPs, an L1 Redis/Valkey lookup checks SHA256(tenant_id || model_id || temperature || canonical_messages). Normalizing whitespace and stripping volatile trace IDs boosts L1 hit rates without risking cross-tenant leaks or stale model-version responses.

FOUNDATION · L1 EXACT CACHE

Tenant-Scoped Canonical SHA-256 Lookup in < 1 ms

Prompt NormalizerCanonicalizerSHA-256 CompositeKeyKey BuilderRedis/Valkey L1StoreExact CacheDeterministic HitFast ReturnLookup exact key

1.Temperature Guard: High-temperature creative prompts (temp > 0.3) are typically bypassed or keyed separately to preserve diversity.

2.Tenant Isolation: Prefixing every key with tenant_id and RBAC policy hash prevents cross-tenant data leakage.

L1 exact-hash caching resolves identical prompts in < 1 ms while enforcing tenant, model-version, and temperature isolation.

03
intermediate

Stage 3: L2 HNSW Semantic Lookup & Embedding Vectorization.

Why this matters: Match paraphrased queries using compact bi-encoder embeddings and metadata-filtered HNSW search.

On an L1 miss, the router embeds the user query (plus intent context) using a fast CPU/ONNX bi-encoder (e.g., all-MiniLM-L6-v2 or BGE-small, ~4 ms) and queries a metadata-filtered HNSW index scoped to tenant_id and model_id. Candidates with cosine similarity >= 0.94 advance to verification.

INTERMEDIATE · L2 HNSW SEMANTIC

4 ms ONNX Embedding + Tenant-Filtered HNSW Candidate Search

ONNX Bi-Encoder(MiniLM)VectorizerTenant + ModelFilterIsolation GateHNSW Vector IndexANN SearchThreshold Gate (cos>= 0.94)Candidate PassSearch tenant subgraph

1.Pre-Filtered HNSW: Filtering by tenant_id inside HNSW traversal prevents empty results when another tenant dominates Top-K.

2.384-D Speed: Compact 384-D embeddings keep ONNX inference under 5 ms on CPU and shrink HNSW RAM by 4x vs 1536-D.

L2 semantic search embeds queries in ~4 ms and runs tenant-filtered HNSW ANN lookup for candidates >= 0.94 cosine similarity.

04
intermediate

Stage 4: Cross-Encoder False-Positive Guard.

Why this matters: Prevent dangerous semantic cache collisions on negated, numeric, or entity-swapped queries.

Bi-encoder cosine similarity frequently scores 'Transfer $100 to Alice' and 'Transfer $1000 to Bob' (or 'enable MFA' vs. 'disable MFA') above 0.94. Passing Top-1/Top-3 HNSW hits through a fast cross-encoder / entity-diff gate (e.g., 5 ms) catches polarity flips, number mismatches, and entity swaps before serving.

INTERMEDIATE · FALSE-POSITIVE GUARD

Entity/Numeric Parity + Cross-Encoder Equivalence Verification

HNSW Candidate (cos>= 0.94)CandidateNumeric & EntityDiffExact GuardTiny Cross-Encoder(~5 ms)Semantic GateVerified Cache Hit(< 15 ms)Verified OutputScore full pair attention

1.Zero Polarity Bugs: Full cross-attention catches single-word negations ('not', 'disable', 'cancel') that pooling erases.

2.Numeric Invariant: Exact regex parity on numbers, dates, and UUIDs guarantees no wrong-amount cache hits.

Numeric/entity parity checks and a 5 ms cross-encoder gate block false-positive semantic hits on negations or changed parameters.

05
intermediate

Stage 5: L3 RadixAttention KV-Cache Prefix Trees.

Why this matters: Reuse precomputed Key/Value attention tensors across requests sharing system prompts, tools, or RAG documents.

When L1/L2 miss, L3 prefix caching inside vLLM/SGLang organizes token sequences into a compressed Radix Tree whose edges point to paged KV-cache blocks in GPU HBM and host DRAM. Matching a 4,096-token system+RAG prefix skips prefilling those 4,096 tokens, computing attention only over the new 64-token user question.

INTERMEDIATE · L3 KV PREFIX CACHE

RadixAttention Prefix Tree Mapping Token Chains to Paged KV Blocks

Tokenized Prompt[4160 tok]Token StreamRadix Tree LongestMatchPrefix IndexPaged KV Blocks(HBM/DRAM)Tensor Store64-Token SuffixPrefillGPU ComputePin matched KV blocks

1.HBM -> DRAM Offload: Cold KV blocks are evicted from GPU HBM to host DRAM (LMCache/Mooncake) before deletion, expanding prefix capacity 10x.

2.LRU Eviction: Leaf nodes in the radix tree with refcount == 0 are evicted first under HBM pressure.

RadixAttention matches shared prompt prefixes in O(prefix_len) to reuse paged KV blocks and slash TTFT by 80%+.

06
advanced

Stage 6: Prefix-Aware Consistent Hash Routing.

Why this matters: Route cache misses to the specific GPU replica that already holds the warm KV prefix blocks in HBM.

If round-robin load balancing sprays requests for the same 8K-token agent system prompt across 32 GPU workers, L3 KV cache hit rates drop to 1/32 (3%). Prefix-aware consistent hashing hashes the first K tokens (e.g., first 512 tokens) to pick primary/secondary workers, bounded by a load-skew cap so hot prefixes spill cleanly.

ADVANCED · PREFIX-AWARE ROUTING

Bounded-Load Consistent Hashing for Distributed KV Locality

Extract First 512TokensPrefix KeyConsistent Hash RingLocality RouterBounded-Load Check(1.25x)Skew GuardWarm KV GPU ReplicaTarget WorkerCheck target queue depth

1.28x Higher KV Hit Rate: Prefix affinity turns a 3% random-routing hit rate into 85%+ across a 32-GPU fleet.

2.Bounded-Load Spillover: Capping load at 1.25x cluster average ensures a viral tenant prompt spills to a secondary replica instead of queuing.

Bounded-load consistent hashing on the first 512 prompt tokens preserves L3 KV cache locality without creating hot GPU shards.

07
advanced

Stage 7: Cache Invalidation, TTLs & Write-Back Consistency.

Why this matters: Prevent stale RAG/tool answers and cache poisoning using model-version epochs, corpus-version tags, and async write-back.

Semantic caches must never return stale answers after a knowledge-base update, model weights upgrade, or RBAC permission change. Every cached entry is tagged with (model_epoch, kb_version, policy_epoch, ttl_sec) and written asynchronously after stream completion—never caching error responses, empty outputs, or PII-bearing user-specific replies.

ADVANCED · INVALIDATION & SAFETY

Epoch-Based Invalidation & Safe Async Write-Back

Completed LLMStreamWrite CandidatePII / Error /Volatility GateWrite FilterEpoch + TTL TaggingVersion GuardAsync Kafka/RedisWrite-BackCache CommitAttach epoch & TTL

1.Instant Epoch Invalidation: Bumping kb_version or model_epoch invalidates stale entries in O(1) without scanning Redis keys.

2.Zero Poisoned Entries: Never cache truncated responses (finish_reason='length'), 5xx fallbacks, or real-time 'what time is it' queries.

Epoch versioning, TTLs, and async PII/error-filtered write-back keep semantic caches fresh and safe without slowing responses.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is a cross-encoder + numeric/entity parity gate needed on top of HNSW cosine similarity (>= 0.94) in an L2 semantic cache?

Recommended Learning Flow