Guide / AI engineering Fundamentals
17. Designing an efficient RAG pipeline
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):
- Source connectors: docs, PDFs, Confluence, DB rows, product catalogue, tickets. Track source ID, version, permissions, last-modified.
- 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.
- Cleaning: remove boilerplate (nav, footers), dedupe near-identical docs, normalize.
- Chunking (section 17.2).
- 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.
- Embedding in batches with retries and rate limits; store model name/version with each vector.
- Indexing: vector index + keyword index (BM25) + metadata store; raw text in a primary DB/S3.
- Incremental updates: CDC or change events → re-chunk and re-embed only changed docs; delete stale chunks by
doc_id; idempotent upserts keyed bydoc_id + chunk_no + version.
Online (query time):
- 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).
- Retrieval: hybrid search (dense + BM25) with metadata/ACL filters, top 20–100 candidates.
- Fusion: combine result lists with Reciprocal Rank Fusion (score = Σ 1/(k + rank), k ≈ 60).
- 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).
- 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.
- Generation: system prompt says “answer only from context; say you don’t know otherwise; cite sources”.
- Post-processing: validate citations exist, check groundedness (optional LLM check), apply guardrails, stream to user.
- Logging: query, retrieved IDs and scores, prompt version, answer, latency, user feedback — the raw material for evals.
17.2 Chunking strategies#
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Fixed-size with overlap | e.g. 300–800 tokens, 10–20% overlap | Simple, predictable | Cuts across sentences/sections |
| Recursive / structural | Split by headings → paragraphs → sentences | Respects document structure | Uneven sizes |
| Semantic | Split where embedding similarity between sentences drops | Topic-coherent chunks | Slower, more tuning |
| Document-specific | Code by function/class, tables by rows, FAQs by Q&A pair, products as one record each | Best quality for that type | Custom work per source |
| Parent-child (small-to-big) | Embed small chunks for precise matching, return the larger parent section to the LLM | Precision + context | Two-level storage |
| Late chunking / long-context embedding | Embed the whole doc then pool per chunk | Chunks keep document context | Needs 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.
| Layer | Metric | Meaning |
|---|---|---|
| Retrieval | Recall@k / hit rate | Is the right chunk in the top k? |
| Retrieval | MRR, nDCG | How high is it ranked? |
| Retrieval | Context precision | How much of the retrieved context is relevant? |
| Generation | Faithfulness / groundedness | Is every claim supported by the context? |
| Generation | Answer relevance / correctness | Does it answer the question correctly (vs reference)? |
| End to end | Task success, user feedback, deflection rate, latency, cost per query | Business 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#
| Symptom | Likely cause | Fix |
|---|---|---|
| Right doc exists but isn’t retrieved | Chunking split the answer, vocabulary mismatch, dense-only | Hybrid search, better chunking, query rewriting, contextual retrieval |
| Retrieved but answer is wrong | Too much noisy context, chunk lacks context, lost in the middle | Reranking, fewer better chunks, parent-child expansion |
| Hallucinated answer when nothing relevant found | Prompt doesn’t permit “I don’t know” | Relevance threshold + explicit refusal instruction + groundedness check |
| Stale answers | No incremental re-indexing | CDC-driven updates, freshness metadata, prefer newest version |
| Leaks another tenant’s / user’s data | ACLs not enforced at retrieval | Filter by permissions in the retrieval query itself (never after generation) |
| Slow | Too many LLM calls in pipeline, large context | Cache, parallelize retrieval, smaller reranker, cap context, stream |
| Can’t answer aggregate questions (“how many orders failed last week?”) | RAG is for text lookup, not analytics | Route 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.