Interview Study Guide

Guide / AI engineering Fundamentals

17. Designing an efficient RAG pipeline

Created · Updated · 5 min read

Retrieval-Augmented Generation = fetch relevant knowledge at query time and give it to the LLM as context, so answers are grounded, current and citable without retraining. Most RAG failures are retrieval failures, not generation failures: if the right chunk isn’t retrieved, no prompt fixes it.

[embedded content: RAG pipeline · offline ingestion feeds online retrieval]

The offline row runs whenever documents change; the online row runs per query, and its retrieve and rerank steps decide most of the answer quality.

17.1 The two pipelines#

Offline (ingestion / indexing):

  1. Source connectors: docs, PDFs, Confluence, DB rows, product catalogue, tickets. Track source ID, version, permissions, last-modified.
  2. Parsing: extract text and structure (headings, tables, lists). PDFs and scans need layout-aware parsing or OCR / vision models; tables often need conversion to Markdown or row-wise text.
  3. Cleaning: remove boilerplate (nav, footers), dedupe near-identical docs, normalize.
  4. Chunking (section 17.2).
  5. Enrichment: attach metadata (title, section path, date, product category, tenant, ACL), optionally generate summaries, keywords or hypothetical questions per chunk; contextual retrieval = prepend a short LLM-written context (“This chunk is from the 2026 refund policy, section on returns”) before embedding.
  6. Embedding in batches with retries and rate limits; store model name/version with each vector.
  7. Indexing: vector index + keyword index (BM25) + metadata store; raw text in a primary DB/S3.
  8. Incremental updates: CDC or change events → re-chunk and re-embed only changed docs; delete stale chunks by doc_id; idempotent upserts keyed by doc_id + chunk_no + version.

Online (query time):

  1. Query understanding: classify intent (does it need retrieval at all?), rewrite conversational follow-ups into standalone queries (“what about the blue one?” → “price of the blue Nykaa lipstick X”), extract filters (price < 500, brand = X).
  2. Retrieval: hybrid search (dense + BM25) with metadata/ACL filters, top 20–100 candidates.
  3. Fusion: combine result lists with Reciprocal Rank Fusion (score = Σ 1/(k + rank), k ≈ 60).
  4. Reranking: a cross-encoder reranker (Cohere Rerank, bge-reranker, or an LLM) scores query–chunk pairs jointly; keep top 3–10. Big precision gain for small latency (~50–200 ms).
  5. Context assembly: dedupe, order by relevance or document order, expand to neighbouring chunks or parent section if needed, fit the token budget, add source IDs for citations.
  6. Generation: system prompt says “answer only from context; say you don’t know otherwise; cite sources”.
  7. Post-processing: validate citations exist, check groundedness (optional LLM check), apply guardrails, stream to user.
  8. Logging: query, retrieved IDs and scores, prompt version, answer, latency, user feedback — the raw material for evals.

17.2 Chunking strategies#

StrategyHowProsCons
Fixed-size with overlape.g. 300–800 tokens, 10–20% overlapSimple, predictableCuts across sentences/sections
Recursive / structuralSplit by headings → paragraphs → sentencesRespects document structureUneven sizes
SemanticSplit where embedding similarity between sentences dropsTopic-coherent chunksSlower, more tuning
Document-specificCode by function/class, tables by rows, FAQs by Q&A pair, products as one record eachBest quality for that typeCustom work per source
Parent-child (small-to-big)Embed small chunks for precise matching, return the larger parent section to the LLMPrecision + contextTwo-level storage
Late chunking / long-context embeddingEmbed the whole doc then pool per chunkChunks keep document contextNeeds supporting models

Rule of thumb: smaller chunks = better retrieval precision, worse context; bigger = more context, more noise. Tune with evals, not intuition.

17.3 Retrieval improvements (know when to use each)#

  • Hybrid search: almost always beats dense-only, especially for names, SKUs, codes, acronyms.
  • Query rewriting / multi-query: generate 3–5 reformulations, retrieve for each, fuse. Helps vague queries; costs an LLM call.
  • HyDE: have the LLM write a hypothetical answer, embed that, search. Helps when queries and documents are phrased very differently.
  • Metadata filtering and routing: route queries to the right index (policies vs products) or filter by date, tenant, language.
  • Step-back / decomposition: break multi-part questions into sub-questions, retrieve for each.
  • Agentic RAG: the model decides when and what to search, can search iteratively, and checks if it has enough (more accurate on complex questions, slower and costlier).
  • Corrective / self-RAG: grade retrieved chunks for relevance; if poor, rewrite the query or fall back to another source.
  • Caching: cache embeddings of frequent queries, retrieval results, and full answers (semantic cache, section 21).

17.4 Evaluating RAG#

Evaluate retrieval and generation separately.

LayerMetricMeaning
RetrievalRecall@k / hit rateIs the right chunk in the top k?
RetrievalMRR, nDCGHow high is it ranked?
RetrievalContext precisionHow much of the retrieved context is relevant?
GenerationFaithfulness / groundednessIs every claim supported by the context?
GenerationAnswer relevance / correctnessDoes it answer the question correctly (vs reference)?
End to endTask success, user feedback, deflection rate, latency, cost per queryBusiness outcome

Build a golden set of 100–500 real questions with the expected source chunks and reference answers. Tools: RAGAS, DeepEval, TruLens, LangSmith, Langfuse, Phoenix.

17.5 Common RAG failure modes and fixes#

SymptomLikely causeFix
Right doc exists but isn’t retrievedChunking split the answer, vocabulary mismatch, dense-onlyHybrid search, better chunking, query rewriting, contextual retrieval
Retrieved but answer is wrongToo much noisy context, chunk lacks context, lost in the middleReranking, fewer better chunks, parent-child expansion
Hallucinated answer when nothing relevant foundPrompt doesn’t permit “I don’t know”Relevance threshold + explicit refusal instruction + groundedness check
Stale answersNo incremental re-indexingCDC-driven updates, freshness metadata, prefer newest version
Leaks another tenant’s / user’s dataACLs not enforced at retrievalFilter by permissions in the retrieval query itself (never after generation)
SlowToo many LLM calls in pipeline, large contextCache, parallelize retrieval, smaller reranker, cap context, stream
Can’t answer aggregate questions (“how many orders failed last week?”)RAG is for text lookup, not analyticsRoute to text-to-SQL / tools instead

17.6 RAG vs long context vs fine-tuning#

  • RAG: knowledge changes often, needs citations, per-user permissions, large corpus. Default for knowledge.
  • Long context (stuff everything in): small, stable corpus (< a few hundred pages), low QPS; simplest but costly per call and weaker on precise retrieval in the middle.
  • Fine-tuning: changes behaviour (format, tone, domain style, classification), not a good way to add facts that change.
  • Often combined: fine-tuned small model + RAG, with prompt caching for the static parts.
Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes