Skip to main content
Anuraag Mishra LogoAnuraag Mishra
← Back to Selected Systems
Flagship AI System · Regulated Production Design
AI Reliability & Retrieval

Semantic Cache & Reliability Layer

Precision-first reuse of previous answers and retrieval results

Semantic CachingHybrid RetrievalQuery UnderstandingNLI
RoleSenior AI/ML Engineer
DomainEnterprise AI / Fintech
StatusProduction Design
ContextEnterprise AI Systems
EXECUTIVE BRIEF :: AT A GLANCE
01.PROBLEM

Repeated and semantically similar requests create unnecessary retrieval and model work, but reusing the wrong answer can be worse than doing the work again.

02.CORE INSIGHT

Semantic similarity proposes candidates. Entity, time, scope, and freshness constraints determine whether reuse is safe.

03.STRATEGY

Check deterministic exact reuse first, then retrieve semantically similar prior results and progressively filter them before deciding how — or whether — they can be reused.

UNCONSTRAINED RETRIEVAL RISKS

Why Similarity Alone Is Unsafe

Nearest-neighbor semantic search measures natural language proximity, but has zero inherent comprehension of corporate boundaries, dates, or freshness:

01. ENTITY MISMATCHCross-Entity Risk

Entity Confusion

Identical semantic phrasing (e.g., 'What was Q3 EBITDA margin?') refers to completely different organizations or tickers. Semantic search alone cannot distinguish company ownership.

02. TEMPORAL DRIFTPeriod Violation

Time & Period Drift

A perfectly accurate historical answer for FY2023 is factually incorrect when the user requests FY2024 results, despite 98% vector semantic similarity between the two query strings.

03. SCOPE LEAKAGEAuthorization Risk

Scope & Boundary Failure

Related intelligence from an external or confidential folder cannot be reused in an unprivileged or public session. Similarity ignores tenant, folder, and document access boundaries.

04. STALENESSStale Cache Risk

Document Invalidation

When an underlying financial report or policy document is revised, previously cached answers become stale. Vector proximity remains high even when underlying data changes.

Core Reliability Rule:Semantic similarity proposes candidates. Structured constraints decide whether reuse is acceptable.
REUSE GOVERNANCE ARCHITECTURE

Semantic Reuse Safety Funnel

A semantic cache cannot rely solely on embedding proximity. Candidate prior results pass through a progressive filtering funnel that eliminates mismatched entities, periods, and stale data:

STAGE 01Candidate Pool

ALL PRIOR RESULTS

Historical queries, retrieved evidence passages & cached answer artifacts

STAGE 02Hybrid Recall

LEXICAL + SEMANTIC CANDIDATES

OpenSearch BM25 keyword matching combined with dense vector retrieval

STAGE 03Hard Boundary Gate

ENTITY COMPATIBLE

Strict entity resolution; eliminates cross-company and ticker mismatch

STAGE 04Temporal Filter

TIME & PERIOD COMPATIBLE

Verifies fiscal year, quarter, and reporting period boundaries

STAGE 05Scope Check

SCOPE COMPATIBLE

Enforces collection, folder, and tenant authorization constraints

STAGE 06TTL & Freshness

FRESH ENOUGH

Invalidates stale entries against document updates and market clock

STAGE 07Verified Safe

CONFIDENT REUSE CANDIDATES

High-confidence intelligence ready for direct answer, context, or subtask reuse

Design Philosophy:Every stage intentionally sacrifices recall to increase reuse safety.
SYSTEM ARCHITECTURE

Two-Tier Lookup & Query Normalization

The architecture establishes an exact O(1) hash check upfront, cascading into OpenSearch hybrid retrieval and multi-constraint evaluation when deterministic misses occur:

QUERY TRANSFORMATION PIPELINE

Multi-Dimensional Query Normalization

A raw incoming question is decomposed into multiple parallel representations before any lookup or retrieval occurs:

