Design a RAG pipeline end to end
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
System-design interviewers use RAG to test whether you can decompose a fuzzy product requirement into two concrete data pipelines and reason about quality at every stage. Strong candidates discuss chunking and embedding-space consistency, explain why retrieval is optimized for recall and reranking for precision, and can name the failure modes — hallucination on retrieval misses, stale indexes, context dilution — with mitigations. Weak answers stop at "embed everything and put it in a vector database".
Mental model
RAG is a retrieval contract between two pipelines: ingestion turns documents into retrievable embedded chunks with metadata, and query turns a question into an embedded search, a reranked shortlist, and a grounded, cited answer. Retrieval quality sets the ceiling for generation quality — if the right passage never makes the shortlist, no prompt can recover the answer, so evaluate retrieval and generation separately.
Step-by-step solution
Step 1: Ingestion builds the index
Retrieval quality is decided before the user ever asks a question. Ingestion is an offline pipeline that turns an organization's messy sources — PDFs, HTML pages, support tickets, database rows — into a searchable index. Parsing extracts text and preserves structure as metadata. Chunking splits the text into passages small enough to embed meaningfully and large enough to stay self-contained. Each chunk is then embedded by the same model the query path will use, because retrieval only works if both sides live in the same vector space. Finally, vectors plus metadata are upserted into the vector database, idempotently keyed by document id and chunk index so a re-run replaces rather than duplicates. Watch the animation: every phase turns raw representation into something more retrievable. Treat ingestion as a versioned, repeatable job rather than a one-off script, because a stale or partially updated index silently degrades every query that follows.
Step 2: Chunk size and overlap
Chunking is the highest-leverage decision in the pipeline because an embedding compresses a chunk into a single vector. Make the chunk too large and it discusses several topics at once; the vector drifts toward the average and stops matching any specific question. Make it too small and it loses its referents — the pronoun whose noun lives in the previous sentence — so retrieval finds fragments that cannot answer anything. A window in the range of a few hundred tokens with ten to twenty percent overlap is a common starting point, and overlap is what protects facts that straddle a boundary: the sentence appears whole in at least one chunk. Watch the animation as the splitter repeats the boundary tokens in both adjacent chunks. Structure-aware splitting helps further: keep headings with their sections, never cut tables or code blocks, and attach the section title to every chunk so the embedding carries context. Then tune empirically with retrieval evaluation.
Step 3: Query path embeds and retrieves
The query path mirrors ingestion but at interactive latency. The user question is embedded with the exact same model, then searched against an approximate nearest neighbor index such as HNSW or IVF. ANN search is what makes retrieval cheap: instead of comparing against every vector, it walks a navigable graph or probes the most promising clusters, trading a small amount of recall for orders-of-magnitude speed. Because this stage optimizes recall, it deliberately over-fetches: ten to one hundred candidates ranked by vector similarity. Watch the animation: the query becomes a vector, the vector probes the index, and a candidate list returns. Metadata filters — tenant, date, source — can be applied before or after the search depending on the engine, and pre-filtering is usually more accurate but harder to keep fast. Same model, same normalization, same dimensionality on both sides; mixing embedding models silently destroys the geometry.
Step 4: Reranking buys precision
Vector similarity finds candidates; a reranker decides which ones actually answer the question. The retrieval stage uses a bi-encoder: query and chunk are embedded independently, so all chunk vectors can be precomputed, and each similarity comparison is a fixed-size dot product. The corpus-size win comes from ANN indexing over those precomputed vectors, not from the comparison being constant-time. That speed comes at a cost — the two texts never see each other, so the score is a coarse approximation of relevance. A cross-encoder reads the query and one candidate concatenated, letting full attention compare them token by token. It is far more precise and far too slow to run across the whole corpus, which is exactly why it belongs after retrieval. Watch the animation: fifty noisy candidates enter, and a handful of precise passages leave. This two-stage design is the standard precision-recall split, and it usually fits a latency budget of tens of milliseconds for a few dozen candidates. Hybrid keyword search and late-interaction models like ColBERT are variations on the same trade.
Step 5: Ground generation with citations
Generation is where retrieval becomes an answer. The reranked passages are packed into a token budget — system instructions first, then numbered context chunks, then the question — and any passage that does not fit is dropped so the window never overflows. Each chunk keeps a stable id, and the prompt instructs the model to answer only from the provided context and cite the ids it used. Watch the animation: top-n passages flow into the budget, the prompt, and a grounded answer whose citations map back to exact sources. This design exposes the failure modes you must name in an interview. When retrieval misses, the model hallucinates fluently unless instructed to abstain; a stale index quietly serves outdated answers; long contexts lose middle passages; and retrieved text can itself carry prompt-injection instructions. Grounding, citations, freshness jobs, and separate retrieval and generation evaluations are the defenses.
Edge cases & traps
- Embedding queries with a different model or normalization than ingestion: the query and documents land in different vector spaces, so freeze the embedding model and version the index alongside it.
- Fixed-size character chunking slices through tables, code, and sentences: use structure-aware splitting (headings, code fences) with 10–20% overlap so boundary facts stay whole.
- Optimizing only top-k similarity and skipping reranking: the answer sits buried under near-duplicates — retrieve k = 50 fast, then rerank to n = 5 precise.
- Hallucination when retrieval misses: give the model an explicit "insufficient context" escape hatch and evaluate retrieval recall separately from answer quality.
- Stale index: a source is updated but old chunks remain — key chunks by document version, re-ingest on change, and delete superseded vectors.