Retrieval-Augmented Generation, End to End
By the Katkat team · Updated · 8 min read
Quick overview
Learn how a RAG pipeline works from ingestion to citation, where each stage fails, and how to debug and explain it clearly in an AI engineering interview.
After this lesson you will be able to walk through a full retrieval-augmented generation (RAG) pipeline in an interview: ingest, chunk, embed, retrieve, rerank, generate and cite. You will be able to say what goes wrong at each step and how you would detect it. You will also be able to size a small system with concrete numbers and explain why end-to-end quality is the product of the stages, not the best stage.
What RAG is and why it exists
A language model only knows what was in its training data and what you put in its prompt. RAG fills the prompt with relevant text fetched at query time, so the model answers from your documents rather than from memory. The idea was popularised by the paper "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks".
The main reasons to use it:
- Fresh or private knowledge. Documents change daily and were never in the training set. Updating an index is cheaper than retraining.
- Attribution. You can show which passage supported an answer.
- Smaller hallucination surface. The model is asked to read, not to recall. This helps but does not eliminate the problem.
The pipeline has two phases. The offline phase (ingest, chunk, embed, index) runs when documents change. The online phase (retrieve, rerank, generate, cite) runs per query.
The offline phase: ingest, chunk, embed, index
Ingest. Raw files (PDFs, HTML, wikis, tickets) are converted to clean text with metadata such as source URL, title, section, last-modified date and access permissions. This step quietly decides quality. A PDF parser that flattens a table into a stream of numbers or interleaves two columns creates text no later stage can repair. See Document Ingestion for RAG.
Chunk. Documents are split into passages small enough to embed precisely and to fit several into a prompt. Typical choices are a few hundred tokens with a small overlap, ideally splitting on structure (headings, paragraphs) rather than at arbitrary character counts. Too large and one vector blurs several topics; too small and a chunk loses the context needed to be understood. See Chunking Documents for Retrieval.
Embed. An embedding model maps each chunk to a vector so that semantically similar text lands close together. The same model must be used for queries and chunks, and changing the model means re-embedding everything. See Embeddings: Representing Text as Vectors.
Index. Vectors go into an approximate nearest-neighbour index (for example HNSW or IVF) next to the chunk text and metadata. Approximate search trades a little recall for large speed gains, so the index itself can miss a relevant chunk.
The online phase: retrieve, rerank, generate, cite
Retrieve. The query is embedded and the index returns the top-k nearest chunks (k is often 20 to 100 here). This stage is optimised for recall: get the right chunk somewhere in the candidate set, cheaply. Pure vector search is weak on exact identifiers, rare names and error codes, so many systems combine it with keyword search (BM25). See Hybrid Search and Reranking.
Rerank. A cross-encoder reads the query and each candidate together and produces a relevance score. It is more accurate than comparing two independent vectors but too slow to run over the whole corpus, so it only rescores the candidates. You keep the top few (often 3 to 8). This stage is optimised for precision.
Generate. The prompt contains instructions, the selected chunks (each labelled with an ID) and the question. Good instructions say: answer only from the provided context, and say you do not know if the context is insufficient. Placement matters, because models can use information in the middle of a long context less reliably than at the start or end, as shown in the "Lost in the Middle" paper.
Cite. Each claim in the answer is tied to the chunk IDs that support it, and the application maps the IDs back to titles and links. Citations are only trustworthy if you verify them: check that cited IDs were actually in the prompt, and optionally that the cited text supports the claim.
Worked example: sizing a small pipeline
Assume 20,000 documents averaging 2,000 tokens each, chunked at 400 tokens with a 50-token overlap.
- Stride between chunk starts: 400 − 50 = 350 tokens.
- Chunk starts per document: 0, 350, 700, 1050, 1400, 1750. The last chunk covers tokens 1750 to 2000 (250 tokens), so there are 6 chunks per document.
- Total chunks: 20,000 × 6 = 120,000.
- Tokens to embed per document: 5 × 400 + 250 = 2,250. Across the corpus: 2,250 × 20,000 = 45,000,000 tokens, about 12.5% more than the raw 40,000,000 because of overlap.
- Vector storage with a 1,024-dimension float32 embedding: 1,024 × 4 bytes = 4,096 bytes per vector. 120,000 × 4,096 = 491,520,000 bytes, about 0.49 GB, before index overhead and chunk text.
Per query, suppose you retrieve 20 candidates, rerank, and keep 5 chunks:
- Context tokens: 5 × 400 = 2,000.
- Add roughly 300 tokens of instructions and 50 for the question: about 2,350 input tokens per request.
Now the quality arithmetic, with illustrative (not measured) numbers. Say retrieval puts the needed chunk in the top 20 for 90% of questions, the reranker then keeps it in the top 5 for 90% of those, and the model answers faithfully 95% of the time when the chunk is present:
0.90 × 0.90 × 0.95 = 0.7695, so about 77% of questions are answered correctly. Improving any single stage by a few points matters less than finding the stage that is losing the most. That is why you measure stages separately.
Failure points at each step
| Stage | Typical failure | Symptom | Diagnosis and fix |
|---|---|---|---|
| Ingest | Bad parsing, lost tables, stale or duplicate documents | Answer text is garbled or outdated | Inspect parsed text directly; add deduplication and re-ingestion on change |
| Chunk | Splits mid-sentence, loses heading context, chunks too big or small | Right document retrieved, wrong or partial passage | Split on structure, prepend titles, tune size and overlap |
| Embed | Model weak on your domain or language; query and document mismatch | Obvious matches missing from results | Test alternative models on labelled queries; try query rewriting |
| Retrieve | Recall miss, exact terms not matched, approximate index misses, missing metadata filters | Relevant chunk absent from top-k | Add keyword search, raise k, tune index parameters, filter by metadata |
| Rerank | Relevant chunk found but ranked below the cut | Chunk in candidates, not in prompt | Add or tune a reranker, adjust how many to keep |
| Generate | Ignores context, mixes in memory, over-answers, loses the middle of long context | Fluent but unsupported answer | Tighten instructions, allow "I don't know", reduce context, reorder chunks |
| Cite | Fabricated or misattributed citations | Link does not support the claim | Cite by ID only, validate IDs, check support |
Two cross-cutting failures deserve mention. Permissions: if retrieval ignores who is asking, the model can leak documents the user should not see, so access filters belong in the retrieval query, not in the prompt. Prompt injection: retrieved text is untrusted input and can contain instructions aimed at the model.
Evaluating and debugging the pipeline
Evaluate retrieval and generation separately. For retrieval, build a set of questions with known relevant chunks and measure recall at k (is the right chunk in the candidates?) and the rank of the first relevant chunk. For generation, measure faithfulness (is every claim supported by the provided context?) and answer correctness. See Evaluating a RAG System.
For a wrong answer, debug in order, from the earliest stage that could be at fault:
- Does the correct text exist in the parsed corpus?
- Is it in a chunk that contains the whole answer?
- Is that chunk in the top-k candidates?
- Does it survive reranking into the prompt?
- Given that prompt, does the model answer correctly?
The first "no" tells you which stage to fix. A step-by-step version is in Your RAG System Gives Wrong Answers: How Do You Debug It?.
How does this come up in interviews?
1. Walk me through a RAG system from document to answer. Cover the offline phase (ingest, chunk, embed, index) and the online phase (retrieve for recall, rerank for precision, generate with instructions to stay grounded, cite by chunk ID). Mention metadata and permissions, and that the same embedding model is used for chunks and queries. Close by saying you would evaluate retrieval and generation separately.
2. Users report wrong answers. Where do you start? Take a failing example and trace it forward through the stages rather than guessing. Check whether the answer text was in the corpus, then whether it was chunked well, retrieved, reranked into the prompt, and used by the model. The first stage where the evidence disappears is the one to fix, and you then add that example to a regression set.
3. Why add a reranker when you already have vector search? Vector search compares independent embeddings, which is fast but coarse. A cross-encoder reads query and passage together and scores relevance more accurately, but it is too expensive for the whole corpus. So you retrieve broadly for recall and rerank narrowly for precision, at the cost of extra latency.
4. How do you choose chunk size? There is no universal value. Small chunks give precise matches but may lack context, while large chunks hold more context but dilute the embedding and use more prompt budget. You pick a starting point (a few hundred tokens with some overlap, split on structure), then measure retrieval recall and answer quality on a labelled set and adjust.
5. How would you make citations trustworthy? Label chunks with IDs in the prompt and ask the model to cite IDs rather than write URLs. Then verify in code that each cited ID was in the context, and optionally check that the cited passage supports the claim with a separate checker. Unverifiable claims can be removed or flagged.
Common mistakes
- Treating RAG as "vector database plus LLM" and ignoring ingestion quality, which often sets the ceiling.
- Evaluating only the final answer, so you cannot tell whether retrieval or generation is at fault.
- Using only dense retrieval and missing exact terms such as product codes or error messages.
- Stuffing too many chunks into the prompt, which raises cost and latency and can bury the useful passage.
- Forgetting that changing the embedding model requires re-embedding the whole corpus.
- Applying access control after generation, or in the prompt, instead of during retrieval.
- Trusting model-written citations without checking them against the retrieved context.
- Believing RAG removes hallucination; the model can still ignore or misread the context.