INPUT: RAW USER QUERY STRINGUnprocessed Natural Language
↓ NORMALIZE / EXTRACT / STRUCTURE ↓
01. Canonical Exact Key

Deterministic normalized hash (lowercased, entity-canonicalized, whitespace-stripped) for O(1) exact cache matching.

02. Lexical Representation (BM25)

Tokenized keywords, extracted financial identifiers, acronyms, and product terms for exact term matching in OpenSearch.

03. Semantic Representation (Dense Vector)

Dense semantic embedding representing high-level user intent and conceptual inquiry for approximate nearest neighbor retrieval.

04. Structured Hard Constraints

Extracted named entities (company, ticker), temporal intervals (FY/quarter, calendar dates), metric types, and scope boundaries.

Extracted Constraints:Entities · Reporting Periods · Exact Metrics · Intent Type · Access Scopes
TWO-TIER LOOKUP STRATEGY

Exact Canonical vs Semantic Retrieval Paths

Neither exact hashing nor semantic similarity is sufficient on its own. The system layers them sequentially to balance instant execution speed with linguistic flexibility.

TIER 1 :: EXACT CANONICAL KEYZero-Cost Fast Path
Strengths:
  • Ultra-low latency memory lookup
  • Completely deterministic and 100% precision
  • Zero model inference compute cost
Inherent Weakness:

Brittle under natural-language phrasing variations and minor syntactic reorderings.

Execution: Instant O(1) hash check
TIER 2 :: HYBRID SEMANTIC RETRIEVALFlexible Recall
Strengths:
  • Recognizes complex conceptual paraphrases
  • Discovers related prior intelligence across sessions
  • Powers subtask and partial-answer reuse
Engineering Challenge:

Produces probabilistic candidates that require rigorous multi-constraint validation.

Execution: OpenSearch BM25 + Vector KNN
Architectural Routing Rule: The system checks exact canonical reuse first; hybrid semantic retrieval is invoked only after the deterministic path misses.
ARCHITECTURE :: PRECISION-FIRST REUSE PIPELINE
EXACT FAST PATH + FILTERED SEMANTIC REUSE
NEW INCOMING QUERYQUERY UNDERSTANDING & CANONICAL KEYnormalize syntax · extract entity / dates · hash exact keyTIER 1 :: EXACT CANONICAL LOOKUPhit → instant zero-model return | miss → tier 2EXACT HITTIER 2 :: HYBRID RETRIEVAL (OPENSEARCH)BM25 lexical overlap + dense vector semantic similarityPROGRESSIVE CONSTRAINT FILTERINGentity match · fiscal period · scope tenant · freshness clock1. DIRECT REUSEhigh-confidence verified answer2. SUPPORTING CONTEXTpassed into generation context3. SUBTASK / FRESHreused in agent or fresh call
Exact Fast PathZero Inference Overhead
Entity SafetyZero Cross-Company Reuse
Temporal GuardStale Period Invalidation
Multi-Mode ReuseAnswer · Context · Subtask
SYSTEM DESIGN PRINCIPLES

Key Engineering Decisions

01

Entity Correctness Is a Hard Constraint

In enterprise and financial systems, returning the right metric for the wrong company is a catastrophic failure. Semantic similarity alone cannot guarantee entity boundaries.

The first design rule makes entity resolution a hard gate: if the requested entity does not match the candidate’s entity metadata exactly, reuse is rejected immediately — regardless of how high the vector similarity score may be.

02

Freshness Is Part of Correctness

A semantically identical question asked today may require a completely different answer if underlying financial filings, market prices, or enterprise policies have changed.

The second design rule integrates document modification timestamps and TTL invalidation clocks directly into candidate acceptance. Stale intelligence is purged before prompt assembly.

03

Reuse Has More Than One Mode

A prior result does not have to be an exact answer replacement to provide immense value. Reusable artifacts can act as direct answers, supporting evidence context, or subtask accelerators.

VALIDATION TRADE-OFF ARCHITECTURE

