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

Dual-Tier Radix Prefix &
HNSW Semantic Prompt Caching.

Exact string caching misses 85%+ of paraphrased LLM queries, while unguarded semantic vector caching risks serving inverted or cross-tenant answers.
Start the journey5 sections· Last modified Nov 26, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When building an LLM semantic cache, gate vector hits with cosine threshold tau=0.08 and exact entity/negation matching to prevent drift.

TL;DR30-second simplified summary
▾

L1 matches exact 256-token prefixes via XXH3-64. L2 encodes user turns with ONNX INT8 and searches tenant-filtered SQ8 HNSW in <6 ms, enforcing slot parity before serving cached RocksDB payloads.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Transformer KV-Cache & Prefill Physics
Prefill attention scales quadratically with prompt length; reusing shared system-prompt KV blocks avoids redundant GPU FLOPs.
Cosine Similarity & HNSW Graphs
Normalized dense embeddings measure semantic proximity via d(u, v) = 1 - (u · v), searchable in O(log N) via HNSW.
Full walkthrough · 5 stages
01
L4 · FUNDAMENTALS

P · Problem & Why Exact String Caching Breaks on Natural Language.

In traditional web APIs, URLs are canonical keys. In LLM applications, two users asking 'Summarize Q3 churn drivers' and 'Give me the main reasons customers churned in Q3' have completely different SHA-256 hashes, resulting in a 0% exact-cache hit rate.

Conversely, dropping prompts blindly into a vector database with a loose threshold (tau = 0.20) causes catastrophic false positives: 'How do I delete my prod cluster?' can match 'How do I back up my prod cluster?'.

HIT RATE VS. DRIFT

Exact String Hash vs. Calibrated Dual-Tier Cache

Before · Naive Exact-Only Cache
  • 10–12% hit rate on paraphrases
  • 88% requests hit GPU origin
  • No partial KV-prefix reuse
After · Dual-Tier L1 Radix + L2 HNSW
  • >25–35% combined hit rate
  • <15 ms p99 cache evaluation
  • <0.5% semantic drift via slot guard
02
L4 · FUNDAMENTALS

R · Representation: Radix Prefix Trees & Normalized Vector Geometry.

Every LLM prompt has two parts: a rigid prefix (system instructions, tool schemas, few-shot examples) and a fluid suffix (the user's natural-language question).

L1 stores 256-token prefix hashes in an in-memory Radix Trie keyed by HMAC(tenant_id, model_epoch). L2 embeds only the normalized user turn into a unit-normalized 384-d INT8 vector.

DUAL-TIER TOPOLOGY

Prompt Splitting Across L1 Radix Trie and L2 HNSW

Edge NormalizerCanonicalize + HMAC…L1 Radix TrieXXH3 Prefix (<1ms)ONNX INT8384-d Embed (4ms)SQ8 HNSWCosine Gate (6ms)256-tok blocksL1 MissUnit vec
03
L5 · APPLIED DESIGN

I · Invariant: Cosine Calibration Curve & Entity/Negation Slot Guard.

Embedding models capture broad topic similarity, not logical polarity. 'Enable audit logging' and 'Disable audit logging' often have cosine distance d = 0.06.

We enforce two invariants before serving an L2 hit: (1) d(u, v) < tau = 0.08, and (2) exact set equality on extracted numbers, dates, currency amounts, and negation tokens.

SEMANTIC GATE TRACE

Cosine Threshold + Lexical Slot Verification

QueryHNSW IndexSlot Guard1. ANN top-1 (d = 0.06)2. Candidate: 'Disable MFA'3. Mismatch ('Enable' !='Disable') -> MISS
04
L5 · APPLIED DESIGN

M · Mechanics at Scale: Tenant Isolation & Lazy Epoch Invalidation.

Every cache entry is prefixed with HMAC-SHA256(master_key, tenant_id) and indexed in HNSW with a Roaring Bitmap tenant filter so Tenant A can never retrieve Tenant B's vectors.

When model weights or system prompts change, bumping model_epoch in etcd/Redis invalidates stale entries in O(1) time on read without flushing 100M keys.

EPOCH LIFECYCLE

O(1) Lazy Model-Epoch Invalidation State Machine

Deploy v4.2Lazy miss + SST mergeEpoch Match (v4.2)Epoch Mismatch(v4.1)RocksDB CompactionDrop
05
L6 · SCALE & TRADE-OFFS

E · Edge Cases, Assumptions & Glossary.

Assumptions & Limitations: Semantic caching assumes deterministic or low-temperature (T <= 0.3) queries where approximate equivalence is acceptable. Never enable L2 semantic caching for creative writing, high-temperature brainstorming, or real-time volatile data (stock prices, live inventory)—route those via TTL = 0s bypass.

Decision Check: If cache evaluation p99 exceeds 12 ms or async shadow drift exceeds 1.5%, fail open directly to the Foundation Model Origin.

WHEN TO USE

Semantic Caching Fit by Workload Profile

Decision Exercise · Make the Call

Your L2 cache hit rate jumps from 26% to 44% after an embedding model update, and users report wrong answers on date-sensitive queries. What is the fastest safe mitigation?

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

Why must an L2 semantic cache pair cosine distance thresholding with an Entity/Negation Slot Guard?

Recommended Learning Flow