Skip to content
Skip to lesson
Back to Topics
LearnAI System Design & InterviewingLLM-Powered Search Engine
HardSystem Design20 min read

LLM-Powered Search Engine

Help a developer find the current parser rule without exposing another team's roadmap. Design a search path that preserves its exception and shows only checked claims.

On this page

A developer asks an internal search engine: "Which parser-v2 migration window applies to service accounts?" Four documents sit in the corpus. The current migration standard requires starting within 30 days. A separate exception allows 60 days for service accounts, only with security approval. An obsolete revision says 90 days, and a private roadmap in another workspace shares almost the exact same keywords. A fluent answer built from either wrong document is worse than returning no answer at all.

Traditional search hands back ten links and lets the reader judge freshness and caveats. An LLM-powered search engine synthesizes a direct statement that users act on, so the architecture must enforce document identity, freshness, access rights, and claim verification across every hop from ingestion to streaming tokens.

In the multi-tenant serving lesson, we kept one workspace from reading another's model state. Here we trace those controls through , , , context packing, citation checks, and streaming.

Decide what counts as an answer

For CodeAtlas, a complete answer must include both the general 30-day rule and the conditional 60-day exception. Saying "service accounts get 60 days" drops the approval qualifier. Citing only the 30-day rule omits the exception that answers the developer's actual question. Pulling text from another workspace's private roadmap leaks confidential data even if the number happens to be right.

conditions an LLM on retrieved passages.[1] Around that core mechanism, the search system enforces three explicit answer rules:

  1. Use only current, authorized sources and preserve qualifying clauses such as "only with security approval."
  2. When two current sources disagree without an explicit supersession link, surface the conflict rather than letting the model invent precedence.
  3. When required evidence is missing or stale, return an incomplete-answer notice or authorized source links instead of guessing.

Size the architecture around this target envelope:

DimensionDesign targetPre-deployment check
Access controlZero unauthorized text, titles, citations, or cached replies leave retrievalCross-tenant and live revocation tests
FreshnessServe only the active published revision with its effective dateIngest lag, deletion, and supersession checks
LatencyTrack progress, first draft token, first checked claim, and completion separatelyEnd-to-end traces and tail percentiles
CoverageInclude both the base rule and its applicable conditional exceptionHeld-out queries with required passage and claim labels
Peak load1,000 requests/s peak; 60% require LLM synthesisMeasured route mix, stage times, and GPU throughput

A progress spinner at 100 ms reassures the user that work has started, and a draft token at 800 ms can arrive before verification completes. Both clocks matter only once every passage in the index carries an exact revision, byte span, and reader list.

Make evidence identifiable before it becomes searchable

Ingestion fetches source revisions, parses them into chunks, and updates lexical and vector indexes. Every chunk needs an immutable (doc_id, revision) key, tenant ID, source URL, character offsets tied to a specific text-normalization version, SHA-256 content digest, effective timestamp, and access metadata.

Updating or deleting a document cannot wait for an overnight re-embedding job. Maintain a lightweight current-revision registry alongside the indexes so the query path rejects superseded, unpublished, or revoked chunks immediately while vector indexes catch up asynchronously.

Architecture of an LLM-powered search engine flowing left to right: offline ingestion hashes policy@2 [0-80] and exception@1 [0-101] with SHA-256 digests into BM25 lexical and dense HNSW indexes scoped to workspace-a, followed by RRF fusion, reranking, grounded synthesis, and an online verification gate checking RBAC, current revision, and exact spans before streaming verified citations. A current-revision registry feeds invalidation updates directly into both retrieval and the verification gate.
The 30-day base rule and conditional 60-day exception retain exact revisions, offsets, and SHA-256 digests. Registry updates invalidate stale candidates and active streams before publication.

Authorization belongs to the service, not the query planner

Derive tenant and group membership exclusively from authenticated server-side credentials. Apply that scope to every retrieval call, speculative rewrite, parent-chunk fetch, external reranker, citation preview, log line, and cache lookup.

Filter candidates inside the index query before top-KK truncation. Vector engines like Qdrant support filtered search directly and recommend payload indexes on access-control fields.[2] Post-filtering a global top-KK list wastes candidate slots on forbidden or stale hits, potentially leaving zero usable passages.

Even when forbidden hits are hidden, shared corpus statistics such as global IDF weights can leak subtle score or timing signals. Elasticsearch explicitly notes that document-level security does not alter global relevance statistics.[3] When strict statistical noninterference is required, place tenants in isolated indexes.

Freshness isn't a timestamp boost

Re-crawling an obsolete document gives it a brand-new crawl timestamp without making it current. Store source publication time, effective date, crawl time, and index publication time as separate fields, and rely on explicit revision supersession rather than exponential time decay. Hot and warm index tiers shorten ingestion lag for fast-changing release notes, while live mutable state (like whether a CI build is running right now) belongs behind an authorized live API rather than a search index.