Selective NLI Validation vs Fast Path

Natural Language Inference (NLI) provides rigorous semantic entailment and contradiction detection, but introduces neural inference latency. The system balances deep checking against fast metadata filtering:

DEFAULT FAST PATHLow Latency

Handles the vast majority of production requests through deterministic metadata gating and calibrated embedding thresholds.

Core Mechanisms:
  • OpenSearch BM25 + dense vector hybrid recall
  • Hard entity and temporal metadata filters
  • Fast scalar score and margin separation checks
Latency profile: Sub-millisecond to low millisecond
DEEP NLI VALIDATION (SELECTIVE)High Assurance

Invoked selectively on high-stakes, ambiguous queries to verify that the cached answer logically entails the new query premise without contradiction.

Advantages:
  • Deep cross-encoder semantic support checking
  • Explicit contradiction and entailment scoring
Engineering Cost:

Cross-encoder inference adds latency; unsuitable as an unconditional fast path.

Application: Targeted verification for ambiguous edge cases
Architectural Stance: Stronger validation is valuable only where its quality benefit justifies its latency cost. NLI is an escalating safeguard, not a universal bottleneck.
FLEXIBLE REUSE POLICY

Four Operational Reuse Modes

A matched candidate is not simply an all-or-nothing cache hit. The system decides the exact mechanism by which prior intelligence serves the active request:

01. DIRECT ANSWER

High-Confidence Full Reuse

Returned directly to the user with zero model invocation when entity, period, intent, and freshness match completely.

02. SUPPORTING CONTEXT

Relevant but Incomplete

Passed into the active generation prompt as authoritative context passages, reducing retrieval workload for the LLM.

03. SUBTASK ARTIFACT

Reusable Component Output

Supplied to an orchestrator agent solving a multi-step query, satisfying one subtask without re-executing its tool call.

04. NO REUSE (REJECT)

Unsafe / Stale / Ambiguous

Rejected due to entity mismatch, stale document version, or boundary violation; triggers fresh grounded pipeline.

Architectural Significance: The system evolved beyond a naive key-value response store into an intelligent multi-role retrieval accelerant.
AGENTIC ORCHESTRATION REUSE

Subtask-Level Reuse in Multi-Step Workflows

In complex agentic reasoning pipelines, reuse is not limited to answering the top-level user prompt in one shot. The cache satisfies intermediate subproblems without re-executing tool calls:

COMPLEX AGENT INQUIRYe.g., "Compare 2024 operating margins between Company X and Company Y"
↓ PLANNER DECOMPOSITION ↓
Subtask A

Extract Company X FY24 Margin

✓ CACHE REUSE
Subtask B

Fetch Company Y Fresh Filing

⚡ FRESH RETRIEVAL
Subtask C

Historical Peer Average

✓ CACHE REUSE
↓ REUSED ARTIFACTS + FRESH RETRIEVAL SYNTHESIS ↓
FINAL SYNTHESIZED COMPARISON RESPONSE
Key Insight:Reuse can operate below the full-answer level.
AI RELIABILITY & QUALITY BENCHMARKING

Evaluation — Reuse Quality, Not Just Hit Rate

Optimizing solely for cache hit rate encourages unsafe loose matching. In production systems, evaluation prioritizes precision, entity fidelity, and temporal correctness:

01. ACCEPTANCE FIDELITYPrecision

Reuse Precision

When the system accepts a candidate for reuse, how frequently was that decision completely appropriate? Ensures users never receive false-match shortcuts.

Objective: Minimize false positive cache hits
02. PRIMARY GOVERNANCE METRICZERO-TOLERANCE

Wrong-Entity Reuse Rate

Strictly tracks whether reused intelligence ever crossed a corporate, ticker, or tenant boundary. In financial AI, serving Company A's data for Company B's question is a critical failure.

Objective: Absolute zero cross-entity leakage
03. TEMPORAL INTEGRITYFreshness

Stale Reuse Rate

