PrepStack › AI › RAG & Vector Databases
RAG & Vector Databases interview cheat sheet
Chunking, embeddings, ANN indexes, hybrid search, re-ranking and RAG evaluation
RAG interviews check whether you can build a retrieval system that finds the right text and makes the model use it. Expect questions on chunking, embeddings and similarity metrics, how HNSW and IVF trade recall for speed, picking a vector DB, hybrid search with BM25 and RRF, re-ranking, evaluation metrics and how to debug a bad answer. The small Python demos are pure standard library so you can see the maths; the library code shows real APIs. Read the 15-minute revision first, then switch to Quiz mode.
15-minute revision
- RAG = retrieve relevant chunks at query time and put them in the prompt. Use it for private, fresh or large knowledge. Fine-tuning changes behaviour and style, not reliable facts.
- Pipeline: ingest → parse → chunk → embed → index (offline), then query → retrieve → rerank → generate with citations (online).
- Most RAG failures are retrieval failures. Debug retrieval first: was the right chunk in the top-k at all?
- Chunking: start with recursive splitting at ~200–800 tokens with 10–20% overlap. Split by document structure (headings, sections) when you have it.
- Small-to-big / parent-child: search small precise chunks, then send their larger parent section to the LLM.
- Embeddings: the same model must embed documents and queries. Changing the model means re-embedding everything.
- If vectors are L2-normalised, cosine similarity = dot product, and Euclidean distance ranks the same way. Normalise, then use dot product (fastest).
- Exact (flat) search is O(N·d) per query. ANN indexes trade a little recall for big gains in latency: HNSW (graph), IVF (clusters), PQ (compression).
- HNSW: multi-layer proximity graph. Knobs:
M(links per node),ef_construction(build quality),ef_search(query recall vs speed). Fast and accurate but memory-heavy. - IVF: k-means into
nlistclusters, search onlynprobenearest clusters. PQ compresses vectors into short codes, e.g. 6 KB → 96 bytes, at some recall cost. - Hybrid search = BM25 (exact words, IDs, codes) + dense vectors (meaning). Merge with Reciprocal Rank Fusion: score = Σ 1/(k + rank), k ≈ 60.
- Re-ranking: a cross-encoder reads query and chunk together and is far more accurate than a bi-encoder, but too slow for the whole corpus. Retrieve 50–100, rerank to 5–10.
- Query transforms: rewriting (chat history → standalone question), multi-query, HyDE (embed a fake answer), decomposition (split multi-hop questions).
- Metadata filtering with ANN: post-filtering can return fewer than k results. Prefer DBs with filter-aware search (pre-filtering or iterative scan).
- Evaluate retrieval with recall@k, precision@k, MRR, nDCG. Evaluate generation with faithfulness (grounded in context) and answer relevance (RAGAS, LLM-as-judge).
- Multi-tenancy: enforce access control inside the retrieval query (tenant filter, namespaces, row-level security), never by asking the LLM to ignore data.
Foundations
Why RAG? RAG vs fine-tuning vs long context
RAG gives a model the right facts at query time without retraining it.
- LLMs only know their training data up to a cutoff. They do not know your private docs, and they may hallucinate when asked about them.
- Retrieval-Augmented Generation searches a knowledge base for the question, puts the best passages in the prompt, and asks the model to answer from those passages.
- Benefits: fresh data (update the index, not the model), citations you can check, per-user access control, and lower cost than fine-tuning.
- Fine-tuning is best for teaching a format, tone, task or domain style. It is a poor way to add facts: they are hard to update, hard to cite and can still be hallucinated.
- Long context (stuffing everything in the prompt) works for small, stable corpora. Anthropic notes that under about 200k tokens you can often skip RAG, especially with prompt caching. Past that, cost, latency and "lost in the middle" effects grow.
- They combine well: a fine-tuned model that follows your citation format, fed by RAG, with a long context window for many retrieved chunks.
Interview questions
- What is RAG and why use it?
- RAG vs fine-tuning: when do you pick each?
- Context windows are now 1M tokens. Is RAG dead?
- Does RAG eliminate hallucinations?
The RAG pipeline end to end
Offline: ingest, parse, chunk, embed, index. Online: rewrite, retrieve, rerank, generate, cite.
- Ingest: pull documents from sources (S3, Confluence, DBs, websites) with IDs, timestamps and permissions.
- Parse: turn PDF, HTML, DOCX and slides into clean text plus structure (headings, tables, page numbers).
- Chunk: split into retrievable units and attach metadata (doc id, section, page, tenant, ACL, updated_at).
- Embed and index: turn each chunk into a vector, store it in a vector index next to its text and metadata. Often also build a BM25 keyword index.
- Retrieve: embed the (possibly rewritten) query, get top-k from dense and/or keyword search, apply metadata filters.
- Rerank and generate: rerank candidates with a cross-encoder, keep the best few, build a prompt with numbered sources, and ask for an answer with citations.
Interview questions
- Walk me through a RAG pipeline.
- Which parts run offline and which at query time?
- Where would you add caching in a RAG system?
Document parsing: PDFs, tables & layout
Garbage in, garbage out: bad text extraction ruins retrieval before chunking even starts.
- PDFs store positioned glyphs, not paragraphs. Naive extraction breaks reading order, merges columns, and splits words with hyphens or headers/footers.
- Use layout-aware parsers (e.g. Unstructured, PyMuPDF, pdfplumber, Docling, cloud document AI) that return elements: title, paragraph, list, table, image, with page numbers.
- Scanned PDFs need OCR. Check text density per page to detect them.
- Tables: keep each table together, convert to Markdown or HTML, repeat the header row if you must split it, and optionally add an LLM-written summary for retrieval.
- Images and charts: caption them with a vision model, or embed them with a multimodal model. Keep a link to the original page for citations.
- Clean up: remove repeated headers, footers and page numbers; normalise whitespace and Unicode; keep headings as structure for chunking.
Interview questions
- How do you handle tables in RAG?
- Why is PDF extraction hard?
- How would you handle images and diagrams in documents?
Chunking & embeddings
Chunking strategies & overlap
Chunks must be small enough to be precise and large enough to make sense alone.
- Fixed-size: split every N tokens. Simple and predictable, but cuts sentences and ideas in half.
- Recursive: try to split on paragraphs, then lines, then sentences, then words, until each piece fits the size limit. A strong default.
- By structure: split on Markdown/HTML headings, code functions, legal clauses or FAQ entries. Best when documents have a clear structure.
- Semantic: embed sentences and start a new chunk where similarity between neighbours drops. Topic-aligned, but slower and not always better.
- Overlap (10–20%) repeats the end of one chunk at the start of the next so facts that cross a boundary are not lost.
- Trade-off: small chunks give precise matches but little context; large chunks carry context but dilute the embedding and waste prompt tokens.
Interview questions
- How do you choose chunk size?
- Why use overlap between chunks?
- Fixed-size vs recursive vs semantic chunking?
- What happens if chunks are too big or too small?
Parent-child, semantic & contextual chunks
Search on small, precise units but give the LLM larger, context-rich text.
- Parent-child (small-to-big): index small child chunks (sentences or ~200 tokens) for matching, then return their parent section (~1–2k tokens) to the LLM.
- Sentence-window retrieval: match a single sentence, then expand to N sentences before and after.
- Multi-vector: store several vectors per document, e.g. for its summary, its chunks and hypothetical questions it answers. All point to the same document.
- Contextual retrieval (Anthropic): before embedding, an LLM writes a 50–100 token note that places the chunk in its document ("This chunk is from ACME's Q2 2023 10-Q; revenue figures…") and prepends it. Apply the same to the BM25 index.
- Anthropic reported contextual embeddings + contextual BM25 cut failed retrievals by 49%, and by 67% with reranking. Prompt caching makes the per-chunk LLM calls cheap.
- Semantic chunking: compute similarity between consecutive sentences and cut where it drops below a threshold or percentile.
Interview questions
- What is parent-child (small-to-big) retrieval?
- What is contextual retrieval?
- How does semantic chunking work, and is it always better?
Embedding models, dimensions & normalisation
An embedding model maps text to a vector so that similar meanings land close together.
- Bi-encoder embedding models (e.g. OpenAI
text-embedding-3-small1536-d /-large3072-d, Cohere Embed, BGE, E5, GTE, Nomic) encode query and document separately, so documents can be pre-computed. - Pick models by retrieval scores on benchmarks like MTEB, by language and domain, max input tokens, dimension, cost, and whether you can self-host.
- Dimensions: more dims can hold more detail but cost more memory and slower search. 1M × 1536 float32 ≈ 6 GB of raw vectors.
- Matryoshka models (e.g. OpenAI v3 via the
dimensionsparameter) let you truncate vectors to fewer dims with modest quality loss. - Normalisation: divide by the L2 norm so every vector has length 1. Then cosine = dot product. Many APIs already return unit vectors.
- Some models need prefixes or instructions (E5 uses
query:/passage:). Using them wrongly hurts recall. - Query and documents must use the same model and version. A model change means a full re-embed and a new index.
Interview questions
- What is an embedding?
- Why normalise embeddings?
- Can you switch embedding models without re-indexing?
- How do you choose embedding dimensions?
Similarity metrics & brute-force top-k
Cosine compares direction, dot product adds magnitude, Euclidean measures straight-line distance.
- Cosine similarity = a·b / (‖a‖‖b‖), range −1 to 1. Ignores length. Most common for text.
- Dot product = a·b. Rewards longer vectors. Use it when the model was trained for it (some models encode relevance in magnitude).
- Euclidean (L2) distance = ‖a − b‖. Smaller is closer. For unit vectors, ‖a − b‖² = 2 − 2·cos, so it ranks exactly like cosine.
- Use the metric the embedding model was trained with. Check its model card.
- Brute-force (flat) search compares the query to every vector: exact, O(N·d). Fine up to roughly 100k–1M vectors with SIMD/GPU, and the ground truth for measuring ANN recall.
Interview questions
- Cosine similarity vs dot product vs Euclidean distance?
- Why is brute-force search not enough at scale?
- How do you pick a similarity threshold to say "nothing relevant found"?
Indexing & vector databases
ANN indexes: flat, IVF, HNSW, PQ
ANN indexes trade a little recall for much lower latency; each type spends memory and build time differently.
- Recall@k of an ANN index = fraction of the true k nearest neighbours (from flat search) that it returns. Typical targets are 0.95–0.99.
- Flat: exact, no build, O(N) per query. Best for small data or as ground truth.
- IVF: k-means into
nlistcells; each vector goes to its nearest centroid. A query searches only thenprobenearest cells. Needs training; recall drops when a neighbour sits in an unprobed cell. - HNSW: layered small-world graph. Search starts at the top layer, greedily moves to closer nodes, then descends. Knobs
M,ef_construction,ef_search. Excellent speed/recall, but needs RAM for vectors plus graph links, and deletes are costly. - PQ (product quantization): split each vector into
msub-vectors and replace each with the id of its nearest sub-centroid (often 1 byte). Huge compression; distances become approximate. Often combined: IVF-PQ, with a re-score using full vectors. - Other options: scalar quantization (float32 → int8, 4× smaller), binary quantization (1 bit per dim, 32× smaller, re-score needed), DiskANN (graph on SSD for billion scale).
Interview questions
- How does HNSW work?
- HNSW vs IVF: when would you choose each?
- What is product quantization?
- What do
M,ef_constructionandef_searchcontrol? - How do you measure if your ANN index is good enough?
Vector databases compared
A vector DB stores vectors with metadata and serves filtered ANN search; pick by scale, ops model and what you already run.
- A vector database adds to an ANN index: persistence, CRUD/upserts, metadata filtering, replication, sharding, access control and often hybrid search.
- A library like FAISS is only the index: you handle storage, updates, filters and serving yourself.
- pgvector keeps vectors next to your relational data in Postgres: ACID, joins, row-level security. Types:
vector(up to 2,000 dims indexed),halfvec(up to 4,000),bit,sparsevec. - Dedicated engines (Qdrant, Weaviate, Milvus, Pinecone) scale further and offer richer filtering, quantization, multi-tenancy and hybrid search out of the box.
- Chroma is easy for prototypes and local apps; Elasticsearch / OpenSearch suit teams that already run them and need strong BM25.
- Selection: data size, QPS, filtering needs, hybrid search, managed vs self-hosted, multi-tenancy, cost and team skills. "Use Postgres until it hurts" is a valid answer.
Interview questions
- What does a vector database give you over FAISS?
- pgvector or a dedicated vector DB?
- What are pgvector's distance operators?
- How do you design a vector store for 1 billion vectors?
Metadata filtering: pre vs post
Filters must run inside the vector search, or a strict filter can leave you with too few results.
- Store filterable metadata (tenant, doc type, language, date, product, ACL groups) with each vector and index it.
- Post-filtering: get top-k by vector, then drop non-matching rows. Simple, but with a selective filter you may get 0 results even though matches exist.
- Pre-filtering: filter first, then search only matching vectors. Exact for the filter, but brute force can be slow if the filtered set is large, and it breaks plain HNSW graph connectivity.
- Filter-aware ANN (Qdrant, Weaviate, Milvus, Pinecone) checks the filter during graph traversal or switches to flat search for very selective filters.
- pgvector applies filters after the index scan; since 0.8 iterative index scans keep scanning until enough rows pass. Partial indexes or partitioning per tenant also help.
- Use filters for hard constraints (permissions, language, date ranges). Use ranking boosts for soft preferences (newer is better).
Interview questions
- What is the difference between pre-filtering and post-filtering?
- A user filters to a small product line and gets no results. Why?
- How would you boost recent documents without excluding old ones?
Retrieval quality
Hybrid search: BM25 + dense & RRF
Keyword search catches exact terms, dense search catches meaning; fuse both for robust recall.
- Dense retrieval handles synonyms and paraphrases ("cancel subscription" ≈ "end my plan") but can miss exact tokens: error codes, SKUs, names, rare jargon.
- BM25 scores term matches with IDF (rare terms count more), term-frequency saturation (
k1, usually 1.2–2.0) and length normalisation (b, usually 0.75). - Learned sparse models (SPLADE, BGE-M3 sparse) expand terms with a model and sit between BM25 and dense.
- Fusion: scores from BM25 and cosine are on different scales, so do not add them raw. Reciprocal Rank Fusion uses only ranks: RRF(d) = Σ 1 / (k + rankᵢ(d)), with k = 60 by convention.
- Alternative: normalise scores (min-max or z-score) and use a weighted sum
α·dense + (1−α)·sparse. Needs tuning per dataset. - Weaviate, Qdrant, Milvus, Pinecone, Elasticsearch/OpenSearch and Vespa support hybrid queries natively; with pgvector you combine it with Postgres full-text search.
Interview questions
- Why use hybrid search?
- Explain Reciprocal Rank Fusion.
- How does BM25 differ from TF-IDF?
- Hybrid search with only Postgres?
Re-ranking with cross-encoders
Retrieve many candidates cheaply, then let a slower, more accurate model reorder the top few.
- Bi-encoder (embedding model): encodes query and document separately; documents are pre-computed, so search is fast, but the model never sees them together.
- Cross-encoder reranker: feeds
[query, document]together through a transformer and outputs a relevance score. Much more accurate because every query token attends to every document token. - Cross-encoders cost one model call per candidate per query, so you use them only on the top 20–100 candidates.
- Options: Cohere Rerank, Voyage rerank, Jina reranker, BGE-reranker,
cross-encoder/ms-marco-MiniLM-L-6-v2, or an LLM as reranker (listwise or pointwise prompting). - ColBERT (late interaction) keeps per-token vectors and scores with MaxSim: more accurate than bi-encoders, cheaper than cross-encoders, but much larger indexes.
- Reranking lets you send fewer, better chunks to the LLM, which cuts tokens and improves faithfulness.
Interview questions
- Bi-encoder vs cross-encoder?
- Why not use a cross-encoder for the whole corpus?
- How many candidates should you retrieve before reranking?
Query transformations: rewrite, HyDE, multi-query
User questions are often a poor search query; transform them before retrieving.
- Query rewriting / condensing: turn a follow-up ("and for Germany?") plus chat history into a standalone query ("refund time for orders shipped to Germany").
- Multi-query: an LLM writes 3–5 paraphrases; retrieve for each and fuse with RRF. Raises recall for vague questions.
- HyDE (Hypothetical Document Embeddings): the LLM writes a fake answer, and you embed that instead of the question, because answer-shaped text sits closer to real answer chunks.
- Decomposition: split multi-hop or comparative questions ("compare plan A and plan B limits") into sub-questions, retrieve for each, then combine.
- Step-back prompting: ask a more general question first ("what are the refund rules?") to retrieve background.
- Self-query / filter extraction: let an LLM pull structured filters (date, product, region) out of the question and apply them as metadata filters.
Interview questions
- What is HyDE and when does it help?
- How do you handle follow-up questions in a chat RAG app?
- A question needs facts from two documents. How do you retrieve them?
GraphRAG & agentic RAG
GraphRAG retrieves over entities and relationships; agentic RAG lets the model decide when and how to retrieve.
- GraphRAG (popularised by Microsoft): an LLM extracts entities and relationships from chunks into a knowledge graph, clusters it into communities and writes community summaries.
- Local search starts at entities in the question and walks their neighbours; global search maps over community summaries to answer "what are the main themes across all documents?" questions that top-k chunk search cannot answer.
- Costs: graph extraction is LLM-heavy at ingestion, and graphs are harder to update incrementally. Use it when questions are about relationships or whole-corpus themes.
- Agentic RAG: retrieval is a tool. The LLM decides whether to search, which source or tool to use (vector store, SQL, web, API), rewrites the query, checks results and loops until it has enough evidence.
- Patterns: router (pick the right index), ReAct / tool-calling loop, corrective RAG (grade retrieved docs; if poor, rewrite or use another source), self-RAG style self-critique.
- Trade-off: better on complex questions, but more LLM calls, higher latency, higher cost and harder debugging. Cap the number of steps.
Interview questions
- What is GraphRAG and when would you use it?
- What is agentic RAG?
- What is corrective RAG?
Generation & evaluation
Grounding, prompts & citations
Tell the model to answer only from numbered sources, cite them, and admit when the answer is missing.
- Grounding prompt: "Use only the sources below. If they do not contain the answer, say you don't know."
- Number each chunk (
[1],[2]) and include title, URL/page so citations map back to real documents. - Ask for inline citations after each claim. Then validate in code: every cited id must exist, and every sentence should have a citation.
- Put the most relevant chunks first (or last) to reduce "lost in the middle" effects; keep total context focused.
- Separate instructions from retrieved content (delimiters / XML tags) and treat document text as untrusted: it may contain prompt injection.
- Use low temperature for factual QA. Some APIs offer native citation features that return exact source spans.
Interview questions
- How do you make an LLM stick to the retrieved context?
- How do you implement citations?
- What is indirect prompt injection in RAG?
Evaluating RAG: retrieval metrics & RAGAS
Evaluate retrieval and generation separately so you know which half to fix.
- Build a golden set: real questions, the chunk/document ids that answer them, and ideal answers. Synthetic questions generated from chunks help bootstrap it.
- Retrieval metrics: recall@k (did we find the relevant chunks?), precision@k, hit rate, MRR (1/rank of first relevant), nDCG@k (graded, position-aware).
- Generation metrics: faithfulness / groundedness (claims supported by context), answer relevance (does it address the question), answer correctness vs a reference.
- RAGAS computes faithfulness, answer (response) relevancy, context precision and context recall, mostly with an LLM as judge. Other tools: TruLens, DeepEval, Arize Phoenix, LangSmith.
- LLM judges are noisy and biased: calibrate them against human labels, fix the judge model and prompt, and look at metric changes, not absolute values.
- Run evals in CI on every change to chunking, model, prompt or index params; monitor production with sampled judging and user feedback (thumbs, clicks on citations).
Interview questions
- How do you evaluate a RAG system?
- Recall@k vs precision@k vs MRR?
- What is faithfulness vs answer relevance?
- You have no labelled data. How do you start evaluating?
Common failure modes & fixes
Find which stage broke (parsing, chunking, retrieval, ranking, generation), then fix that stage.
- Missing content: the answer is not in the corpus. Fix: detect with low retrieval scores and make the model say so.
- Missed top-k: the right chunk exists but is not retrieved. Fix: hybrid search, better chunking, query rewriting, better or fine-tuned embeddings, larger k.
- Not in context after ranking: retrieved at rank 30, cut off before the LLM. Fix: reranker, better fusion.
- Not extracted: the chunk is in the prompt but the model ignores it (too much noise, lost in the middle). Fix: fewer, better chunks; ordering; stronger prompt.
- Wrong format / incomplete / unfaithful: the model mixes in prior knowledge or answers partially. Fix: grounding prompt, citations, faithfulness checks, structured output.
- Debug with the trace: question → rewritten query → retrieved ids + scores → reranked ids → prompt → answer. Check the golden chunk's rank at each step.
Interview questions
- Users say the RAG bot gives wrong answers. How do you debug?
- What is MMR and why use it?
- Retrieval recall is low for domain jargon. What do you try?
Production concerns
Freshness, updates & re-indexing
Keep the index in sync with sources incrementally, and plan for full re-embeds when models change.
- Give every chunk a stable id (
doc_id#chunk_n), a content hash,source_updated_atand the embedding model version. - Incremental sync: on change, re-chunk the document, embed only new or changed chunks, upsert them, and delete chunks that no longer exist. Use change events (webhooks, CDC) or periodic diffing.
- Deletes matter: removed or permission-revoked documents must leave the index quickly, for compliance and trust.
- Full re-index (new embedding model, new chunking): build a new index alongside the old one, backfill, evaluate, then switch an alias (blue-green) and drop the old.
- ANN indexes degrade with heavy churn (HNSW tombstones, IVF centroids drifting from data). Schedule compaction / rebuilds or re-training.
- For time-sensitive questions, store versions and dates in metadata and filter or boost by recency.
Interview questions
- How do you keep a RAG index up to date?
- How do you migrate to a new embedding model with zero downtime?
- How do you handle documents with many versions, like policies?
Access control & multi-tenancy
Enforce who can see what inside retrieval, before any text reaches the prompt.
- Threat: a user asks a question and retrieval returns chunks from another tenant or a document they cannot open. The LLM will happily summarise it.
- Tenant isolation options: separate index/collection per tenant (strong isolation, more overhead), namespaces / partitions, or a shared index with a mandatory tenant_id filter.
- Document-level ACLs: store allowed groups/users on each chunk and filter by the caller's groups. Sync permission changes from the source system quickly.
- In Postgres you can use row-level security so every query is filtered by the session's tenant automatically.
- Apply the same filter to every retriever (dense, BM25, caches). A shared semantic answer cache can leak across users.
- Also: encrypt at rest, audit-log retrievals, redact PII at ingestion if needed, and honour delete requests (GDPR) in the vector store and backups.
Interview questions
- How do you enforce document permissions in RAG?
- One index per tenant or a shared index with filters?
- A permission is revoked in SharePoint. What must happen in your RAG system?
Cost & latency optimisation
The LLM call usually dominates latency and cost; shrink the prompt and parallelise the rest.
- Typical latency budget: query rewrite (LLM) 200–800 ms, embed query 20–100 ms, ANN search 5–50 ms, rerank 50–300 ms, generation 0.5–5 s. Streaming hides much of generation.
- Cut prompt tokens: rerank and keep fewer chunks, compress or trim chunks, avoid duplicates. Input tokens are the main per-query cost.
- Cache: query embeddings, retrieval results, prompt caching for stable prefixes, semantic answer cache (scoped per tenant).
- Parallelise: run BM25 and dense retrieval, and multi-query searches, concurrently.
- Index cost: quantize vectors (int8/binary + re-score), reduce dimensions (Matryoshka), use disk-based indexes, or tiered storage for cold tenants.
- Ingestion cost: batch embedding calls, embed only changed chunks, use cheaper models for enrichment, and skip contextual enrichment where eval shows no gain.
- Use smaller / cheaper models where quality allows (query rewriting, routing, grading) and route only hard questions to the large model.
Interview questions
- Your RAG endpoint has 6 s p95 latency. How do you reduce it?
- How do you reduce vector storage cost at scale?
- What is a semantic cache and what are its risks?