All posts
System Design Mastermind · Part 25
  • System design
  • Interview prep
  • RAG
  • AI/ML systems
  • Search

RAG assistant over company docs system design: retrieval, permissions and answers you can trust

How to design a RAG assistant over company documents in real interview order: corpus, churn and tokens per question as the numbers that matter, an API with identity from SSO and citations as data, an explainer on hybrid search and reciprocal rank fusion, ingestion and serving built in passes around a versioned index, one question walked from Slack to a cited answer, a lab on retrieval quality against tokens, latency and cost, a lab on permission filters and freshness, evals, LLM judges, rollouts and guardrails, and what happens when each part fails.

24 Oct 2026 · 34 min read · interactive

Share

The 1-minute answer

It's two halves that meet at a versioned search index. Ingestion listens for change events from Drive, the wiki and Jira (with a periodic full sync to catch misses), parses documents with tables kept whole, splits them into chunks of a few hundred tokens with a context line each, embeds only the chunks that changed, and writes them to an index that holds both keywords and vectors, plus each document's allowed users and groups. Serving takes the employee's identity from SSO, rewrites a follow-up into a standalone question, runs hybrid search with the permission filter inside it, fuses the lists, reranks ~150 candidates down to ~8, and asks the LLM to answer only from those numbered sources, citing each claim, or say it can't find it. A groundedness check runs before the answer is final, cited documents are re-checked against the source, and every answer is saved with the chunks and versions it used. Every change to prompts, chunking, embeddings or models is gated by a golden set scored on retrieval and on answers, and production runs permission probes that must never return a canary document.

How this page follows the interview

Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

New to embeddings, chunking and reranking? Foundations F18 (AI foundations: inference, RAG and agents) explains them in one page. Serving the LLM itself is Part 22; this page treats it as a gateway.

Requirements and numbers

Agree sources, permissions and the quality bar, then size the corpus, the churn and the tokens per question. Traffic is small; the corpus and the prompt are not. Change any input: each number comes with the decision it forces.

Functional

  • Ask in chat or Slack; get a short answer with citations
  • Follow-up questions in a conversation
  • Documents from several sources (Drive, wiki, Jira, HR portal)
  • Open a citation to see the exact passage
  • Thumbs up / down; "I couldn't find this" when the docs don't say

Non-functional

  • Never answer from a document the asker can't open
  • Grounded: every claim supported by a cited source
  • Edits searchable within 15 min; access removals within 5
  • First token under 1.5 s at p95
  • A cost per question, tracked

Out of scope (say it)

Taking actions (filing tickets, changing settings: the agent platform, next in this track), writing documents, public customers, training models.

Capacity calculator

Every input is an assumption 🔶: say it out loud. LLM prices are round teaching numbers for a mid-sized hosted model; check your provider. Embedding at $0.02 per million tokens is OpenAI's text-embedding-3-small price. ✅ OpenAI Jan 2024 Contextualising chunks cost $1.02 per million document tokens in Anthropic's setup. ✅ Anthropic 2024

Three rules for this estimate
  1. A day is 86,400 seconds, but questions bunch into working hours: use a peak factor of 3–5.
  2. Chunks = documents × tokens ÷ chunk size, plus ~10% overlap between neighbours.
  3. Tokens per question set the bill: fixed prompt + chunks × chunk size, on every question.
They'll push on thisAnswer out loud, then open.

Core entities and the API

A document is the unit of permission; a chunk is the unit of retrieval; an answer record ties a question to the exact chunks and versions used. What they listen for: identity from the token, citations as data, a search-only path, and change hooks.

EntityKey fieldsNote
Request
Response

Hybrid search: how two ranked lists become one

Keyword scores and vector similarities aren't on the same scale, so don't add them. Reciprocal rank fusion uses only positions: each list adds 1 ÷ (k + rank). Change the ranks (0 = not in that list) and watch the order.

Why it works

  • Agreement wins: a chunk that's decent in both lists beats one that's top in only one. That's B. ✅ Cormack et al. 2009
  • No tuning of scores: BM25 scores and cosine similarities never need normalising; ranks are enough. ✅ Elastic docs
  • k damps the top: with k = 60, rank 1 vs rank 10 is 0.0164 vs 0.0143, so one list can't dominate. A small k lets a single #1 win. 🧭
  • Then rerank: fusion decides the ~150 candidates; the cross-encoder decides the final 8. ✅ Anthropic 2024