Route the question without weakening its constraints

"Which parser-v2 migration window applies to service accounts?" belongs on hybrid document search. "Is build-1042 running now?" belongs on a live job-status API. A combined question needs both branches concurrently.

Query expansion techniques like Hypothetical Document Embeddings (HyDE) generate a synthetic passage whose embedding can boost recall.[4] Keep generated expansions strictly inside retrieval: never cite a synthetic HyDE passage as source evidence, and never let query rewriting drop identifiers, dates, or negations.

The compact router below keeps freshness independent of route selection, so asking for the "latest" rule or combining a live build check with a migration question preserves both constraints:

query-routing.py
from dataclasses import dataclass

@dataclass(frozen=True)
class Plan:
    routes: tuple[str, ...]
    requires_current_revision: bool

def plan_query(query: str) -> Plan:
    text = query.lower().replace("service-account", "service account")
    fresh = any(term in text for term in ("latest", "current", "right now"))
    live = any(term in text for term in ("build-", "job status", "quota remaining"))
    rule_doc = any(term in text for term in ("policy", "migration", "exception"))
    routes = []
    if live:
        routes.append("authorized_live_api")
    if rule_doc or not live:
        routes.append("authorized_hybrid_search")
    return Plan(tuple(routes), fresh or rule_doc)
Output
Plan(routes=('authorized_hybrid_search',), requires_current_revision=True)
Plan(routes=('authorized_live_api', 'authorized_hybrid_search'), requires_current_revision=True)
Non-crossing query routing graph under authenticated workspace-a scope. On the left, a latest parser-v2 policy question routes to authorized_hybrid_search with requires_current_revision True. In the center, a combined build-1042 status and current migration policy question fans out cleanly to both authorized_hybrid_search and authorized_live_api. On the right, a live build-1042 status question routes only to authorized_live_api. Both backends converge into versioned evidence merge and live access recheck.
Independent routing and freshness flags. Document questions hit filtered hybrid search, mutable job state hits the live API, and mixed queries fan out to both while retaining the current-revision constraint.

If the query planner fails or times out, fall back to a narrower authorized search or ask for clarification; never widen tenant scope. Treat raw query logs as sensitive data too, since queries often contain internal identifiers.

Retrieve broadly within the permitted corpus

excels at exact identifiers like parser-v2 using term frequency, inverse document frequency, and length normalization.[5] Dense vector search catches paraphrases and conceptual matches. Run both branches concurrently and merge them with (RRF):

RRF⁡(d)=∑j: d∈Rj1k+rank⁡Rj(d).\operatorname{RRF}(d) = \sum_{j:\,d \in R_j} \frac{1}{k + \operatorname{rank}_{R_j}(d)}.

Ranks start at 1, and each document contributes at most once per list so duplicate chunks cannot inflate a document's score. Using k=60k = 60 provides a standard starting balance without assuming BM25 and cosine similarities share a numerical scale.[6]

Reciprocal Rank Fusion at k = 60. Lexical BM25 ranks policy@2 first (1/61 = 0.01639) and exception@1 second (1/62 = 0.01613) while dropping an intra-list duplicate of policy@2. Dense vector search reverses the order. Stacked contribution bars on a 0 to 0.04 scale show both documents tying at exactly 0.03252, with identity ordering placing exception@1 first.
With k = 60, reversing two documents across lexical and dense lists gives an exact tie (1/61 + 1/62 = 0.03252). Deduplicating within each list prevents repeated chunks from double-counting.

After fusion, a cross-encoder jointly scores the query and top candidate passages, while late-interaction models like ColBERT keep per-token embeddings to balance precision and speed.[7] Tune candidate counts against measured recall and latency rather than hardcoding arbitrary funnels.

Side-by-side narrowing retrieval funnels at K = 2 over the four-document ranking [roadmap@1, policy@1, policy@2, exception@1]. Left: post-filtering truncates to Top-2 first, capturing forbidden roadmap@1 and obsolete policy@1, then drops both at eligibility check leaving 0 usable passages. Right: pre-filtering enforces workspace-a access and current revision before Top-2, preserving both policy@2 and exception@1.
Eligibility-before-top-K versus top-K-then-filter at K = 2. Filtering after truncation empties both slots; pre-filtering preserves both required workspace-a documents.

Run a miniature evidence pipeline

Let's wire the entire corpus into an executable pipeline: pre-filtered BM25 and cosine retrieval, RRF fusion, budget-aware packing, and exact span publication. Watch how the checks handle five real failure modes: empty budget, tenant mismatch, duplicate hits, truncated qualifiers, and mid-flight permission or revision changes.

local-search-pipeline.py
@dataclass(frozen=True)
class Principal:
    tenant: str
    groups: frozenset[str]

