Home / AI Architecture & System Design / RAG & Retrieval
Walk me through how you'd build a RAG system over a company's internal docs.
30-second answer
Offline: load and parse docs keeping structure, chunk by section with overlap, prepend title/section headers, embed, store with metadata (source, date, ACL). Online: rewrite the query with conversation context, run hybrid retrieval (BM25 + vectors) with permission filters, rerank top ~50 to ~5, build a prompt with delimited, ID-tagged chunks and instructions to cite and to say when the answer isn't present, then generate. Wrap it with an eval set measuring recall@k and faithfulness, plus logging and feedback.
Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.
New to these terms? 17 terms on this page are explained in the glossary
0–5 min Functional requirements
"Build RAG over internal docs" hides most of the hard parts: many source systems, permissions, freshness and messy formats. Surface them early.
You Which sources? One wiki, or several systems?
Interviewer Confluence, Google Drive and Jira to start. Slack later.
You Does everyone see everything, or do we need to respect each system's permissions?
Interviewer Permissions must be respected. HR and finance content is restricted.
You Who asks, and what kind of questions? Policy lookups, engineering runbooks, project status?
Interviewer All employees. Mostly "how do I…" and "what's our policy on…", plus engineers searching runbooks and past incidents.
You Should answers cite sources?
Interviewer Yes. People need to check the original.
You How fresh does it need to be?
Interviewer An edited page should show up in answers within minutes. A permission removal should apply even faster.
| # | Functional requirement | Why it matters |
|---|---|---|
| F1 | Answer questions in natural language from Confluence, Drive and Jira, with citations linking to the source | Trust and verification |
| F2 | Only use content the asking employee can open in the source system | Restricted HR, finance and legal content |
| F3 | Reflect edits, new documents and deletions within minutes | Stale answers erode trust fast |
| F4 | Handle follow-up questions in a conversation | Natural usage |
| F5 | Say clearly when the answer isn't in the documents, and show the closest sources | Better than a confident guess |
| F6 | Collect feedback and let admins add or pause sources | Operability |
Out of scope: writing back to source systems, Slack (phase two), and summarizing whole projects or spaces.
5–10 min Non-functional requirements and estimates
You Is there any tolerance for permission mistakes?
Interviewer None. One leaked salary document and the project is shut down.
You Then permission checks happen at retrieval time, before the model sees anything, with automated leak tests on every release. I won't rely on the prompt for that.
| Requirement | Target | What it forces in the design |
|---|---|---|
| Permission correctness | Zero leaks; permission removal applied ≤ 5 min | ACL metadata on every chunk, filter inside the search, event-driven ACL sync |
| Freshness | Content edits searchable ≤ 10 min | Webhooks and change cursors, incremental indexing |
| Latency | First text ≤ 2 s p95, streamed | Parallel retrieval, small models for rewriting |
| Quality | Recall@5 ≥ 90%, groundedness ≥ 95% on the evaluation set | Hybrid search, reranking, citation checks |
| Availability | 99.9% during working hours | Replicated index; search-only fallback |
| Cost | Embedding and LLM costs predictable and attributable | Skip re-embedding unchanged chunks; usage per team |
Back-of-envelope estimates:
- Corpus: 2M documents averaging ~3,000 tokens → ~6B tokens. At ~500-token chunks with some overlap, that's ~12–13M chunks.
- Vector storage: 12M × 1,024 dimensions × 4 bytes ≈ 49 GB in float32, or ~12 GB with int8 quantization. That's too big to treat casually: plan for a sharded vector index or quantization with re-scoring.
- Initial embedding: 6B tokens. At an illustrative $0.02–0.13 per million tokens, that's ~$120–800 once. Throughput, not cost, sets the backfill time.
- Churn: ~1% of documents change per day → 20,000 documents, ~60M tokens/day to re-embed. Skipping chunks whose content hash hasn't changed cuts this a lot.
- Queries: 20,000 employees × ~5 questions/day = 100,000/day; ~6 queries/s at peak. Retrieval load is light; LLM cost dominates.
10–18 min High-level design
You Two pipelines: ingestion keeps a hybrid index in sync with sources, content and permissions included. The query path rewrites, retrieves with permission filters, reranks, answers with citations and checks the citations.
Scroll sideways to see the whole diagram.
Components:
- Connectors: one per source system. Each subscribes to change events (webhooks) and also keeps a change cursor so nothing is missed if a webhook drops.
- Ingestion pipeline: fetch, parse (keep headings, tables and code blocks), chunk with breadcrumbs, embed and upsert. Runs as queue-driven workers.
- Hybrid index: vectors, a BM25 inverted index and metadata per chunk:
doc_id,source,url,title_path,updated_at,acl_groups,content_hash. - Query service: rewrites the question, resolves the employee's groups, runs filtered hybrid search, reranks and builds the prompt.
- Answer LLM: streams an answer with source IDs; a citation checker verifies claims against cited chunks.
- Logs and evaluation: traces of retrieved IDs, scores and latency; a golden set run in CI.
One question, end to end:
Scroll sideways to see the whole diagram.
API sketch:
POST /v1/ask { question, conversation_id? }
→ SSE: delta | citations [{ doc_id, title, url, snippet }] | not_found | done
POST /v1/feedback { answer_id, rating, comment }
Internal:
POST /index/upsert { doc_id, version, chunks: [{ idx, text, title_path, hash }], acl_groups }
POST /index/delete { doc_id }
POST /index/acl { doc_id, acl_groups } # permission-only update, no re-embedding
Note the separate ACL endpoint: a permission change shouldn't require re-embedding the document.
How it works: a worked example
A study aid: one question traced through the running system, and one document change traced through ingestion, with the actual data at each step.
Part 1 · A document changes. At 10:02 an HR partner edits the Confluence page "Parental leave policy (US)" and removes the all-employees group so only hr-us can see a draft section.
- Confluence sends a webhook:
{ "event": "page_updated", "page_id": "CF-88412", "version": 37 }. The connector also keeps a change cursor, so a missed webhook is caught within 5 minutes. - The connector fetches the page and its permissions and puts a job on the ingestion queue:
{ "doc_id": "confluence:CF-88412", "version": 37, "source": "confluence",
"title": "Parental leave policy (US)", "acl_groups": ["hr-us"],
"url": "https://wiki.example.com/x/88412", "updated_at": "2026-11-16T10:02:11Z" }
- A worker parses the HTML into sections, chunks by heading (~500 tokens) and hashes each chunk. Of 9 chunks, 2 changed; only those 2 are re-embedded. All 9 get the new
acl_groups, which is a metadata-only update. - The index now holds, per chunk:
text,vector,title_path("Parental leave policy (US) > Eligibility"),acl_groups,content_hash,version. Searchable by 10:04.
Part 2 · A question. At 10:30 Dev, an engineer in groups eng, all-employees, us-staff, asks: "How many weeks of parental leave do US employees get?"
- The query service resolves Dev's groups from the identity provider (cached for 5 minutes) and rewrites the question (first turn, so no rewrite needed).
- Hybrid search with a permission filter inside the search, not after it:
{ "query": "parental leave weeks US employees",
"filter": { "acl_groups": { "any_of": ["eng", "all-employees", "us-staff"] },
"status": "published" },
"k": 50 }
The draft section restricted to hr-us can't appear in Dev's candidates at all.
- The reranker keeps 5 chunks. The prompt contains them as
<doc id="confluence:CF-88412#2" title="...">blocks plus instructions to cite and to say "I couldn't find this" when unsupported. - The streamed answer: "US employees get 16 weeks of paid parental leave [1]..." followed by a
citationsevent with titles and URLs. - A citation checker compares each sentence with its cited chunk; all pass.
- The trace records the retrieved chunk IDs, scores, Dev's group set hash (not the groups themselves), latency and tokens.
Where each piece runs:
| Component | Runs as | Example technology | Sizing (12–13M chunks, ~6 queries/s peak) | If it fails |
|---|---|---|---|---|
| Connectors | One service per source, scheduled + webhook-driven | Custom or open-source connectors | 20k changed docs/day | Cursor catch-up on restart; nothing lost |
| Ingestion queue + workers | Queue-driven workers | SQS/Kafka + container workers | Burst to 100k docs/hour during backfills | Dead-letter queue; the old version stays searchable |
| Embedding | Batch API calls or one GPU | Hosted embeddings or self-hosted model | ~60M tokens/day of churn | Retry with backoff; index lags but serves |
| Hybrid index | Sharded search cluster | OpenSearch/Elasticsearch, or a vector DB + keyword index | ~49 GB float32 vectors (≈12 GB int8) across shards | Replicas; keyword-only fallback |
| Identity lookup | Cached call to the IdP | Okta/Entra ID groups API | Cached 5 min | Fail closed: no groups means no restricted results |
| Query service + LLM | Stateless service + model API | Model gateway | ~6 req/s | Return search results without a generated answer |
When permissions change: a removal is applied as a metadata update within minutes (no re-embedding), and a nightly reconciliation compares every document's ACL in the index with the source system to catch anything the events missed.
18–32 min Deep dive
You The areas with the most risk are ingestion and freshness, retrieval quality on messy enterprise content, and grounded generation. Permissions are a deep topic of their own; I'll cover them briefly here.
Interviewer Start with ingestion. How do you keep two million documents in sync?
Deep dive 1 · Ingestion and freshness
Scroll sideways to see the whole diagram.
- Change detection: webhooks give low latency, and per-source change cursors (for example "modified since T") catch anything webhooks miss. A nightly reconciliation compares source document lists with the index to catch drift and deletions.
- Queue-driven workers: events go onto a queue, so bursts (someone bulk-editing a space) don't overwhelm the embedder. Workers are idempotent: processing the same version twice changes nothing.
- Skip unchanged chunks: each chunk stores a hash of its text. On an edit, re-chunk the document, compare hashes, and re-embed only the chunks that changed. A typo fix re-embeds one chunk, not forty.
- Deletes and permission changes are fast paths: a delete removes all chunks for the document right away; a permission change updates ACL metadata without touching embeddings.
- Parsing quality matters more than most tuning: convert tables to Markdown with header rows kept, keep code blocks intact, drop navigation and boilerplate, and record the heading path for every chunk.
- Failures: documents that fail parsing go to a dead-letter queue with the error, and a dashboard shows sources with high failure rates.
Interviewer Now retrieval. Enterprise content is full of duplicates and outdated pages. How do you get good results?
Deep dive 2 · Retrieval and ranking
- Query rewriting: turn follow-ups into standalone questions, and expand internal acronyms using a glossary ("PTO" → "paid time off").
- Hybrid search: BM25 for exact terms (project codenames, ticket IDs, error messages) plus vectors for paraphrase, merged with Reciprocal Rank Fusion.
- Permission filter inside the search: the query carries the employee's resolved groups; only chunks whose
acl_groupsintersect are candidates. - Metadata boosts: prefer recently updated documents and authoritative spaces (official HR policy pages over someone's old notes). Demote archived spaces.
- Deduplicate: many near-identical copies of a page exist. Collapse chunks with near-duplicate text before reranking so five copies don't crowd out other sources.
- Rerank and expand: a cross-encoder picks the best 5 of ~50; for each, include the parent section so the model sees enough context.
Deep dive 3 · Grounded answers and citations
- Prompt: sources in delimited, numbered blocks; the model must cite a source number for every factual claim and must say so when the sources don't answer the question.
- Citation check: split the answer into claims and check each against its cited chunk with a small entailment model or LLM judge. Drop or flag unsupported claims.
- Conflicts: when sources disagree, prefer the newer and more authoritative one, but show both: "The 2024 travel policy says X; an older page says Y."
- Not found: if no chunk passes the relevance threshold, answer "I couldn't find this" and show the three closest documents. This is better for trust than a guess.
Deep dive 4 · Permissions (briefly)
Groups are resolved from the identity provider at query time and cached for a few minutes. Each chunk carries the source's ACL as group IDs, and the search filters on them. An event-driven ACL sync plus nightly reconciliation keeps them current. Highly sensitive sources get a final permission re-check against the source API before generation. Automated leak tests run synthetic low-privilege users against restricted documents on every release.
32–37 min Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Change detection | Webhooks + cursors + nightly reconcile | Periodic full re-crawl | Minutes of freshness without re-reading 2M documents |
| Re-embedding | Only changed chunks (by hash) | Whole document on any edit | Big savings on large, frequently edited pages |
| Permissions | Filter inside retrieval | Filter after retrieval, or trust the prompt | Post-filtering can return too few results; prompts aren't security |
| Vector storage | int8 quantization + re-scoring | float32 everywhere | ~4× less memory with negligible recall loss |
| Ranking | Hybrid + rerank + recency/authority boosts | Vectors only | Codenames and IDs need exact match; duplicates need demoting |
| Answering | Cite-or-abstain with a citation check | Free-form answers | Trust; errors are visible and measurable |
Build first: one source (Confluence), permission filtering, hybrid search with citations, and the golden set with leak tests. Then add Drive and Jira, the citation checker, and boosts.
37–40 min Wrap-up and likely follow-ups
Close with: "Connectors stream changes into an idempotent ingestion pipeline that re-embeds only changed chunks and updates permissions separately. Queries are rewritten, searched with hybrid retrieval filtered by the employee's groups, reranked and answered with checked citations. Freshness, permission correctness and answer quality each have numbers and tests."
Likely follow-ups:
- How do you handle 300-page PDFs and slide decks? Layout-aware parsing, per-page or per-section chunks, keeping slide titles as headings, and OCR for scanned documents.
- How would you add Slack? Chunk by thread rather than message, respect channel membership as ACLs, and weight it lower than official documentation.
- How do you scale to 50M chunks? Shard the index by source or hash, quantize vectors, keep BM25 in a search engine cluster, and cache embeddings of frequent queries.
- What if two teams want different ranking? Per-team boosts layered on the same index rather than separate indexes.
What interviewers listen for
- Treating ingestion, freshness and deletes as first-class problems.
- Permissions enforced in retrieval, with a plan for revocations.
- Concrete retrieval improvements for enterprise content: rewriting, hybrid search, deduplication, boosts.
- Citations that are checked, and a clear "not found" behaviour.
Red flags
- A one-off batch job that embeds everything once.
- Ignoring deletions and permission changes.
- "The LLM will only use documents the user can see."
Discussion
Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.