Measures whether candidates that have undergone source file updates, revised earnings statements, or expired TTL clocks are properly invalidated.

Objective: Immediate invalidation on file modifications
04. RETRIEVAL & EFFICIENCYSystem Impact

Retrieval Benchmark & Compute Avoidance

Retrieval Quality: Precision@K, Recall@K, MRR, nDCG on candidate retrieval.

Avoided Compute: Redundant database scans avoided, model calls bypassed, tokens saved, latency reduction.

Objective: Measurable resource efficiency at verified high precision
Evaluation Thesis:How much work can we safely avoid without introducing wrong-context reuse?
FAILURE MODES & FALLBACK DESIGN

The Cache Optimizes the Product — It Must Not Become a Product Dependency

A caching layer must never introduce a single point of failure. The system treats the cache as an accelerant with seamless fallbacks:

Failure ModeSystem Safeguard ResponseArchitectural Rationale
Wrong entity matchReject via hard entity constraintsCompany/ticker mismatch fails hard equality check; candidate is discarded immediately.
Stale / expired resultReject through freshness validationTTL expiry or underlying file modification invalidates the cached entry before prompt assembly.
Semantic false positiveFilter / validate / trigger fresh pipelineLow score separation or NLI contradiction triggers immediate fallback to fresh retrieval.
Over-normalization riskRetain raw + normalized representationsOriginal raw query string is preserved alongside canonical tokens to prevent lost nuances.
Reuse layer unavailable / timeoutBypass cache → direct fresh generationCache outage degrades gracefully to standard retrieval without throwing user-facing errors.
SYSTEM COMPROMISES & DESIGN BALANCES

Engineering Trade-Offs

Architectural DecisionPrimary BenefitEngineering Cost / Compromise
Exact canonical fast pathInstant zero-cost return for identical normalized requestsMisses conceptual paraphrases with different wording
Hybrid semantic retrieval (OpenSearch)Matches complex linguistic variations and subtask patternsIntroduces vector/BM25 retrieval overhead on exact misses
Hard entity / temporal constraintsCompletely eliminates cross-company and stale-period hallucinationsReduces raw cache utilization by discarding out-of-boundary matches
Freshness & TTL validationGuarantees responses reflect active documents and current market stateRequires invalidation lifecycle management across document updates
Selective NLI cross-encoder validationDeep logical support checking and contradiction detectionInference latency overhead; only viable on high-stakes ambiguous paths
Multiple operational reuse modesAllows partial context and subtask acceleration in agent workflowsMore complex orchestrator integration than a simple binary cache
Safe fresh fallback architectureSystem never breaks when reuse confidence is weak or cache is downPays full retrieval/generation cost when uncertainty is detected
Optimization Core:Precision and contextual correctness over aggressive cache utilization
OWNERSHIP & CORE COMPETENCIES

Contribution & Technical Proof

MY DIRECT CONTRIBUTION

My work focused on designing the precision-first retrieval and reuse framework:

  • Designing the two-tier exact and semantic retrieval architecture
  • Establishing hard entity, temporal, and scope filtering so semantic similarity alone does not grant reuse
  • Integrating hybrid search (BM25 + dense vectors) in OpenSearch for prior intelligence discovery
  • Creating multi-mode reuse pathways: direct answer, context injection, and subtask artifacts
  • Structuring selective NLI validation for high-risk ambiguous queries
  • Defining evaluation suites focused on safe reuse precision, wrong-entity rate, and compute avoidance rather than raw hit rate

The core lesson was that semantic caching is fundamentally a precision-retrieval safety problem, not an approximate memory shortcut.

WHAT THIS DEMONSTRATES

Key engineering competencies proven by this architecture:

Semantic CachingHybrid RetrievalQuery NormalizationEntity ResolutionTemporal ReasoningFreshness ControlOpenSearchRetrieval EvaluationNLI ValidationAgent / Orchestrator IntegrationLatency & Cost OptimizationProduction AI Reliability