What it is
Retrieval-augmented generation (RAG) answers a question in two stages. First it retrieves passages relevant to the question from your own data, typically chunks in a vector index (often combined with keyword search). Then it generates an answer with a language model whose prompt contains those passages and an instruction to answer from them, citing sources.
Why it exists
A model knows what was in its training data up to a cutoff date. It has never seen your handbook, tickets or contracts, and those change constantly. Fine-tuning is slow to update, does not reliably teach facts, and cannot point to a source. RAG keeps knowledge in an index you control: update a document, re-index it, and the next answer reflects it, with a citation the user can check. It also lets you enforce permissions at retrieval time.
How it works
- Embed the question with the same embedding model used to index the documents. Optionally rewrite it first (resolve “it” from the conversation, expand acronyms).
- Retrieve candidates: vector search for meaning, keyword search (BM25) for exact terms, run in parallel and fused (reciprocal rank fusion is a common, parameter-light choice). Apply metadata filters such as tenant and permissions inside the search.
- Rerank the top few dozen candidates with a cross-encoder or similar model that reads question and passage together, and keep the best handful.
- Build the prompt: instructions (answer only from the sources, cite ids, say when the sources are insufficient), the passages with ids and titles, the conversation if needed, then the question.
- Generate, usually streamed to the user.
- Post-process: validate that cited ids were actually retrieved, turn them into links, log everything for evaluation.
Latency. Embedding and search take tens of milliseconds, a reranker roughly a hundred; generation takes seconds and grows with prompt size (prefill) and answer length (decode). Throughput is set by the model deployment’s concurrency and quota, not by the index.
When to use it
- Question answering over private or frequently changing documents: internal knowledge bases, support content, product documentation, policies.
- When answers must cite sources or respect per-user permissions.
- When the knowledge base is too large to put in every prompt.
When not to
- Structured questions (“revenue by region last quarter”): query the database (possibly via a model that writes the query), do not retrieve text chunks.
- Teaching a model a style, format or skill: that is what prompting and fine-tuning are for.
- A small, stable corpus that fits comfortably in the prompt, especially with prompt caching: retrieval may add more complexity than it saves.
- Questions needing several dependent lookups or comparisons: single-shot retrieval often fails; see agentic RAG.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Larger top-k | Higher chance the right chunk is included | Longer prefill, higher cost, more noise |
| Reranker | Better precision in the final few chunks | ~100 ms per request, another model to run |
| Hybrid search | Exact terms and paraphrases both found | Two indexes, a fusion step to tune |
| Strict grounding (“only from sources”) | Fewer hallucinations | More “I don’t know” when retrieval misses |
| Smaller chunks | Precise passages | Lost surrounding context; may need neighbour expansion |
Alternatives
- Long-context prompting: put the whole (small) corpus in the prompt, ideally with prompt caching. Simple, but cost and latency scale with corpus size.
- Fine-tuning: adapts behaviour and style; not a reliable way to add or update facts.
- Text-to-SQL or API tools for structured data.
- Agentic RAG: let the model decide when and what to retrieve, at the cost of more model calls.
Failure modes
- Retrieval miss: vocabulary mismatch, bad chunk boundaries, acronyms, missing documents. The model answers wrong or says it does not know.
- Stale or unauthorised content: deletes and permission changes not propagated to the index.
- Context overload: too many chunks; relevant facts in the middle get less attention, irrelevant ones mislead.
- Unfaithful answers: the model adds facts not in the sources or misreads them; citations look valid but do not support the claim.
- Prompt injection via documents: retrieved text containing instructions (“ignore previous instructions…”). Treat retrieved content as untrusted data.
- Generation bottleneck: traffic grows, the model deployment saturates while retrieval idles.
In production
Log the question, retrieved chunk ids and scores, the prompt size, the answer and the citations for every request. Build an evaluation set of real questions with known supporting passages, and track retrieval metrics (is the right chunk in the top-k?) separately from answer metrics (faithfulness to sources, relevance to the question). Re-run it on every change to chunking, embedding model, retrieval settings, prompt or model. In .NET, Microsoft.Extensions.AI provides the chat and embedding abstractions, and Microsoft.Extensions.VectorData offers a common interface over vector stores; Azure AI Search and others support hybrid search with semantic reranking as a managed feature.
Common misconceptions
- "RAG stops hallucinations." It reduces them when retrieval works; when it misses, the model may still improvise.
- "Bigger context windows make retrieval obsolete." Cost, latency and attention over long contexts still favour sending little, relevant text.
- "Use the best LLM and quality follows." Retrieval quality usually limits answer quality first.
- "The vector database is the performance problem." Generation dominates latency and capacity.
- "Citations prove correctness." They make answers checkable; you still have to check them, at least in evaluation.
Interview angle
For “design a document Q&A assistant”, cover both pipelines: ingestion (chunk, embed, index, keep in sync, permissions) and query (rewrite, hybrid retrieve, rerank, grounded prompt, generate, cite). Give a latency budget per stage and note that generation dominates. Estimate tokens per request and translate traffic into model quota. Explain how you would evaluate retrieval and answers separately and how you handle permissions and prompt injection from documents.
Model assumptions
The simulation is a simplified model, not a benchmark. The RAG API is the traffic source (Poisson arrivals). The orchestrator calls its dependencies one after another: embedding (~30 ms), retrieval, reranker (~120 ms), then the LLM (~2.5 s without context, ~2.8 s with five chunks, ~4.3 s with forty; lognormal, cv 0.4), which has 24 concurrent slots and a short waiting line. Retrieval is vector search alone (~20 ms) until the hybrid step; from then on a Hybrid Retriever queries the vector index and the keyword index (~15 ms) at the same time and answers when both are back, so it costs the slower search. Rank fusion itself is not modelled. Retrieval quality, prompt contents and citations are scripted illustrations; the engine does not model answer quality. The prompt-size effect on generation time is an illustrative assumption, not a measurement.