Design a Retrieval-Augmented Generation (RAG) system

    A Retrieval-Augmented Generation (RAG) system grounds an LLM in private/up-to-date data by retrieving relevant chunks via semantic search and injecting them into the prompt. It splits into an offline ingestion pipeline and an online query pipeline.

    AI & Machine Learning, 7 components, about 40 min

    1. Scope

    In scope

    • • Ingest + chunk + embed documents
    • • Semantic retrieval
    • • Prompt augmentation
    • • LLM generation with streaming

    Out of scope

    • • Training/fine-tuning the LLM
    • • Agentic tool use
    • • Multi-modal retrieval

    2. Functional requirements

    Must have

    • • Answer questions grounded in a knowledge base
    • • Retrieve relevant context
    • • Keep the index fresh as docs change
    • • Cite/ground responses

    Nice to have

    • • Hybrid (keyword + vector) search
    • • Re-ranking
    • • Per-tenant isolation

    3. Non-functional requirements

    Answer latencyFirst token < 1 s
    Retrieval latency< 100 ms (ANN)
    FreshnessMinutes after doc update
    GroundingMinimize hallucination

    4. Back-of-envelope estimation

    Assumptions

    • • 10M document chunks
    • • Embedding dim ~1536
    • • Top-k = 5 retrieved
    • • Chunk ~500 tokens

    Derived numbers

    Vector store~60 GB— 10M × 1536 × 4B
    RetrievalANN sub-100ms
    LLM costDominant per-query cost

    5. API design

    POST/api/ask

    { query } → streamed grounded answer + sources

    POST/api/ingest

    Add/refresh documents into the index

    6. High-level design

    What each box in the reference diagram is responsible for:

    RAG API — Orchestrates: embed query → retrieve → build prompt → call LLM → stream.
    Embedding Model — Text → vector for both queries and documents.
    Vector DB — Pinecone/Milvus ANN index of chunk embeddings + metadata.
    LLM — Generates the answer from prompt + retrieved context.
    Knowledge Source — PDFs/docs ingested into the index.
    Ingestion Worker — Extract → chunk → embed → upsert (LangChain/LlamaIndex).

    7. Data model

    Vector DB: chunk_id → (embedding[1536], text, source, metadata)

    8. Deep dives

    Chunking strategy

    Documents are split into chunks (~200-500 tokens) before embedding. Too large and retrieval is imprecise + wastes context window; too small and you lose coherence. Overlap chunks slightly so context isn't cut mid-thought. Store source metadata for citations.

    Semantic retrieval with ANN

    Both documents and the query are embedded into the same vector space; relevance = cosine similarity. Exact nearest-neighbor over millions of vectors is too slow, so use Approximate NN (HNSW/IVF) for sub-100ms top-k retrieval at a tiny recall cost. Hybrid search (combine BM25 keyword + vector) improves precision on names/IDs.

    Augmentation & grounding

    Inject the retrieved chunks into a prompt template ("Answer using ONLY this context: ..."). This grounds the LLM in real data, reducing hallucination, and lets you cite sources. Manage the context window: include only top-k, and re-rank candidates if needed.

    Keeping the index fresh

    When source docs change, the ingestion pipeline re-chunks and re-embeds just the affected documents and upserts into the vector DB — so answers reflect current data within minutes.

    9. Bottlenecks

    • LLM latency/cost → stream tokens, cache, smaller models where possible
    • Retrieval quality → chunking + hybrid search + re-ranking
    • Stale index → incremental re-embedding on change

    10. Trade-offs

    Retrieval method

    Choose: Hybrid: BM25 plus dense vectors, merged (for example reciprocal rank fusion), then a cross-encoder reranker on the top ~50.

    Instead of: Dense vectors only: simpler, but misses exact identifiers, codes and rare names.

    Keyword and semantic retrieval fail on different queries; the reranker fixes ordering cheaply on a small set.

    Chunking

    Choose: Structure-aware chunks (headings, paragraphs) of a few hundred tokens with small overlap, each tagged with document title and section.

    Instead of: Fixed-size blind chunks: easy, but split tables and definitions mid-thought.

    Retrieval quality is mostly chunk quality.

    Long context or retrieval

    Choose: Retrieve for large or changing corpora; put the whole document in context when it fits and is queried repeatedly (with prompt caching).

    Instead of: Always stuff everything into context: cost and latency grow with corpus size.

    Retrieval keeps per-query tokens bounded as the corpus grows.

    11. Failure modes

    Retrieved text contains instructions (prompt injection)

    The model follows a document instead of the user.

    Mitigation: Treat retrieved text as data in delimited blocks, give the model no dangerous tools, and filter sources at ingest.

    Permissions leak

    Users see answers from documents they cannot access.

    Mitigation: Store access-control lists with chunks and filter at retrieval time by the caller's identity, not after generation.

    Stale index after a document changes

    Confident wrong answers.

    Mitigation: Change-data-driven re-embedding, deletes propagated as tombstones, and citations with document version.

    12. What interviewers probe

    Answer each one yourself before opening it.

    How do you evaluate a RAG system?Show a strong answer

    Separately: retrieval (recall@k against labelled question-passage pairs) and generation (faithfulness to retrieved text and answer correctness), graded by code where possible and by a different model otherwise.

    How big is the vector index for 10M chunks?Show a strong answer

    10M × 1,536 dims × 4 bytes ≈ 61 GB in float32; quantizing to int8 or binary cuts that 4–32×, with a rerank on full precision.

    How do you make answers cite sources?Show a strong answer

    Give each chunk an id, require citations by id in a structured output, and verify every cited id was actually retrieved.

    What drives cost per query?Show a strong answer

    Input tokens from retrieved chunks; cap k, rerank to fewer chunks, cache the stable prompt prefix, and route easy questions to a cheaper model.

    Sign in to track this guide in your curriculum progress.