How would you design a RAG system that answers questions over a company's internal documents?
Written by the mlprep team · Updated
Design an assistant that answers employee questions using the company's internal documents: wikis, PDFs, support tickets, and Slack threads. Walk me through the architecture end to end, from ingestion to the answer the user sees.
How to drive the interview#
Clarify before drawing boxes:
- How big is the corpus, and how fast does it change? Thousands of pages updated weekly is a different system from millions of tickets updated every minute.
- Do documents have access controls? Almost always yes inside a company, and it shapes the retrieval design.
- What does a good answer look like: a short factual answer with citations, or a synthesized summary across many documents?
- Latency budget and cost per query?
- Is "I don't know" an acceptable answer? It should be.
Then walk the pipeline: ingestion → chunking → indexing → query understanding → retrieval → reranking → generation with citations → feedback and evaluation.
- Query understanding rewrite follow-ups into standalone questions; detect intent and filters (team, product, date)
- Hybrid retrieval BM25 + dense embeddings, filtered by the user's document permissions
- Rerank cross-encoder scores the top ~50–100 candidates; keep the best handful
- Grounded generation LLM answers only from retrieved passages, with inline citations
- Answer + feedback citations shown to the user; thumbs up/down and clicks logged for evaluation
Ingestion and chunking#
Every source needs a connector that extracts clean text plus metadata: title, URL, author, last-modified time, source system, and access control list. PDFs and slide decks need layout-aware parsing; naive text extraction scrambles tables and multi-column pages.
Chunking is one of the highest-leverage decisions:
- Too large: the embedding averages several topics, so retrieval gets fuzzy, and each chunk burns context tokens.
- Too small: a chunk loses the context needed to answer, such as the heading that says which product a paragraph is about.
- A practical default is structure-aware chunking: split on headings and paragraphs, keep chunks to a few hundred tokens with small overlap, and prepend the document title and section path to each chunk before embedding.
Keep a mapping from chunk to source document and position so you can cite it and re-index it when the document changes.
Retrieval: why hybrid#
Dense retrieval (a two-tower embedding model plus an approximate nearest neighbor index) handles paraphrase: "How do I expense a flight?" matches "travel reimbursement policy". But dense embeddings are weak on exact tokens: error codes, product SKUs, people's names, internal acronyms. BM25 is the opposite.
Run both and merge, for example with reciprocal rank fusion. This is cheap and fixes a large class of "the answer was in the docs but the bot didn't find it" failures.
Reranking#
First-stage retrieval optimizes for recall over a large index, so it uses cheap bi-encoder scores. A cross-encoder reranker reads the query and passage together and is far more precise, but too slow to run over the whole index. Rerank the top ~50–100 candidates and keep the best few for the prompt. This is the same retrieval → ranking funnel used in search and recommendations.
Generation#
The prompt contains the question, the selected passages with source IDs, and instructions to answer only from those passages, cite them, and say when the passages don't contain the answer. Show citations as links in the UI. Citations are what let users verify answers and what let you debug failures.
How do you evaluate this system? Your PM wants a single number that says whether a change made it better.
Evaluate the stages separately#
One end-to-end score hides where failures come from. Measure:
- Retrieval: recall@k. Is a passage that contains the answer among the top k sent to the model? This needs a labeled set of questions mapped to their supporting passages.
- Faithfulness (groundedness): is every claim in the answer supported by the retrieved passages? This catches hallucination even when retrieval was fine.
- Answer quality: is the answer correct, complete, and actually responsive to the question?
- Abstention: when the corpus doesn't contain the answer, does the system say so instead of guessing?
Building the evaluation set#
Start with a few hundred real questions from search logs or support tickets, not questions engineers invent. Have subject-matter experts write reference answers and mark the supporting passages. Include unanswerable questions on purpose. Refresh the set as the corpus and usage change, and keep a frozen copy so results stay comparable across releases.
LLM-as-judge, carefully#
An LLM grader scales faithfulness and correctness scoring, but treat it as a measurement instrument that needs calibration:
- Check its agreement with human labels on a sample before trusting it, and re-check when you change the judge model or prompt.
- Watch for known biases: preference for longer answers, for its own model family's style, and position effects in pairwise comparisons.
- Use rubric-based, per-claim grading rather than a vague 1–10 score.
Answering the PM#
Give a small scorecard rather than one number: retrieval recall@k, faithfulness rate, answer correctness, and abstention accuracy on the frozen set, plus online signals such as thumbs-down rate, citation click-through, and escalations to a human. A change ships when it improves the target metric without regressing the others.
The system is live. What goes wrong in production, and how do you design for it?
Permissions leakage#
If retrieval ignores access controls, the assistant will happily summarize a confidential HR document for anyone who asks. Store ACLs with every chunk and filter at retrieval time using the requesting user's identity. Filtering after generation is too late, because the content has already influenced the answer. Re-sync permissions when they change, not just when content changes.
Stale answers#
When a policy page is updated, the old chunks must be replaced, or the assistant cites last year's policy with confidence. Use incremental, change-driven re-indexing from source modification events, delete chunks for deleted documents, and show the source's last-updated date next to citations. When sources conflict, prefer the more recent and more authoritative one, and say there is a conflict.
Prompt injection through documents#
Retrieved text is untrusted input. A wiki page or ticket can contain text like "ignore previous instructions and ...". Mitigations:
- Clearly delimit retrieved content in the prompt and instruct the model to treat it as data.
- Don't give the answering model tools or actions it doesn't need; an assistant that can only answer limits the damage of a successful injection.
- Monitor for answers that deviate from the citation-backed pattern.
Latency and cost#
Most latency comes from reranking and generation. Levers: cache embeddings and frequent queries, cap the number and length of passages, use a smaller model for query rewriting, and stream the answer. Track cost per answered question, not just per request.
Interview red flags#
- Jumping to fine-tuning the LLM when the problem is retrieval: the right passage never reaches the model.
- Pure vector search with no lexical component, which misses error codes, names, and acronyms.
- Ignoring document permissions, or filtering only after generation.
- Evaluating with a handful of demo questions or a single LLM-as-judge score that was never checked against human labels.
- No plan for stale or deleted documents.
Go deeper: Fine-tuning vs RAG covers when retrieval is the wrong tool; Embeddings covers how the dense retriever's representations are learned.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
RAG quality is mostly retrieval quality. Use structure-aware chunking with titles prepended, hybrid BM25 + dense retrieval filtered by user permissions, a cross-encoder reranker, and generation that answers only from cited passages and abstains otherwise. Evaluate retrieval recall, faithfulness, correctness, and abstention separately on a frozen, expert-labeled set, and design for stale documents, permission changes, and prompt injection from retrieved text.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How would you handle questions that need information from many documents, such as "summarize every incident involving service X this quarter"?
- When would you fine-tune the embedding model or reranker on your own data, and what training signal would you use?
- How would you support multi-turn conversations where the follow-up question only makes sense with the previous turn?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
Fine-tuning vs RAG: tradeoffs and when to use each
When is a large foundation model unjustified? Simple models vs LLMs.
How would you automatically detect and reduce LLM hallucinations?
How would you design a recommendation system for Reddit?