The problem, stated properly
An LLM knows only what was in its training data: nothing about your company docs, nothing after its cutoff, and it will confidently invent answers when it does not know. Retrieval-Augmented Generation fixes this with a simple move: before the model answers, fetch the relevant pieces of your data and paste them into the prompt. The model then answers from real text instead of from memory. The idea is one sentence; making it actually work in production is chunking, embeddings, vector search, reranking, and evaluation, each with its own failure modes.
The pipeline, both halves
Offline (indexing), done once per document set and on every update:
- Ingest + clean: pull docs from Drive/Notion/Confluence/web. Strip boilerplate, extract text from PDFs (tables and multi-column layouts are where extraction quietly destroys quality).
- Chunk: split into pieces of ~200-500 tokens with 10-20% overlap. Chunking is the highest-leverage decision in the whole system: too big and embeddings blur unrelated ideas together; too small and every chunk lacks the context to be useful. Split on semantic boundaries (headings, paragraphs), never mid-sentence, and store metadata (source, title, section, date) with every chunk.
- Embed: each chunk passes through an embedding model (OpenAI text-embedding-3, Cohere, open-source BGE/E5) producing a vector of ~768-3072 floats. Similar meanings land at nearby points.
- Index: vectors go into a vector DB (pgvector, Pinecone, Weaviate, Qdrant, FAISS) with an ANN index like HNSW that finds approximate nearest neighbors in milliseconds over millions of vectors.
Online (answering), per question:
- Embed the user's question with the same model.
- ANN search returns the top ~20-50 candidate chunks; keyword (BM25) search in parallel catches exact terms vectors miss, like part numbers and error codes. Merge the two result sets (hybrid search).
- Rerank: a cross-encoder model rescores the candidates against the actual question (expensive but accurate) and keeps the top 3-8.
- Stuff the survivors into the prompt with instructions to answer only from the context and cite sources.
- The LLM generates the answer; citations map back to chunk metadata so users can verify.
Why vector search is fast: ANN in one paragraph
Comparing a query vector against 100 million stored vectors one by one (exact search) costs ~100M dot products per query: seconds, not milliseconds. HNSW (Hierarchical Navigable Small World) builds a multi-layer graph over the vectors, where each node links to its nearest neighbors; search greedily walks the graph from a sparse top layer down to dense bottom layers, landing near the true neighbors after ~log N hops. You trade a small recall loss (you might miss 2-5% of true neighbors) for 1000x speed, which is the correct trade in almost every system.
Real numbers to design with
- Corpus: 1M docs x ~10 chunks each = 10M vectors x 1536 dims x 4 bytes is about 60 GB, plus HNSW graph overhead (~1.5-2x). Fits on one beefy node or a small shard set.
- Latency budget: embedding the query ~50-100 ms (API call), ANN search ~5-20 ms, rerank 50 candidates ~50-200 ms, LLM generation 1-5 s (streaming hides most of it). Retrieval adds well under 500 ms; the LLM is the slow part.
- Cost shape: indexing a million docs is a one-time batch cost; every query pays one embedding call + one LLM call with a fattened prompt. Prompt tokens from retrieval are usually the dominant recurring cost, which is why reranking down to 3-8 chunks matters.
Failure modes (this is where interviews are won)
- Retrieval miss: the answer is in the corpus but the right chunk never made the top-k, so the model hallucinates anyway. Fixes: hybrid search, query rewriting/expansion (an LLM rewrites the vague question into 2-3 specific searches), higher recall + rerank.
- Chunk boundary decapitation: the answer spans a split ("The limit is... [chunk ends] 5 requests per second [next chunk]"). Overlap and section-aware splitting exist because of this.
- Distractor pollution: top-k contains 3 relevant chunks and 5 confidently-irrelevant ones, and the model happily weaves all of them in. Reranking and lower k are the fix.
- Stale index: the doc changed last week, the embedding is from last quarter. Index freshness (webhook-driven re-embedding on doc update) is a production requirement, not a nicety.
- "The model ignored the context": long prompts bury the relevant chunk in the middle, and models have a real lost-in-the-middle weakness. Put the best chunks first and last, keep total context lean.
- Multimodal reality: your PDFs are 40% tables and figures that text extraction mangles. Table-aware extraction or multimodal embeddings, or accept wrong answers on tabular questions.
Tradeoffs worth naming
- RAG vs fine-tuning: fine-tuning teaches the model how to talk (style, format, domain vocabulary); RAG gives it what to know (facts that change). Fine-tuning cannot keep up with facts that change weekly and hallucinates when asked about them anyway. Most production systems use RAG for knowledge and fine-tuning only for behavior, if at all.
- RAG vs long-context models: "just paste everything into a 1M-token window" works for one-off analysis of a small doc set, but at 1M docs it is impossible, and even at small scale it costs 100x more per query and degrades accuracy (lost-in-the-middle). Long context complements RAG; it does not replace it.
- Dedicated vector DB vs pgvector: under ~10M vectors, pgvector inside your existing Postgres removes an entire system to operate. Beyond that, or when you need advanced filtering at high QPS, a dedicated store earns its complexity.
Common interview traps
- Describing RAG as "search, then answer" without the offline/online split, chunking strategy, or reranking.
- Claiming embeddings understand exact keywords. They capture semantic similarity; "ERR_429_THROTTLE" needs BM25, not cosine similarity.
- No evaluation story. Production RAG is measured: retrieval recall (does the right chunk make top-k?), answer faithfulness (does the answer stick to the retrieved text?), both tracked over a golden question set.
- Ignoring citations and permissions. Enterprise RAG must retrieve only what the asking user is allowed to see, which means ACL metadata on every chunk and filtering at query time.
Interview Q&A
Q: Users complain the system answers questions the docs definitely cover. Walk me through debugging.
A: Split the pipeline and test each stage alone. First, retrieval: run the failing question, look at the top-20 chunks. If the right chunk is missing, it is a recall problem: check chunking (was the answer split or in a mangled table?), try hybrid search and query rewriting. If the right chunk is retrieved, it is a generation problem: check whether reranking buried it, whether the prompt is too long, and whether the model instructions let it say "I don't know" instead of forcing an answer. Every RAG bug is exactly one of these two, and the discipline is never tweaking prompts before measuring retrieval recall.
Q: How do you keep answers faithful and reduce hallucination?
A: Four compounding defenses: retrieve well (most hallucinations are retrieval misses in disguise), instruct the model to answer only from the provided context and to say "not covered" when it is not, require citations per claim so unfaithful answers are visible, and evaluate faithfulness on a golden set with an LLM-judge or human review before every prompt/model change ships. None of these is sufficient alone; together they get faithfulness into the high 90s.
Problem ko sahi se samjho
LLM sirf wahi jaanta hai jo uske training data mein tha: tumhare company docs ke baare mein kuch nahi, cutoff ke baad ka kuch nahi, aur jab use nahi pata hota to wo confidently jawab invent kar deta hai. Retrieval-Augmented Generation ise ek simple move se fix karta hai: model ke jawab dene se pehle, tumhare data ke relevant tukde fetch karo aur prompt mein paste kar do. Phir model memory se nahi, asli text se jawab deta hai. Idea ek sentence ka hai; production mein kaam karwana chunking, embeddings, vector search, reranking aur evaluation hai, har ek ke apne failure modes ke saath.
Pipeline, dono halves
Offline (indexing), har document set pe ek baar aur har update pe:
- Ingest + clean: Drive/Notion/Confluence/web se docs lo. Boilerplate hatao, PDFs se text extract karo (tables aur multi-column layouts wahi jagah hain jahan extraction chupke se quality khatam karta hai).
- Chunk: ~200-500 tokens ke tukde, 10-20% overlap ke saath. Chunking poore system ka sabse high-leverage decision hai: bahut bada to embeddings unrelated ideas ko mila dete hain; bahut chhota to har chunk ke paas context nahi bachta. Semantic boundaries pe kaato (headings, paragraphs), kabhi sentence ke beech nahi, aur har chunk ke saath metadata store karo (source, title, section, date).
- Embed: har chunk embedding model (OpenAI text-embedding-3, Cohere, open-source BGE/E5) se guzarta hai aur ~768-3072 floats ka vector banta hai. Similar meanings paas-paas ke points pe land karte hain.
- Index: vectors vector DB mein jaate hain (pgvector, Pinecone, Weaviate, Qdrant, FAISS) HNSW jaise ANN index ke saath jo millions of vectors pe milliseconds mein approximate nearest neighbors dhundta hai.
Online (answering), har question pe:
- User ke question ko same model se embed karo.
- ANN search top ~20-50 candidate chunks deta hai; parallel mein keyword (BM25) search exact terms pakadta hai jo vectors miss karte hain, jaise part numbers aur error codes. Dono result sets merge karo (hybrid search).
- Rerank: ek cross-encoder model candidates ko actual question ke against rescore karta hai (mehenga par accurate) aur top 3-8 rakhta hai.
- Bache hue chunks prompt mein daalo, instructions ke saath ki sirf context se jawab do aur sources cite karo.
- LLM answer generate karta hai; citations chunk metadata tak map hoti hain taaki user verify kar sake.
Vector search fast kyun hai: ANN ek paragraph mein
Query vector ko 100 million stored vectors se ek-ek karke compare karna (exact search) har query pe ~100M dot products ka cost: seconds, milliseconds nahi. HNSW (Hierarchical Navigable Small World) vectors ke upar multi-layer graph banata hai, jahan har node apne nearest neighbors se link hota hai; search sparse top layer se dense bottom layers tak greedily walk karta hai aur ~log N hops ke baad true neighbors ke paas pahunch jaata hai. Tum thoda recall loss trade karte ho (2-5% true neighbors miss ho sakte hain) 1000x speed ke liye, jo lagbhag har system mein sahi trade hai.
Design ke liye real numbers
- Corpus: 1M docs x ~10 chunks = 10M vectors x 1536 dims x 4 bytes, about 60 GB, plus HNSW graph overhead (~1.5-2x). Ek beefy node ya chhote shard set pe fit.
- Latency budget: query embed karna ~50-100 ms (API call), ANN search ~5-20 ms, 50 candidates rerank ~50-200 ms, LLM generation 1-5 s (streaming zyada chhupa deti hai). Retrieval 500 ms se kaafi kam add karta hai; LLM slow part hai.
- Cost shape: million docs ka indexing one-time batch cost hai; har query ek embedding call + fattened prompt ke saath ek LLM call. Retrieval ke prompt tokens usually dominant recurring cost hain, isliye rerank karke 3-8 chunks tak laana matter karta hai.
Failure modes (interviews yahi jeeti jaati hain)
- Retrieval miss: jawab corpus mein hai par sahi chunk top-k mein kabhi aaya hi nahi, to model waise bhi hallucinate karta hai. Fixes: hybrid search, query rewriting/expansion (ek LLM vague question ko 2-3 specific searches mein rewrite karta hai), higher recall + rerank.
- Chunk boundary decapitation: jawab split ke across hai ("The limit is... [chunk khatam] 5 requests per second [agla chunk]"). Overlap aur section-aware splitting isi wajah se exist karte hain.
- Distractor pollution: top-k mein 3 relevant chunks aur 5 confidently-irrelevant hain, aur model khushi se sab ko mila deta hai. Reranking aur kam k fix hai.
- Stale index: doc pichle hafte badla, embedding pichle quarter ka hai. Index freshness (doc update pe webhook-driven re-embedding) production requirement hai, nicety nahi.
- "Model ne context ignore kar diya": lambe prompts relevant chunk ko beech mein daba dete hain, aur models ki lost-in-the-middle weakness real hai. Best chunks pehle aur aakhir mein rakho, total context lean rakho.
- Multimodal reality: tumhare PDFs 40% tables aur figures hain jo text extraction bigaad deta hai. Table-aware extraction ya multimodal embeddings, ya tabular questions pe galat jawab accept karo.
Tradeoffs jo naam dene layak hain
- RAG vs fine-tuning: fine-tuning model ko sikhata hai kaise baat karna hai (style, format, domain vocabulary); RAG deta hai kya jaanna hai (facts jo badalte hain). Fine-tuning weekly badalte facts ke saath nahi chal sakta aur unke baare mein poochho to waise bhi hallucinate karta hai. Zyadatar production systems knowledge ke liye RAG use karte hain aur fine-tuning sirf behavior ke liye, wo bhi agar zaroorat ho.
- RAG vs long-context models: "sab kuch 1M-token window mein paste kar do" chhote doc set ki one-off analysis ke liye chal jaata hai, par 1M docs pe impossible hai, aur chhote scale pe bhi per query 100x zyada cost aur accuracy degrade (lost-in-the-middle). Long context RAG ka complement hai, replacement nahi.
- Dedicated vector DB vs pgvector: ~10M vectors tak, existing Postgres ke andar pgvector operate karne ke liye poora ek system hata deta hai. Usse aage, ya high QPS pe advanced filtering chahiye, to dedicated store apni complexity kamata hai.
Common interview traps
- RAG ko "search, phir answer" bolke khatam karna, bina offline/online split, chunking strategy ya reranking ke.
- Kehna ki embeddings exact keywords samajhte hain. Wo semantic similarity pakadte hain; "ERR_429_THROTTLE" ko cosine similarity nahi, BM25 chahiye.
- Evaluation story ka na hona. Production RAG measure hota hai: retrieval recall (sahi chunk top-k mein aaya?), answer faithfulness (jawab retrieved text tak simta hai?), dono golden question set pe track.
- Citations aur permissions ignore karna. Enterprise RAG sirf wahi retrieve karna chahiye jo poochhne wale user ko dekhne allowed hai, matlab har chunk pe ACL metadata aur query time pe filtering.
Interview Q&A
Q: Users complain kar rahe hain ki system un sawaalon ke jawab deta hai jo docs mein clearly hain. Debugging walk through karo.
A: Pipeline ko split karo aur har stage alag test karo. Pehle retrieval: failing question chalao, top-20 chunks dekho. Agar sahi chunk missing hai, to recall problem hai: chunking check karo (jawab split hua ya mangled table mein tha?), hybrid search aur query rewriting try karo. Agar sahi chunk retrieve hua, to generation problem hai: dekho reranking ne dabaaya to nahi, prompt bahut lamba to nahi, aur model instructions use "I don't know" bolne dete hain ya jawab force karte hain. Har RAG bug exactly in dono mein se ek hai, aur discipline ye hai ki retrieval recall measure kiye bina prompts kabhi mat chhedo.
Q: Answers faithful kaise rakhte ho aur hallucination kaise kam karte ho?
A: Char compounding defenses: achha retrieve karo (zyadatar hallucinations disguised retrieval misses hain), model ko instruct karo ki sirf provided context se jawab de aur cover na ho to "not covered" bole, har claim pe citations maango taaki unfaithful answers dikhein, aur har prompt/model change se pehle golden set pe faithfulness evaluate karo, LLM-judge ya human review se. Inme se koi akela kaafi nahi; saath milke faithfulness high 90s tak le jaate hain.