How does RAG work end to end?
MediumRAGRetrieval
How does retrieval-augmented generation (RAG) work end to end?
TL;DR
RAG gives an LLM relevant, up-to-date or private knowledge at query time, by retrieving it and putting it in the prompt, instead of relying on what the model memorized. It has two pipelines. Indexing (offline): load documents → clean them → split into chunks → embed each chunk → store vectors with metadata. Query (online): embed the user's question → retrieve the top-k similar chunks (often with hybrid search and reranking) → build a prompt with those chunks as context → the LLM generates an answer grounded in them, with citations.
Key points
- RAG reduces hallucinations and lets you update knowledge by re-indexing, with no retraining.
- Most RAG failures are retrieval failures: the right chunk was never retrieved. Debug retrieval first.
- Levers, in rough order of impact: data quality and parsing (tables, PDFs), chunking, hybrid search, reranking, query rewriting, metadata filters.
- Instruct the model to answer only from the context and to say "I don't know" when the context doesn't contain the answer.
- Return citations (chunk or document IDs) so users can verify answers.
- Evaluate retrieval and generation separately: retrieval with recall@k and MRR; generation with faithfulness and answer relevance.
- Access control: filter retrieved chunks by the user's permissions before they reach the prompt.
Example
python
def answer(question, user):
q_vec = embed(question)
chunks = vector_db.search(q_vec, k=20, filter={"tenant": user.tenant})
top = reranker.rank(question, chunks)[:5]
context = "\n\n".join(f"[{c.id}] {c.text}" for c in top)
return llm(
system="Answer only from the context. Cite sources like [id]. "
"If the answer isn't in the context, say you don't know.",
user=f"Context:\n{context}\n\nQuestion: {question}",
)Common follow-ups
- The right document exists but the answer is wrong. How do you debug? Check whether it was retrieved (log retrieved IDs). If not: chunking, embeddings, hybrid search or query rewriting. If it was: the prompt, context order, or the model ignoring the context.
- What's agentic RAG? The model decides when and what to search, can issue several searches and refine queries, using retrieval as a tool.
What interviewers look for
Tip
Both pipelines, retrieval quality as the main lever, grounded prompting with citations, separate evaluation, and permission filtering.
- Red flag: "we embed everything and send the top 3 chunks", with no evaluation.