Elasticsearch's RRF retriever defaults rank_constant to 60. Try k = 1: B, good in both lists, drops to last, because a single #1 now dominates.

They'll push on thisAnswer out loud, then open.

High-level design

Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.

They'll push on thisAnswer out loud, then open.

Walk one question, box by box

From a Slack question to a cited answer, then a question the docs can't answer, an edit, a permission removal and a new embedding model. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.

On the wire

Arrows show who calls whom, and the numbers give the order. Replies go back along the same line.

Keeping the index fresh and safe

Ingestion is half the system and most of the bugs. These six details are what separates a demo from a product.

    Data and database choices

    The index is a derived copy: rebuildable from documents and stored embeddings. Permissions travel with every chunk; groups are expanded at query time; every answer is saved with what it used.

    DataPickConsideredWhy not those

    The one call to know: retrieve()

    # One question → a few chunks this user may read.
    # Illustrative; field names are made up.
    def retrieve(question, history, user):
        q = rewrite(question, history)            # small model
        principals = [user.id] + groups(user.id)  # cached ~60 s
        acl = {"terms": {"allowed": principals}}  # filter INSIDE
        kw  = bm25(q, filter=acl, size=150)
        vec = knn(embed(q), filter=acl, k=150)
        cands = rrf([kw, vec], k=60)[:150]        # Σ 1/(60+rank)
        top = rerank(q, cands)[:8]                # cross-encoder
        if not top or top[0].score < ABSTAIN:
            return []                             # say "not found"
        return top

    Illustrative. The filter sits inside both searches, not after them. 🧭

    Why "filter after" fails

    1. Approximate indexes return a fixed number of neighbours, then the filter drops some. ✅ pgvector docs
    2. pgvector's own example: with HNSW's default ef_search of 40 and a filter that matches 10% of rows, about 4 rows come back. ✅ pgvector docs
    3. Company docs are worse: a typical employee may read a few percent of everything. ❓ assume 5%
    4. Fixes: filter inside the search (iterative scans, filtered kNN in a search engine), partition by tenant, or partial indexes for a few values. ✅ pgvector docs

    More database questions

    They'll push on thisAnswer out loud, then open.

    Deep dive: retrieval quality vs tokens, latency and cost

    If the chunk that answers the question isn't in the prompt, no model and no prompt can fix it. But every chunk you add is paid for on every question. The chart shows the share of questions that miss their chunk as you put more chunks in the prompt (top), and the cost (bottom). Pick a preset, then change the switches and numbers.

    Teal: questions whose answer-bearing chunk isn't in the prompt. Dashed: your target. Apricot: cost per 1,000 questions; dashed: budget. Dot: your setting. Anchored on Anthropic's measured top-20 failure rates; the curve's shape is a teaching assumption. 🔶

    The rules this lab teaches

    1. Recall is cheap in the index, expensive in the prompt. Fetch many candidates, keep few. 🧭
    2. Keywords and context fix different misses. Contextual embeddings: 5.7% → 3.7%; plus contextual BM25: 2.9%. ✅ Anthropic 2024
    3. Reranking beats stuffing: 150 → 20 reranked cut failures to 1.9%. In the lab, reranking to 8 costs about 44% less than sending 20. ✅ Anthropic 2024
    4. The reranker can't rescue what wasn't fetched, and past a point more candidates only add latency. 🔶

    Real numbers to quote

    Anthropic: 20 chunks beat 10 and 5 in their tests; a knowledge base under ~200,000 tokens can skip RAG and go whole into the prompt. ✅ Sep 2024

    Uber Genie: better parsing (tables kept whole), metadata and an agentic retrieval step raised acceptable answers by 27% and cut incorrect advice by 60% (relative). ✅ May 2025

    Lost in the Middle: models use information at the start or end of a long context best, and the middle worst. ✅ 2023

    They'll push on thisAnswer out loud, then open.

    Deep dive: permissions and freshness

    The assistant reads everything so it can answer anyone; it must never answer anyone from everything. And it must forget access faster than it learns content. The chart shows the chance a question gets enough chunks the user may read when you filter after the search. Pick a preset, then change the numbers.

    Where the permission filter runs

    Teal: P(at least the chunks you need are ones this user may read) when filtering after fetching K candidates. Dashed: 99%. Dot: your K. Binomial model; teaching numbers. 🧭

    Three rules, in order

    1. Filter inside the search on allowed principals stored with every chunk; never after, never in the prompt. ✅ OWASP LLM08 2025
    2. Access changes beat content changes: their own events, their own lag metric, and a re-check of cited docs at answer time. 🧭
    3. Prove it continuously: canary documents and test users that must never see them, probed every few minutes. 🧭

    Why sources make this hard

    Google Drive: notifications carry no content or metadata; you fetch changes with a cursor. Changes channels last at most a week and must be renewed. ✅ Drive API docs

    Each source has its own model: Drive shares, wiki spaces, Jira projects and HR records differ. Map each to principals at ingestion, not at query time. 🧭

    They'll push on thisAnswer out loud, then open.

    Deep dive: evals, rollouts, cost and guardrails

    A new chunking rule, embedding model or prompt can make one slice worse while the average improves, and nothing errors. Ship RAG changes like risky deploys: measured on a golden set, tried on a few users, and reversible in seconds.

    The release ladder

      LLM-as-judge for RAG: useful, with limits

      Prompt, RAG or fine-tune?

      Tick what's true for the feature.

      A fine-tuned model can't forget a deleted document or respect permissions, so company knowledge belongs in retrieval. 🧭

      Cost and latency per question

      1. Fewer, better chunks: the biggest lever (the lab's rerank-to-8 preset). 🧭
      2. Cache the fixed prefix: system prompt and rules first, identical on every call, so the provider's prompt cache hits. ✅ OpenAI docs
      3. Route by step: a small model rewrites follow-ups; the strong one answers. 🧭
      4. Cache answers only per permission set, invalidated when a cited doc changes. 🧭
      5. Guardrails cost time: DoorDash runs a cheap similarity check and calls the LLM evaluator only when it flags. ✅ DoorDash 2024

      Guardrails, in layers

      1. Retrieved text is untrusted input. OWASP's example: white text in a CV telling a screening model to recommend the candidate. Strip hidden text; flag instruction-like chunks. ✅ OWASP LLM08
      2. No exfiltration paths: don't render links or images to unknown domains. Slack AI (Aug 2024): a planted public message made answers include a link carrying private data. ✅ via Willison, third-party research
      3. Grounded or held: DoorDash's guardrail cut hallucinations by 90% and severe compliance issues by 99%. ✅ DoorDash 2024
      4. Fail mode per surface, decided in advance. 🧭
      They'll push on thisAnswer out loud, then open.

      A document's lifecycle

      Every document moves through ingestion as a small state machine. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.

      NormalSomething went wrongGreyed out: not possible from the current state.

      Edge cases interviewers love

      They'll push on thisAnswer out loud, then open.

      Failure, monitoring and recovery

      A RAG assistant fails loudly (no answers) and quietly (wrong, stale or leaked answers with green graphs). The quiet ones matter more. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.

      Tracing it back: a healthy answer vs a slow, held one

      Every span carries the question id, index version and prompt version. Times are seconds from arrival. In the bad trace the reranker times out, the fallback sends 30 chunks, and the grounding check holds the answer.

      How one failure becomes three

      What you'd alert on (SLOs)

      SignalTargetAlert

      Incident playbook

        The toolkit

        Name the technique, then say where it goes in this design.

        They'll push on thisAnswer out loud, then open.

        Making it fast, and who owns what

        Retrieval takes a few hundred milliseconds; the prompt's length sets the first token, the answer's length sets the rest, and the pipeline sets freshness. Bars are sizing estimates, not measured figures.

        TeamOwnsPaged when…

        Senior follow-ups beyond the happy path

        Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.

        Practice ladder

        Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.

        Sources

        Checked October 2026. Retrieval numbers come from Anthropic's Contextual Retrieval post (19 Sep 2024; its 5.7% → 3.7% → 2.9% → 1.9% failure rates are on Anthropic's own benchmarks, not your documents). Company examples are as published: DoorDash (17 Sep 2024) and Uber's Genie (29 May 2025). Mechanisms and limits come from papers (RAG 2020, HNSW 2016, RRF 2009, Lost in the Middle 2023, Ragas 2023, LLM-as-a-judge 2023) and official docs (Elasticsearch RRF, pgvector 0.8 filtering via a docs mirror, Google Drive push notifications, Claude citations, OpenAI embeddings pricing from Jan 2024 and prompt caching). The Slack AI issue is third-party security research (PromptArmor, Aug 2024) as summarised by Simon Willison, with Slack's response. OWASP's LLM08:2025 is the reference for vector-store risks. Techinterview.org is a third-party prep site, used only to cross-check what interviewers expect. Both labs use rounded teaching values; the miss-rate curve's shape and every latency are assumptions.

        System Design Mastermind · AI / ML systems

        Series home

        All of AI / ML systems

        8 published · 1 comingLLM and ML systems, where interviews are heading.

        22

        LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changes

        Chat API (auth, token limits, history, safety, SSE with resumable event ids) → router picks model (easy turns to a small one), version (registry canary split) and a replica with the prefix cached → vLLM-style engines batch continuously up to the time-per-token target. Admit by priority because GPUs take minutes to add; ship every model change through evals, shadow and canary, with rollback by one number.

        34 min · interactive Preview
        25

        RAG assistant over company docs system design: retrieval, permissions and answers you can trust

        Ingestion (change events + full sync → parse → chunk with a context line → embed only changed chunks) fills a versioned index of keywords, vectors and allowed principals. Serving rewrites the question, runs hybrid search with the permission filter inside it, reranks 150 → 8, answers only from numbered sources, checks grounding and re-checks cited docs. A golden set gates every change.

        You're reading this Preview
        28

        AI agent platform system design: tools, durable runs, approvals and agents you can trust

        A durable orchestrator runs each agent as workflow code: pin the version, call the model through a caching gateway, record every step so crashes resume. The model only proposes tool calls; a tool gateway validates, authorizes with the user's own token, adds idempotency keys and parks irreversible steps for approval. Budgets stop runaways; end-state evals with k tries gate every release.

        35 min · interactive Preview
        31

        Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanish

        Validate the file, split it into ~20-minute shards, lease them to GPU workers on spot that load the model once and run hundreds of rows at a time with the shared prompt cached. Each attempt writes its own file; one conditional commit per shard makes output exactly-once. Golden set and canary shard gate every new version.

        34 min · interactive Preview
        34

        Content moderation pipeline system design: hash matching, classifiers, LLM checks and human review at a billion items a day

        Hash at upload against known-bad lists, score every policy with small classifiers in ~50 ms, two lines per policy: remove above, allow below, and the band between goes to an LLM that reads the policy, then a review queue ordered by severity × reach × likelihood. Every decision logged with a reason, appealable, and gated by golden set → shadow → canary.

        34 min · interactive Preview
        35

        Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B tests

        Several sources (two-tower ANN search, like-your-likes, trending, a fresh pool) retrieve a few thousand items; a light ranker keeps a few hundred; a heavy multi-task ranker predicts finish, like, share and skip; a value model and re-rank add diversity, in ~200 ms. Events stream back to features in seconds and to incremental training in minutes; models ship via interleaving and A/B tests.

        34 min · interactive Preview
        36

        LLM evaluation and guardrails platform system design: judges, guard latency, paired eval gates and safe rollouts

        Every product calls an AI gateway: versioned config, input guards (PII mask, a small injection classifier, an LLM judge only when unsure), output guards on streamed chunks, a trace per request. Off the path: sampled traces judged online, people calibrating the judges, failures turned into regression tests, and every change gated by a paired eval with error bars, then shadow, canary and A/B.

        33 min · interactive Preview
        37

        AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals

        Three shapes, one backend: a small self-served Tab model per keystroke; an agent loop with a context engine (grep plus an optional index), a cached prompt to a frontier model, text-anchored edits or a fast apply model, permissions and an OS sandbox; and background agents in a container per task that open a PR. An eval harness gates every change on pass^k.

        34 min · interactive Preview
        ··

        Feature store and training platform

        Coming next

        More posts