Course contents

16. AI System Design Lesson 4 of 10

Retrieval-Augmented Generation

Follow a question through embed, retrieve, rerank and generate: grounded prompts, citations, retrieval failures, context limits and where latency goes.

18 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • RAG puts retrieved, current facts into the prompt instead of into the model.
  • Flow: embed the question, retrieve top-k, rerank, build a grounded prompt, generate, validate citations.
  • Retrieval costs tens of milliseconds; generation costs seconds and sets throughput.
  • Most bad answers are retrieval misses; hybrid search and reranking fix many of them.
  • More context is slower and costlier and not reliably better.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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

  1. Embed the question with the same embedding model used to index the documents. Optionally rewrite it first (resolve “it” from the conversation, expand acronyms).
  2. 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.
  3. Rerank the top few dozen candidates with a cross-encoder or similar model that reads question and passage together, and keep the best handful.
  4. 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.
  5. Generate, usually streamed to the user.
  6. 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. The model has never seen your documents

    Employees ask an internal assistant: *“How many days of parental leave do we get?”* The model was trained on public data up to its cutoff date. It has never seen your HR handbook, so it either says it does not know or, worse, produces a plausible number from other companies’ policies.

    The call itself works fine: ~2.5 s, no errors. The problem is not the plumbing. The model is missing the facts, and fine-tuning is a poor way to add facts that change every quarter.

    Scene: The RAG API sends questions straight to the LLM through the orchestrator. Answers take about 2.5 seconds, but the model has no access to company documents.

    Key idea: A model only knows its training data. Your private, changing facts have to be put in the prompt.

  2. 2. Search first, then ask

    Retrieval-augmented generation adds a search step. The orchestrator embeds the question with the same embedding model that indexed the documents (~30 ms), asks the vector index for the top-k closest chunks (~20 ms), and only then calls the LLM.

    The scripted packets show the order: embed → search → generate. Every simulated request now takes that path too. The documents were chunked and indexed beforehand by the embedding pipeline.

    Scene: The orchestrator now embeds each question, retrieves the five closest chunks from the vector index and then calls the LLM.

    Key idea: RAG = embed the question, retrieve the top-k chunks, then generate with them in the prompt.

  3. 3. Build the prompt

    The retrieved chunks go into the prompt, each with an id: *“Answer only from the sources below. Cite the source id for every claim. If the sources do not answer the question, say so.”* Then the five chunks, then the question.

    The scripted packets show five chunks arriving and one larger request leaving for the LLM. Five chunks of ~400 tokens add ~2,000 prompt tokens, which the model has to read before it writes (prefill). In this model generation goes from ~2.5 s to ~2.8 s (illustrative).

    Scene: Scripted: five retrieved chunks arrive at the orchestrator, which assembles them with instructions and the question into one prompt for the LLM. Generation takes slightly longer because the prompt is longer.

    Key idea: The prompt grounds the model: sources with ids, an instruction to cite them, and permission to say “I don’t know”.

  4. 4. Where the time goes

    Compare P50 with the first step. Embedding and vector search together add ~50 ms of work plus a few network hops: a few percent of the total. The bigger increase comes from the longer prompt the model has to read.

    That is why RAG latency work starts at the model (prompt size, output length, model choice, streaming) and not at the vector index. The embedding model and the index are nearly idle at this traffic.

    Scene: Latency breakdown: about 30 ms to embed, 20 ms to search and 2.8 seconds to generate. Retrieval adds only a few percent to the total.

    Key idea: Retrieval costs tens of milliseconds; generation, and the prompt size it depends on, costs seconds.

  5. 5. Answers with sources

    The model answers *“20 days [hr-policy#4]”*. Before the answer goes out, the orchestrator checks that every cited id is one of the chunks it actually retrieved, drops citations that are not, and turns the valid ones into links to the source document.

    Citations make answers checkable for users and measurable for you: you can evaluate whether the cited chunk really supports the claim. They do not guarantee correctness; the model can still misread a source.

    Scene: Scripted: the LLM’s answer with a citation returns to the orchestrator, which validates the cited chunk id against the retrieved set before the answer and its source link reach the employee.

    Key idea: Ask for citations by chunk id, validate them against what was retrieved, and link them for the user.

  6. 6. Retrieval misses, the answer fails

    Someone asks *“How much PTO do I get?”* The handbook says annual leave, the question says PTO, and the top-5 chunks are about the PTO *request form* and travel policy. The model, told to answer only from sources, says it does not know or answers the wrong question.

    Most bad RAG answers are retrieval failures, not model failures. Typical causes: vocabulary mismatch, chunks cut in the wrong place, acronyms and product codes that embeddings blur, or the right document missing from the index.

    Scene: Scripted: a question using different words than the documents retrieves irrelevant chunks, so the LLM cannot answer it from the sources.

    Key idea: If the right chunk is not in the top-k, no model can answer correctly. Measure retrieval separately.

  7. 7. Hybrid search and reranking

    Hybrid search runs a keyword query (BM25) in parallel with the vector query and fuses the two lists, for example with reciprocal rank fusion. Keywords catch exact terms and codes; vectors catch paraphrases. A reranker (a cross-encoder model that reads question and chunk together) then reorders the top ~50 candidates and keeps the best 5.

    Here a Hybrid Retriever sends both queries at the same moment and waits for the slower one, so the keyword search adds almost nothing: retrieval costs the slower of the two searches (~20 ms), not their sum. The reranker adds about 120 ms per request: worth it when it puts the right chunk in the prompt, and still small next to generation.

    Scene: Each question is embedded, then a Hybrid Retriever queries the vector index and the keyword index at the same time and fuses the results; a reranker picks the best five chunks, and the LLM gets them. Retrieval costs the slower search, not both; the reranker adds about 120 ms.

    Key idea: Hybrid retrieval plus a reranker fixes most vocabulary misses for a fraction of the generation time.

  8. 8. Just send more chunks?

    Context windows are large now, so why not send the top 40 chunks instead of 5? That is ~16,000 prompt tokens. The model reads all of them before writing: generation here goes from ~2.8 s to ~4.3 s (illustrative), and you pay for every input token on every request.

    Quality does not reliably improve either. Models use information in the middle of long contexts less reliably than at the start or end, and irrelevant chunks invite wrong answers. Better retrieval beats bigger prompts.

    Scene: The orchestrator sends 40 chunks instead of 5. Prompts grow to about 16,000 tokens and median latency rises by more than a second.

    Key idea: More context costs latency and money on every request and often dilutes the answer. Retrieve well, send little.

  9. 9. The LLM is the capacity limit

    Back to 5 reranked chunks. The assistant is rolled out company-wide: 12 questions per second. The LLM deployment has 24 concurrent slots at ~2.8 s each, about 8.5 answers per second. Its waiting line fills and it rejects requests.

    Meanwhile the embedding model and the vector index are almost idle. Scaling the vector database would change nothing. The fixes are on the generation side: more model capacity, shorter answers, a smaller model for easy questions, or caching repeated questions.

    Scene: At 12 questions per second the LLM is saturated and rejects requests, while the embedding model, vector index and reranker are mostly idle.

    Key idea: In RAG, generation is both the latency and the throughput bottleneck. Scale and optimise it first.

  10. 10. RAG is a search system with a writer on top

    The pipeline: embed → retrieve (hybrid) → rerank → build a grounded prompt → generate → validate citations. Quality comes mostly from retrieval: chunking, hybrid search, reranking and filters by permission. Latency and capacity come mostly from generation.

    Evaluate the two halves separately: retrieval (is the right chunk in the top-k?) and generation (is the answer faithful to the chunks and does it answer the question?). Tools for both exist, but a few hundred real questions with known answers are the foundation.

    Scene: The complete RAG system: embedding model, vector and keyword indexes, reranker and LLM behind the orchestrator. At 12 questions per second the LLM remains the bottleneck.

    Key idea: Measure retrieval and generation separately; fix retrieval for quality, generation for latency and cost.