@dataclass(frozen=True)
class Document:
    doc_id: str
    revision: int
    tenant: str
    text: str
    vector: tuple[float, float]

    @property
    def key(self):
        return (self.doc_id, self.revision)

    @property
    def digest(self):
        return hashlib.sha256(self.text.encode()).hexdigest()

@dataclass(frozen=True)
class Access:
    current_revision: int
    readers: frozenset[str]
    published: bool = True

@dataclass(frozen=True)
class Quote:
    key: tuple[str, int]
    start: int
    end: int
    text: str
    digest: str

alice = Principal("workspace-a", frozenset({"engineering"}))
corpus = [
    Document("policy", 1, "workspace-a", "Parser-v2 migrations may start within 90 days.", (1.0, 1.0)),
    Document("policy", 2, "workspace-a", "Parser-v2 SDK migrations must start within 30 days after the deprecation notice.", (1.0, 0.5)),
    Document("exception", 1, "workspace-a", "Service-account SDK migrations may start within 60 days after the notice only with security approval.", (0.5, 1.0)),
    Document("roadmap", 1, "workspace-b", "Private parser-v2 service-account SDK migration roadmap.", (1.0, 1.0)),
]
store = {doc.key: doc for doc in corpus}
registry = {
    "policy": Access(2, frozenset({"engineering"})),
    "exception": Access(1, frozenset({"engineering"})),
    "roadmap": Access(1, frozenset({"engineering"})),
}

def eligible(doc, principal, access):
    rule = access.get(doc.doc_id)
    return bool(rule and rule.published
                and doc.tenant == principal.tenant
                and doc.revision == rule.current_revision
                and principal.groups & rule.readers)

def words(text):
    return re.findall(r"[a-z0-9]+(?:-[a-z0-9]+)*", text.lower())

def lexical_ranking(query, docs):
    if not docs:
        return []
    counts = {doc.key: Counter(words(doc.text)) for doc in docs}
    avg_len = sum(sum(c.values()) for c in counts.values()) / len(docs)
    scores = {}
    for doc in docs:
        score = 0.0
        for term in set(words(query)):
            df = sum(term in c for c in counts.values())
            idf = math.log(1 + (len(docs) - df + 0.5) / (df + 0.5))
            tf = counts[doc.key][term]
            length = sum(counts[doc.key].values())
            score += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length / avg_len))
        scores[doc.key] = score
    return sorted(scores, key=lambda key: (-scores[key], key))

def vector_ranking(query_vector, docs):
    def cosine(doc):
        dot = sum(a * b for a, b in zip(query_vector, doc.vector))
        norm = math.sqrt(sum(a * a for a in query_vector) * sum(b * b for b in doc.vector))
        return dot / norm if norm else 0.0
    return [doc.key for doc in sorted(docs, key=lambda doc: (-cosine(doc), doc.key))]

def rrf(rankings, k=60):
    if k < 0:
        raise ValueError("k must be nonnegative")
    scores = defaultdict(float)
    for ranking in rankings:
        for rank, key in enumerate(dict.fromkeys(ranking), 1):
            scores[key] += 1 / (k + rank)
    return sorted(scores, key=lambda key: (-scores[key], key))

def retrieve(principal, access):
    docs = [doc for doc in corpus if eligible(doc, principal, access)]
    query = "parser-v2 SDK migration policy for service-account exceptions"
    return rrf([lexical_ranking(query, docs), vector_ranking((1.0, 1.0), docs)])

def pack(keys, word_budget):
    if word_budget < 0:
        raise ValueError("budget must be nonnegative")
    selected, used = [], 0
    for key in dict.fromkeys(keys):
        doc = store[key]
        cost = len(words(doc.text))
        if used + cost <= word_budget:
            selected.append(Quote(key, 0, len(doc.text), doc.text, doc.digest))
            used += cost
    return selected

def publish(quotes, principal, access):
    if len(quotes) != 2 or {q.key[0] for q in quotes} != {"policy", "exception"}:
        return "Insufficient current, authorized evidence."
    for quote in quotes:
        doc = store.get(quote.key)
        if (doc is None or not eligible(doc, principal, access)
                or quote.digest != doc.digest
                or quote.start != 0 or quote.end != len(doc.text)
                or doc.text[quote.start:quote.end] != quote.text):
            return "Insufficient current, authorized evidence."
    return "\n".join(f'"{q.text}" [{q.key[0]}@{q.key[1]}:{q.start}-{q.end}]'
                     for q in sorted(quotes, key=lambda q: q.key))

ranked = retrieve(alice, registry)
assert set(ranked) == {("policy", 2), ("exception", 1)}
assert rrf([ranked + ranked]) == rrf([ranked])
assert retrieve(Principal("workspace-c", alice.groups), registry) == []

packed = pack(ranked, word_budget=40)
answer = publish(packed, alice, registry)
assert "only with security approval" in answer
assert "Insufficient" in publish(pack(ranked, 0), alice, registry)

corrupted = [replace(packed[0], text="Approval is not required."), *packed[1:]]
assert "Insufficient" in publish(corrupted, alice, registry)

exc = next(q for q in packed if q.key[0] == "exception")
short_text = exc.text.split(" only with security approval.")[0]
truncated = [replace(exc, end=len(short_text), text=short_text) if q.key[0] == "exception" else q for q in packed]
assert "Insufficient" in publish(truncated, alice, registry)

revoked = {**registry, "exception": replace(registry["exception"], readers=frozenset())}
assert "Insufficient" in publish(packed, alice, revoked)
advanced = {**registry, "policy": replace(registry["policy"], current_revision=3)}
Output
eligible ranked keys: [('exception', 1), ('policy', 2)]
"Service-account SDK migrations may start within 60 days after the notice only with security approval." [exception@1:0-101]
"Parser-v2 SDK migrations must start within 30 days after the deprecation notice." [policy@2:0-80]
Revocation, missing evidence, stale revision, and changed-span checks passed.
condition-truncated exact quotation rejected: True
revision advanced before reindex: Insufficient current, authorized evidence.

Look closely at the two edge cases caught at the end of that run. First, a substring [0, 72) of exception@1 matches the document's SHA-256 digest and is a verbatim prefix, yet drops "only with security approval." Checking full clause integrity prevents silent truncation of qualifying conditions.

Calibrated character-offset span comparison on exception@1 (101 characters). The base clause occupies characters 0 to 72 and the qualifying clause "only with security approval." occupies characters 73 to 100. Case A quotes the verbatim prefix [0, 72), passing SHA-256 digest matching but dropping the qualifier and failing publication (HOLD). Case B preserves the complete span [0, 101), passing both digest and clause checks (PUBLISH).
A verbatim prefix [0, 72) matches the source digest while stripping the approval condition. Requiring complete conditional spans catches silent qualifier truncation before publication.

Second, when the registry advances policy to revision 3 while the search index still holds revision 2, retrieve excludes policy@2 and publish blocks even a previously complete quote pack. Availability pauses briefly until revision 3 lands rather than silently serving an obsolete 30-day rule.

Asynchronous revision lag timeline across three states. At T1, the registry and search index both hold policy@2 and exception@1 so publication succeeds. At T2, the registry advances policy to revision 3 while the search index still serves policy@2, creating a lag gap. During this gap, the publication gate rejects stale policy@2 (leaving the policy slot empty while exception@1 stays filled) and withholds the answer until policy@3 lands at T3.
When the registry moves to revision 3 ahead of the index, stale revision 2 is withheld rather than silently substituted.

Pack evidence without changing its meaning

Packing turns ranked passages into a prompt budget counted with the serving model's actual tokenizer (reserving space for system instructions, the user query, tool schemas, and output tokens). Pure relevance sorting can fill the entire window with ten near-duplicate chunks of the general 30-day rule and crowd out the single exception chunk. Add document-diversity and coverage constraints so secondary rules survive packing.

Position matters too: Liu et al.'s Lost in the Middle study showed that models can overlook relevant facts buried in the middle of long contexts.[8] Measure recall sensitivity across prompt positions on your serving model before tuning chunk order. If you apply prompt compression such as LLMLingua, run it strictly after authorization and passage selection, verify that numbers and negations survive, and keep mappings back to exact original spans for verification.[9]

Verify that citations support their claims

Split citation verification into three independent checks:

CheckWhat it verifiesFailure caught
ResolutionCitation ID maps to a current, authorized revision and spanLink points to a deleted or cross-tenant document
SupportThe cited span entails the claim, including numbers and conditionsModel drops "only with security approval"
CoverageEvery material part of the question has backing evidenceGeneral rule cited, relevant exception omitted

Verbatim quotes can be checked deterministically; paraphrased claims require semantic verification via natural language inference (NLI) models or calibrated verifier LLMs (as studied in TRUE and FActScore).[10][11] Never confuse keyword overlap with semantic entailment:

lexical-support-counterexample.py
def terms(text):
    return set(re.findall(r"[a-z0-9]+", text.lower()))

claim = "Security approval is required"
negated_source = "Security approval is not required"
paraphrased_source = "Authorization from the security team is mandatory"
assert terms(claim) <= terms(negated_source)
assert not terms(claim) <= terms(paraphrased_source)
print("Negated source passes lexical check:", terms(claim) <= terms(negated_source))
print("Paraphrase passes lexical check:", terms(claim) <= terms(paraphrased_source))
Output
Negated source passes lexical check: True
Paraphrase passes lexical check: False
Token-level comparison showing why lexical containment fails claim verification. The claim "Security approval is required" contains 4 terms. Left: the negated source "Security approval is not required" matches all 4 claim tokens (4/4 lexical pass, false positive) while the highlighted token "not" flips meaning to NLI contradiction. Right: the valid paraphrase "Authorization from the security team is mandatory" matches only 2 of 4 tokens (lexical fail, false negative) yet achieves NLI entailment.
Token overlap accepts a direct contradiction and rejects an accurate paraphrase. Verifying paraphrased claims requires semantic entailment models.

Treat every retrieved passage as untrusted data, never as instructions. Delimit retrieved chunks clearly, block tool calls triggered solely by retrieved text, and keep secrets out of the generation context to defend against indirect prompt injection.[12]

Finite-state machine for streaming claim verification bound to (request-a, draft-2, rev 2). Claims start in PENDING (held in buffer). Stale events (draft-1, rev 1) or non-boolean verdicts ("false", 1) self-loop back to PENDING and are dropped. Strict accepted is True transitions to terminal CHECKED, emitting the claim once while ignoring duplicate event IDs. Strict accepted is False transitions to terminal BLOCKED, permanently suppressing publication even if a later accept arrives.
Streaming verification binds each check event to `(request_id, draft_hash, source_revision)`. Valid approval emits the claim once; rejection permanently blocks it.

Stream progress before policy claims

Users want fast visual feedback, yet you cannot un-show a leaked or wrong rule after a reader copies it. Stream safe progress updates and authorized source citations immediately, while holding factual claims until their verification verdict arrives.

Server-Sent Events (SSE) provide simple HTTP streaming with Last-Event-ID reconnect cursors, though authentication, authorization, and replay deduplication remain application responsibilities.[13] One subtle browser quirk breaks naive deduplication: if an SSE event omits an id: line, the browser silently inherits the previous event's lastEventId:

inherited-sse-event-id.txt
id: 12
data: {"type":"progress"}

data: {"type":"checked_claim"}

Both callbacks receive lastEventId == "12". Deduplicating solely on lastEventId drops the second frame! Always emit monotonic explicit IDs (12, 13, ...) on every replayable frame. Also note that native browser EventSource only supports GET requests, so create the search job separately or stream via fetch instead of stuffing secrets into query strings.[14]

Side-by-side Server-Sent Events wire trace comparing omitted vs explicit event IDs. Left: Frame 1 sends id: 12 (progress) and sets browser lastEventId = "12" (emitted). Frame 2 omits id for checked_claim, so the browser inherits lastEventId = "12" and client deduplication drops the verified claim. Right: Frame 2 sends explicit id: 13, updating lastEventId = "13" so both frames deliver cleanly and reconnects resume with Last-Event-ID: 13.
Omitting an SSE `id` field makes the browser inherit `lastEventId = 12`. Emit explicit monotonic IDs on every replayable event so reconnects and deduplication never drop verified claims.

The state machine below shows how to bind every verification verdict to (request_id, draft_hash, source_revision) with strict boolean checking so a string "false" or integer 1 never accidentally releases an unverified claim:

stream-publication-state.py
from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Event:
    event_id: int
    request_id: str
    kind: str
    draft_hash: str
    source_revision: int
    accepted: bool = False

def apply_events(events):
    state = "pending"
    emitted = []
    seen = set()
    for ev in events:
        if ev.request_id != "request-a" or ev.event_id in seen:
            continue
        if ev.event_id < 0 or ev.source_revision < 0:
            continue
        if ev.accepted is True:
            verdict = "checked"
        elif ev.accepted is False:
            verdict = "blocked"
        else:
            continue
        seen.add(ev.event_id)
        if ev.draft_hash != "draft-2" or ev.source_revision != 2:
            continue
        if state != "pending" or ev.kind != "check":
            continue
        state = verdict
        if state == "checked":
            emitted.append("checked policy claim")
    return state, emitted

accepted = Event(1, "request-a", "check", "draft-2", 2, True)
rejected = Event(2, "request-a", "check", "draft-2", 2, False)
stale = Event(3, "request-a", "check", "draft-1", 1, True)
assert apply_events([stale]) == ("pending", [])
assert apply_events([rejected]) == ("blocked", [])
assert apply_events([accepted, accepted]) == ("checked", ["checked policy claim"])
assert apply_events([rejected, accepted]) == ("blocked", [])
for bad in (replace(accepted, accepted="false"), replace(accepted, accepted=1)):
Output
stale result: ('pending', [])
rejected claim: ('blocked', [])
accepted replay: ('checked', ['checked policy claim'])
malformed verdict: ('pending', [])

Matching ev.accepted is True and ev.accepted is False by identity rejects truthy strings like "false" and numeric flags like 1 before a malformed payload can release unverified text.

Measure the useful response from request to verification

You can overlap query planning (40 ms) with an independent retrieval branch that searches the raw query (260 ms). A branch that depends on a rewritten query must wait for planning to finish first. Adding reranking (90 ms), packing (20 ms), model TTFT (430 ms), first claim completion (100 ms), and claim verification (80 ms) gives the critical path:

MilestoneCritical-path sumLatency
Raw-branch draft TTFTmax⁡(40,260)+90+20+430\max(40, 260) + 90 + 20 + 430800 ms
Rewrite-dependent draft TTFT40+260+90+20+43040 + 260 + 90 + 20 + 430840 ms
First checked claim800+100+80800 + 100 + 80980 ms
Calibrated 0 to 1,000 ms latency Gantt chart comparing parallel raw-branch retrieval against serial rewrite-dependent retrieval. Top: planning (40 ms) overlaps raw retrieval (260 ms), followed by rerank (90 ms), pack (20 ms), and model TTFT (430 ms) to hit draft TTFT at 800 ms, then claim completion (100 ms) and verification (80 ms) for first checked claim at 980 ms. Bottom: waiting for rewrite (40 ms) before retrieval shifts draft TTFT to 840 ms (+40 ms).
Overlapping planning with raw-query retrieval saves 40 ms on the critical path (800 ms draft TTFT vs. 840 ms when waiting on a rewrite), reaching the first checked claim at 980 ms.

Always compute end-to-end percentiles from complete request traces (including timeouts, cancellations, and retries) rather than adding individual stage p95s. Optimizations like PagedAttention and speculative decoding speed up the generation slice, not slow upstream retrievals or claim checks.[15][16]

Count KV-resident requests separately

By Little's Law (L=λWL = \lambda W), mean concurrency equals arrival rate times residence time. Crucially, a search request only occupies GPU KV cache during the model-resident portion of its life, not while waiting on retrieval or post-generation CPU checks.

At 1,000 peak QPS with 60% synthesis traffic (600 synthesis requests/s), suppose each synthesis request spends 0.37 s in retrieval/packing, 1.93 s holding GPU KV cache, and 0.20 s in final checks (2.50 s total), with 120 mean output tokens and 1,560 mean cached positions. For a 32-layer GQA decoder with 8 KV heads, head dimension 128, and 2-byte FP16/BF16 entries, each cached position takes 2×32×8×128×2=131,0722 \times 32 \times 8 \times 128 \times 2 = 131{,}072 bytes (128 KiB). Let's size both KV memory and decode throughput lower bounds with a 12 GiB net KV budget and 6,000 output tokens/s per GPU:

search-capacity.py
from math import ceil

all_qps, synthesis_fraction = 1000, 0.60
synthesis_qps = all_qps * synthesis_fraction
before_model, model_resident, after_model = 0.37, 1.93, 0.20
in_flight = synthesis_qps * (before_model + model_resident + after_model)
kv_resident = synthesis_qps * model_resident

kv_bytes_per_position = 2 * 32 * 8 * 128 * 2
mean_cached_positions = 1560
kv_gib = kv_resident * mean_cached_positions * kv_bytes_per_position / 2**30

kv_devices = ceil(kv_gib / 12)
decode_devices = ceil(synthesis_qps * 120 / 6000)
assert round(in_flight) == 1500 and round(kv_resident) == 1158
assert kv_devices == 19 and decode_devices == 12
print("synthesis in flight:", round(in_flight))
print("KV-resident requests:", round(kv_resident))
print("mean KV GiB:", round(kv_gib, 2))
print("KV / decode device lower bounds:", kv_devices, "/", decode_devices)
Output
synthesis in flight: 1500
KV-resident requests: 1158
mean KV GiB: 220.52
KV / decode device lower bounds: 19 / 12
Two-panel quantitative capacity diagram for 600 synthesis requests per second. Top: calibrated 2.50-second request lifecycle showing 0.37 s pre-model, 1.93 s active KV residency, and 0.20 s post-release; Little’s Law gives 1,500 total in-flight requests but only 1,158 KV-resident requests consuming 220.52 GiB. Bottom: horizontal GPU lower-bound chart comparing KV memory (19 GPUs at 12 GiB/GPU) against decode throughput (12 GPUs at 6,000 tok/s/GPU), with a dashed envelope line at max(19, 12) = 19 GPUs on one shared pool.
Only the 1.93 s model interval consumes KV cache (1,158 of 1,500 in-flight requests), driving 220.52 GiB of KV state. The 19-device memory bound and 12-device decode bound run on the same pool and are never summed.

Price the route mix, including the cheap routes

Full synthesis pays for retrieval, reranking, prompt + output tokens, and claim verification. Cache hits and structured API lookups are far cheaper, though they still pay for auth, storage, and formatting. With a 60% synthesis / 30% validated cache / 10% structured lookup split (using a 1,500-token prompt and 400-token answer at $3 per million tokens):

search-route-cost.py
prompt_tokens, output_tokens = 1500, 400
rate_per_million = 3.0
synthesis_usd = (prompt_tokens + output_tokens) * rate_per_million / 1_000_000
full_usd = 0.002 + 0.001 + synthesis_usd + 0.001
cache_usd, structured_usd = 0.0003, 0.001
mean_usd = 0.60 * full_usd + 0.30 * cache_usd + 0.10 * structured_usd
assert round(full_usd, 4) == 0.0097 and round(mean_usd, 5) == 0.00601
print(f"full route: ${full_usd:.4f}")
print(f"weighted mean: ${mean_usd:.5f}")
print(f"1,000 QPS: ${mean_usd * 1000 * 60:.2f} per minute")
Output
full route: $0.0097
weighted mean: $0.00601
1,000 QPS: $360.60 per minute
Two-panel route economics chart at 1,000 QPS. Left: horizontal unit-cost bar chart comparing full synthesis ($0.0097), structured lookup ($0.0010), and validated cache ($0.0003), with a dashed reference line at the 60/30/10 weighted mean of $0.00601 per query (-38%). Right: 100% stacked comparison showing that 60% full-synthesis traffic accounts for 96.8% of total spend ($0.00582 of $0.00601, or $360.60/min), while 30% cache and 10% structured routes account for only 3.2% combined.
Offloading 40% of traffic to validated cache and structured routes trims mean cost from $0.0097 to $0.00601 per query ($360.60/min at 1,000 QPS).

A semantic cache match is only a candidate lookup. Before returning a cached answer, revalidate the caller's tenant scope, prompt/model version, and every cited document revision against the live registry. If freshness or access cannot be verified, take the miss path instead of serving stale private text.

Evaluate each kind of failure separately

Measure each stage independently on held-out labeled queries containing deletions, conflicting rules, mid-stream revocations, indirect prompt injections, and conditional exceptions:

LayerPrimary metricWhat it misses alone
RetrievalRecall@K, MRR, nDCG over current authorized docsWhether the generator actually used the retrieved exception
PackingFraction of required evidence surviving token budgetMulti-document coverage when one topic dominates ranking
CitationsResolution, semantic support, and claim coverageEach of the three can fail while the other two pass
AnswerTask correctness and calibrated abstentionFaithfulness to a stale source still produces a wrong answer
ServiceChecked-claim p95/p99, error rate, cost, KV occupancyAverages over successful requests hide timeouts and overload
SecurityZero unauthorized leaks across revocation testsHigh relevance never offsets an access breach

Reference-free LLM-as-a-judge frameworks like RAGAS help track faithfulness trends when labeled sets are small, while click-through and reformulation rates supply useful online signals; neither replaces labeled retrieval and security regression suites.[17]

When computing Recall@K and nDCG@K, deduplicate by document identity first so two chunks from the same document do not earn double credit, and return None for empty gold sets (unanswerable queries):

retrieval-metrics.py
from math import log2

def metrics(ranked, relevant, k):
    if k <= 0:
        raise ValueError("k must be positive")
    if not relevant:
        return {"recall": None, "ndcg": None}
    unique = list(dict.fromkeys(ranked))[:k]
    recall = len(set(unique) & relevant) / len(relevant)
    dcg = sum((doc in relevant) / log2(rank + 1) for rank, doc in enumerate(unique, 1))
    ideal = sum(1 / log2(rank + 1) for rank in range(1, min(k, len(relevant)) + 1))
    return {"recall": round(recall, 4), "ndcg": round(dcg / ideal, 4)}

gold = {"policy@2", "exception@1"}
Output
missing exception: {'recall': 0.5, 'ndcg': 0.6131}
both required sources: {'recall': 1.0, 'ndcg': 1.0}
Retrieval evaluation comparing three top-2 rankings against gold set {policy@2, exception@1} on a 0.0 to 1.0 scale. Duplicate chunks [policy@2, policy@2] deduplicate to one hit and score 0.50 recall and 0.6131 nDCG, identical to [policy@2, faq]. Retrieving both unique required documents [policy@2, exception@1] scores 1.00 recall and 1.0000 nDCG.
Deduplicating by document identity prevents multiple chunks of policy@2 from masking a missing exception@1 (recall 0.50, nDCG 0.6131).

Keep stage-level attribution in traces so regressions point straight to their cause: a missing active revision points to ingestion or retrieval, a dropped exception points to packing, a stripped qualifier points to synthesis or NLI verification, and any cross-tenant hit points directly to access control.

Mastery check

Evaluation rubric

  • Trace both the base rule and its conditional exception through revision tracking, pre-filtered hybrid retrieval, RRF, packing, and span verification, explaining why stale or forbidden hits cannot occupy top-KK slots.
  • Separate citation resolution, semantic support, and coverage, and show how composite event binding stops stale verdicts or live revocations from releasing text.
  • Derive the 980 ms checked-claim path, 1,158 KV-resident requests, and route-weighted cost, distinguishing memory lower bounds from decode lower bounds.

Follow-up questions

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A trusted global ranking is [forbidden-X, obsolete-Y, allowed-A, allowed-B, allowed-C]. All three allowed documents are current and relevant. With K = 3, how many useful documents survive top-K-then-filter versus eligibility-before-top-K?
2.The local router receives “quota remaining and current exception”. Which source plan and current-revision flag result from the independent live and document routing rules?
3.Use RRF with k = 10 on branch lists [M, M, N] and [N]. After within-branch deduplication, which document wins and what is its fused score?
4.The miniature publisher receives four packs for policy@5 (120 characters) and exception@3 (84 characters). Both records are current, published and authorized, with matching document digests. Every quote equals its stated source slice. A has spans policy [0,120), exception [1,84); B has [0,120), [0,84); C has [2,120), [0,84); D has [0,119), [0,84). Which pack does the publisher release?
5.The search engine's publication reducer receives three check events for a pending draft. All three match request-a, draft-2 and source revision 2. In arrival order, their accepted values are 1 (event 6), True (event 7) and False (event 8). Which event first makes the reducer emit a claim, if any? What are the final state and total number of claims emitted?
6.Three SSE events carry these id fields in order: “27”, no id field, then an explicitly empty id field. Each has distinct nonempty data and a terminating blank line. What lastEventId values do callbacks receive, and is a nonempty Last-Event-ID available afterward for reconnect?
7.A search request has planning 55 ms, independent raw retrieval 210 ms, rerank 70 ms, pack 30 ms, model-to-first-token 360 ms, claim completion 90 ms and checking 60 ms. What are the first checked-claim times with raw-branch overlap and with rewrite-dependent retrieval?
8.A steady-state synthesis route receives 400 requests/s. Mean total residence is 2.8 s, of which model KV is retained for 1.6 s. Each resident averages 2048 cached positions at 24576 bytes/position. Use 1 GiB = 2^30 bytes. What are the mean total in-flight count, KV-resident count and KV footprint?
9.A search route mix is 50% full synthesis at $0.012, 35% valid cache at $0.0004 and 15% structured lookup at $0.002. At 800 total requests/s, what are the mean cost per request and cost per minute?
10.The relevant document identities are {A, B, C}. A search returns [C, C, irrelevant, A] in rank order. When scoring by document identity, what are recall@3 and binary nDCG@3, rounded to four decimals?

10 questions remaining.

References

Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.

Lewis, P., et al. · 2020 · NeurIPS 2020

https://arxiv.org/abs/2005.11401

Filtering

Qdrant · 2026

https://qdrant.tech/documentation/search/filtering/

Controlling access at the document and field level

Elastic · 2026

https://www.elastic.co/docs/deploy-manage/users-roles/cluster-or-deployment-auth/controlling-access-at-document-field-level

Precise Zero-Shot Dense Retrieval without Relevance Labels.

Gao, L., Ma, X., Lin, J., & Callan, J. · 2022 · arXiv preprint

https://arxiv.org/abs/2212.10496

The Probabilistic Relevance Framework: BM25 and Beyond.

Robertson, S., & Zaragoza, H. · 2009 · Foundations and Trends in Information Retrieval

https://doi.org/10.1561/1500000019

Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods.

Cormack, G. V., Clarke, C. L. A., & Buettcher, S. · 2009 · SIGIR '09

https://dl.acm.org/doi/10.1145/1571941.1572114

ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT.

Khattab, O., & Zaharia, M. · 2020 · SIGIR 2020

https://arxiv.org/abs/2004.12832

Lost in the Middle: How Language Models Use Long Contexts

Liu, N.F., et al. · 2024 · TACL 2024

https://aclanthology.org/2024.tacl-1.9/

LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models

Jiang, H., et al. · 2023 · EMNLP

https://arxiv.org/abs/2310.05736

TRUE: Re-evaluating Factual Consistency Evaluation.

Honovich, O., et al. · 2022 · NAACL 2022

https://arxiv.org/abs/2204.04991

FActScore: Fine-grained Atomic Evaluation of Factual Precision in Long Form Text Generation.

Min, S., et al. · 2023 · EMNLP 2023

https://arxiv.org/abs/2305.14251

OWASP GenAI LLM Top 10 2026

OWASP GenAI Security Project · 2026

https://genai.owasp.org/resource/owasp-genai-llm-top-10-2026/

HTML Standard: Server-sent events

WHATWG · 2026

https://html.spec.whatwg.org/multipage/server-sent-events.html

Using server-sent events

MDN Web Docs · 2026

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

Efficient Memory Management for Large Language Model Serving with PagedAttention.

Kwon, W., et al. · 2023 · SOSP 2023

https://arxiv.org/abs/2309.06180

Fast Inference from Transformers via Speculative Decoding.

Leviathan, Y., Kalman, M., & Matias, Y. · 2023 · ICML 2023

https://arxiv.org/abs/2211.17192

RAGAS: Automated Evaluation of Retrieval Augmented Generation.

Es, S., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2309.15217

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.