AI

RAG Interview Questions and Answers (With Python Code)

RAG Interview Questions and Answers (With Python Code)

Short answer: RAG interviews test four things: chunking and search, embeddings and vector indexes, measuring quality, and how the system fails in production. Strong candidates answer with trade-offs and numbers, not definitions. They also know when RAG is the wrong tool, for example when fine-tuning or a long prompt fits better.

Below are 30 questions in six groups. Each has a model answer and the common wrong answer interviewers listen for. Six answers include small Python programs you can run with no installs.

How to use this list

RAG stands for retrieval-augmented generation. The idea: search your own documents first, then give the best passages to a large language model (LLM) so it answers from them. If you have never built one, start with Crio's RAG explained, with code for a from-scratch walkthrough. Then come back here to practise the interview version.

All code below uses only the Python 3 standard library. Save each block under the file name in its first line, in one folder, and run it with python3 <file>. Two of the programs import bm25.py, so keep them together. Every output shown was produced by running the code with Python 3.12.8 on 21 November 2026. No LLM was called, so your output will match exactly.

The running example is a small help centre for a food-delivery app: refunds, cancellations, delivery fees. The articles are invented for practice.

Basics

1. What is RAG? Explain it with an example.

Strong answer: RAG combines two kinds of memory. One is the knowledge stored inside the model's weights, called parametric memory. The other is an outside document index the model can search, called non-parametric memory. The standard reference is the 2020 paper by Lewis et al. It introduced RAG models that pair a BART text generator with a dense vector index of Wikipedia. Example: a user asks a food-delivery bot "how long does a refund take?". The system finds the refund policy article, puts it in the prompt and the model answers "5 to 7 working days", citing that article.

Watch out for: "RAG is a vector database." The database is one part. RAG is the whole loop of search, then generate from what was found.

2. Why not just ask the LLM? What problems does RAG solve?

Strong answer: Three problems. The model's knowledge stops at its training date. It has never seen your private documents. And it cannot show where an answer came from. RAG fixes all three because the facts live in an index you control. The original paper tested this directly. It swapped a December 2016 Wikipedia index for a December 2018 one and asked about 82 world leaders who had changed. With the matching index, accuracy was 70% (2016) and 68% (2018). With the wrong index, it fell to 12% and 4%. Updating knowledge meant replacing the index, not retraining.

Watch out for: "RAG stops hallucinations." It reduces them when retrieval finds the right text. If retrieval fails, the model can still make things up.

3. Walk me through a RAG pipeline end to end.

Strong answer: Split it into two phases. Indexing runs when documents change: load documents, split them into chunks, turn each chunk into an embedding (a list of numbers that captures meaning) and store it. Querying runs on every question: embed it, retrieve the top chunks and optionally rerank them. Then put them in a prompt that says to answer only from the context, generate, and return citations. Finally, say where you would measure: retrieval quality after step 2 of querying, answer quality at the end.

Watch out for: Describing only the happy path. Interviewers want to hear what happens when nothing relevant is found. A good system says "I don't know" instead of guessing.

4. RAG vs fine-tuning: when do you pick which?

Strong answer: Fine-tuning changes the model's weights. It is good for teaching behaviour: a tone, an output format, a narrow task. RAG is better for facts that change or must be cited. One study, Ovadia et al. (2023), compared unsupervised fine-tuning with RAG for adding knowledge. RAG consistently did better, both for facts seen in training and for new facts. The authors also found models struggle to learn new facts through unsupervised fine-tuning. In practice teams often combine the two: fine-tune for format, retrieve for facts.

Watch out for: "Fine-tune the model on our documents so it knows them." It is costly to redo for every update, and the model still cannot cite a source.

5. RAG vs long context vs CAG: which would you choose?

Strong answer: It depends on how big the knowledge is and how often it changes.

  • Long context means pasting all documents into the prompt on every call. It is simple but you pay to process every token each time.
  • CAG, or cache-augmented generation, comes from the paper "Don't Do RAG" (Chan et al., arXiv 2412.15605, WWW '25 short paper). It preloads all documents into the model's context once and saves the model's key-value (KV) cache, its internal state after reading them. Each question then reuses that cache with no retrieval step.
  • RAG retrieves only the few chunks a question needs.

In the CAG paper, Llama 3.1 8B with a preloaded cache scored the highest BERTScore in most tests on SQuAD and HotPotQA. It was compared against BM25 and dense-retrieval RAG. The gap narrowed as the data grew. The authors state the limit plainly: the method "becomes impractical for significantly larger datasets". They suggest hybrids that preload a base context and retrieve only for edge cases.

Fine-tuningLong contextCAGRAG
Where knowledge livesModel weightsPrompt, every callPrecomputed KV cacheExternal index
Knowledge sizeNew facts are hard to teach this wayMust fit the context windowMust fit the context windowCan be very large
Updating knowledgeRetrainEdit the promptRebuild the cacheRe-index changed documents
Retrieval errors possibleNo retrievalNo retrievalNo retrievalYes
Can cite sourcesNoYesYesYes
Good forStyle, format, narrow tasksSmall, one-off document setsSmall, stable knowledge basesLarge or changing knowledge

Watch out for: "Context windows are huge now, so RAG is dead." Fitting text in the window is not the same as using it well (see question 25). Long prompts also cost more on every call.

6. What is the difference between RAG-Sequence and RAG-Token?

An advanced follow-up. Strong answer: Both come from the original paper. RAG-Sequence uses the same retrieved document to generate the whole answer, then combines answers across the top documents. RAG-Token can draw on a different document for each generated token, so one answer can mix facts from several passages. For a short answer of one token, the two are the same.

Watch out for: Confusing RAG-Token with "retrieve again after every token". Both variants retrieve once per question. They differ only in how the top documents are combined during generation.

Retrieval and chunking

7. Why do we split documents into chunks at all?

Strong answer: Three reasons. Embedding models accept a limited input length. One vector for a 40-page PDF blurs every topic together, so search becomes vague. And the prompt has a budget: you want the three paragraphs that answer the question, not the whole manual. The original RAG paper split Wikipedia into disjoint 100-word chunks, 21 million in total.

Watch out for: "Smaller chunks are always better." Very small chunks lose the context that makes them meaningful, like a sentence that says "this fee" without saying which fee.

8. Fixed-size, overlapping or sentence-aware chunks: what is the trade-off?

Strong answer: Fixed-size chunks are simple and predictable, but they cut sentences in half. Overlap repeats a few words between neighbours, so a fact cut at one boundary may be whole in the next chunk. Sentence-aware chunking packs whole sentences up to a size limit. This program checks whether the refund sentence survives each method:

# chunking.py: fixed-size chunks, overlap, and sentence-aware chunks
import re

text = (
    "Orders can be cancelled free of charge until the restaurant accepts them. "
    "After that, a cancellation fee applies. If an order arrives damaged, "
    "report it in the app within 2 hours. Approved refunds go back to the "
    "original payment method within 5 to 7 working days. Cash on delivery "
    "refunds are credited to the app wallet instead."
)
fact = "Approved refunds go back to the original payment method within 5 to 7 working days."


def chunk_words(text, size, overlap=0):
    words = text.split()
    step = size - overlap
    chunks = []
    for start in range(0, len(words), step):
        chunks.append(" ".join(words[start:start + size]))
        if start + size >= len(words):
            break
    return chunks


def chunk_sentences(text, max_words):
    sentences = re.split(r"(?<=[.!?])\s+", text)
    chunks, current = [], []
    for s in sentences:
        if current and len(" ".join(current + [s]).split()) > max_words:
            chunks.append(" ".join(current))
            current = []
        current.append(s)
    chunks.append(" ".join(current))
    return chunks


def report(name, chunks, show=False):
    whole = [i for i, c in enumerate(chunks) if fact in c]
    print(f"{name}: {len(chunks)} chunks, refund sentence whole in chunk {whole}")
    if show:
        for i, c in enumerate(chunks):
            print(f"  [{i}] {c}")


print(f"text: {len(text.split())} words; refund sentence: {len(fact.split())} words")
report("fixed 16, overlap 0", chunk_words(text, 16), show=True)
report("fixed 16, overlap 4", chunk_words(text, 16, 4))
report("fixed 16, overlap 6", chunk_words(text, 16, 6))
report("sentences, max 30 words", chunk_sentences(text, 30), show=True)

Output:

text: 57 words; refund sentence: 15 words
fixed 16, overlap 0: 4 chunks, refund sentence whole in chunk []
  [0] Orders can be cancelled free of charge until the restaurant accepts them. After that, a cancellation
  [1] fee applies. If an order arrives damaged, report it in the app within 2 hours. Approved
  [2] refunds go back to the original payment method within 5 to 7 working days. Cash on
  [3] delivery refunds are credited to the app wallet instead.
fixed 16, overlap 4: 5 chunks, refund sentence whole in chunk []
fixed 16, overlap 6: 6 chunks, refund sentence whole in chunk [3]
sentences, max 30 words: 3 chunks, refund sentence whole in chunk [1]
  [0] Orders can be cancelled free of charge until the restaurant accepts them. After that, a cancellation fee applies.
  [1] If an order arrives damaged, report it in the app within 2 hours. Approved refunds go back to the original payment method within 5 to 7 working days.
  [2] Cash on delivery refunds are credited to the app wallet instead.

Look at chunk [2] with no overlap. It says "within 5 to 7 working days" right next to "Cash on", which invites a wrong answer about cash refunds. An overlap of 4 still split the sentence; an overlap of 6 kept it whole only because of where the windows happened to fall. A fixed window guarantees an L-word span is whole only when overlap is at least L − 1, here 14 words. Sentence-aware chunking kept it whole with fewer chunks.

Watch out for: "Use 20% overlap, it always works." Overlap raises your chunk count and index size, and as the output shows, it only improves the odds.

9. How do you choose chunk size and top-k?

Strong answer: By measurement, not a rule of thumb. Build a labelled set of questions (question 23), then try a few chunk sizes and values of k, the number of chunks retrieved. Track recall@k (question 21) and the token cost of the prompt. Bigger chunks and larger k usually raise recall but add noise and cost. Also respect document structure: split on headings, sections and table rows before falling back to word counts.

Watch out for: Quoting one "best" chunk size as a universal fact. The right size depends on your documents, your questions and your embedding model.

10. Sparse vs dense retrieval: how does BM25 work?

Strong answer: Sparse retrieval matches words. BM25 is the standard formula, described in full by Robertson and Zaragoza (2009). A document scores higher when it contains rare query words, contains them more often (with diminishing returns), and is not unusually long. Two knobs control this: k1 for the diminishing returns and b for length normalisation. Their review reports experiments suggesting 0.5 < b < 0.8 and 1.2 < k1 < 2 work well in many cases. Elasticsearch uses BM25 by default with k1 = 1.2 and b = 0.75. Dense retrieval compares embeddings instead, so it can match "money back" to "refund". Here is BM25 from scratch, using the same idf formula as Apache Lucene:

# bm25.py: a tiny BM25 keyword retriever over 10 help-centre articles
import math
import re
from collections import Counter

DOCS = {
    "d1": "Orders can be cancelled free of charge until the restaurant accepts the order.",
    "d2": "Approved refunds go back to the original payment method within 5 to 7 working days.",
    "d3": "Cash on delivery refunds are credited to the app wallet instead of a bank account.",
    "d4": "The delivery fee depends on distance and is shown before you pay.",
    "d5": "Report a damaged or missing item in the app within 2 hours of delivery.",
    "d6": "Gold members get free delivery on orders above Rs 199.",
    "d7": "You can pay with UPI, cards, net banking or cash on delivery.",
    "d8": "To change your delivery address, edit the order before the restaurant accepts it.",
    "d9": "Wallet balance never expires and can be used on any order.",
    "d10": "Contact support from the Help tab; chat is open from 8 am to midnight.",
}
STOP = {"a", "an", "the", "of", "to", "on", "is", "and", "or", "in", "can", "be",
        "you", "your", "my", "i", "do", "does", "how", "what", "it", "are", "for", "from"}


def tokens(text):
    words = [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP]
    return [w[:-1] if len(w) > 3 and w.endswith("s") else w for w in words]  # refunds -> refund


class BM25:
    def __init__(self, docs, k1=1.2, b=0.75):
        self.ids = list(docs)
        self.tf = {d: Counter(tokens(t)) for d, t in docs.items()}
        self.len = {d: sum(c.values()) for d, c in self.tf.items()}
        self.avg = sum(self.len.values()) / len(docs)
        df = Counter(w for c in self.tf.values() for w in c)
        n = len(docs)
        self.idf = {w: math.log(1 + (n - f + 0.5) / (f + 0.5)) for w, f in df.items()}
        self.k1, self.b = k1, b

    def score(self, query, d):
        s = 0.0
        for w in tokens(query):
            f = self.tf[d][w]
            if f:
                norm = self.k1 * (1 - self.b + self.b * self.len[d] / self.avg)
                s += self.idf[w] * f * (self.k1 + 1) / (f + norm)
        return s

    def search(self, query, k=3):
        scored = [(d, round(self.score(query, d), 3)) for d in self.ids]
        scored = [x for x in scored if x[1] > 0]           # no shared word, no result
        return sorted(scored, key=lambda x: -x[1])[:k]


if __name__ == "__main__":
    bm25 = BM25(DOCS)
    for q in ["how long does a refund take", "refund for cash on delivery order",
              "when will I get my money back"]:
        print(q, "->", bm25.search(q))

Output:

how long does a refund take -> [('d3', 1.454), ('d2', 1.275)]
refund for cash on delivery order -> [('d3', 3.424), ('d7', 2.067), ('d8', 1.462)]
when will I get my money back -> [('d6', 1.955), ('d2', 1.715)]

Two lessons hide in this output. For "how long does a refund take", the right article d2 comes second. BM25 does not know that "how long" relates to "5 to 7 working days", and d3 wins on being shorter. For "money back", the word "get" appears only in d6, so it earns a high weight and puts the Gold membership article first. Rare words are not always meaningful words.

On research benchmarks, dense retrieval has often won. The DPR paper (Karpukhin et al., 2020) beat a Lucene BM25 system by 9 to 19 points in top-20 passage accuracy. But the CAG paper saw BM25 beat dense retrieval on its datasets. Keywords still win on exact terms like error codes, product IDs and names.

Watch out for: "BM25 is outdated." It is cheap, needs no model, explains its scores, and handles exact matches that embeddings blur.

11. What is hybrid search, and how does reciprocal rank fusion work?

Strong answer: Hybrid search runs keyword and vector search, then merges the two ranked lists. The scores are on different scales, so you merge by rank. Reciprocal rank fusion (RRF), from Cormack, Clarke and Büttcher (SIGIR 2009), gives each document 1 / (k + rank) from every list and adds them up. The paper fixed k = 60 in a pilot study and found the exact choice was not critical. In this program, the vector lists are made up by hand to show the arithmetic; they are not model output:

# rrf.py: reciprocal rank fusion of a keyword ranking and a vector ranking
from bm25 import BM25, DOCS


def rrf(rankings, k=60):
    scores = {}
    for ranking in rankings:
        for rank, d in enumerate(ranking, start=1):
            scores[d] = scores.get(d, 0.0) + 1 / (k + rank)
    return sorted(scores.items(), key=lambda x: -x[1])


bm25 = BM25(DOCS)
# Made-up vector-search results, to show the arithmetic. A real embedding
# model would produce its own list; these are NOT outputs of a model.
vector = {
    "when will I get my money back": ["d2", "d9", "d3", "d6"],
    "what time can I talk to someone": ["d10", "d5", "d7"],
}
for q, vec in vector.items():
    kw = [d for d, _ in bm25.search(q, k=4)]
    fused = rrf([kw, vec])
    print(q)
    print("  keyword:", kw, " vector:", vec)
    print("  fused:  ", [(d, round(s, 4)) for d, s in fused[:3]])
print("check d2:", round(1 / (60 + 2) + 1 / (60 + 1), 4))

Output:

when will I get my money back
  keyword: ['d6', 'd2']  vector: ['d2', 'd9', 'd3', 'd6']
  fused:   [('d2', 0.0325), ('d6', 0.032), ('d9', 0.0161)]
what time can I talk to someone
  keyword: []  vector: ['d10', 'd5', 'd7']
  fused:   [('d10', 0.0164), ('d5', 0.0161), ('d7', 0.0159)]
check d2: 0.0325

d2 was second for keywords and first for vectors, so it scores 1/62 + 1/61 = 0.0325 and wins. A document found by both lists beats one that only a single list liked. When keyword search finds nothing, RRF simply falls back to the vector list.

Watch out for: "Just add the BM25 score and the cosine score." BM25 scores are unbounded and cosine is between −1 and 1, so a plain sum lets one list dominate.

12. What is a reranker? Bi-encoder vs cross-encoder?

Strong answer: A bi-encoder embeds the question and each document separately, then compares vectors. Documents can be embedded ahead of time, so search is fast. DPR, the retriever used in the original RAG paper, is a bi-encoder. A cross-encoder reads the question and one document together and outputs a relevance score. Nogueira and Cho (2019) did this with BERT, feeding the query and passage as one input, to rerank BM25's top 1,000 passages. It is more accurate but must run once per question-document pair. So you run it only on a short candidate list from the first-stage retriever.

Watch out for: "Use the cross-encoder for the whole corpus." That means one model call per document per question, which does not scale.

13. What is query rewriting, and what is HyDE?

Strong answer: User questions are often short or vague, so you change the query before searching. Common moves: expand abbreviations, split a two-part question into two searches, or rewrite a follow-up like "and for COD?" into a full question using chat history. HyDE (Gao et al., 2022) goes further. An LLM writes a hypothetical answer document, which may contain false details. You embed that fake document and retrieve real documents near it. The real documents ground the answer, not the fake one.

Watch out for: Forgetting the cost. Every rewrite is an extra LLM call that adds latency, so measure whether recall actually improves.

Embeddings and vector databases

14. What is an embedding?

Strong answer: An embedding is a fixed-length list of numbers that an encoder model produces for a piece of text. The model is trained so that texts with similar meaning get vectors pointing in similar directions. "How long does a refund take" and "when will I get my money back" share few words but should land close together. You can only compare vectors made by the same model.

Watch out for: "Each number stands for a topic." Individual dimensions usually have no human-readable meaning. Only distances between vectors matter.

15. Cosine similarity, dot product or Euclidean distance?

Strong answer: Cosine similarity compares direction and ignores length. Dot product grows with length. Euclidean (L2) distance measures straight-line distance, so long vectors look far away. Here they are on toy vectors:

# similarity.py: cosine similarity, dot product and L2 distance on toy vectors
import math


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def norm(a):
    return math.sqrt(dot(a, a))


def cosine(a, b):
    return dot(a, b) / (norm(a) * norm(b))


def l2(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))


# Toy 4-number "embeddings". Real ones have hundreds of numbers.
query = [0.9, 0.1, 0.0, 0.3]            # "how long does a refund take"
docs = {
    "refund_policy": [0.8, 0.2, 0.1, 0.4],
    "refund_policy_x3": [2.4, 0.6, 0.3, 1.2],   # same direction, 3 times longer
    "delivery_fee": [0.1, 0.9, 0.3, 0.0],
}
print(f"{'doc':<17} {'cosine':>7} {'dot':>6} {'L2':>6}")
for name, v in docs.items():
    print(f"{name:<17} {cosine(query, v):>7.3f} {dot(query, v):>6.3f} {l2(query, v):>6.3f}")

unit = lambda a: [x / norm(a) for x in a]
q, d = unit(query), unit(docs["refund_policy_x3"])
print(f"after normalising: dot = {dot(q, d):.3f}, cosine = {cosine(q, d):.3f}")

Output:

doc                cosine    dot     L2
refund_policy       0.978  0.860  0.200
refund_policy_x3    0.978  2.580  1.844
delivery_fee        0.198  0.180  1.208
after normalising: dot = 0.978, cosine = 0.978

The scaled refund vector has the same cosine (0.978) but triple the dot product. By L2 it is farther away (1.844) than the unrelated delivery-fee article (1.208). Once vectors are normalised to length 1, dot product equals cosine. The FAISS documentation says the same: cosine similarity "is a dot product on normalized vectors". That is why many systems normalise once and use the cheaper dot product.

Watch out for: Picking a metric at random. Use the metric the embedding model was trained with, which its documentation states.

16. Do you need a vector database?

Strong answer: Not always. For a small corpus, exact search over an in-memory array is often enough. FAISS is a library, not a database: Meta built it for "efficient similarity search and clustering of dense vectors". pgvector adds vector search to PostgreSQL, so vectors sit next to your normal rows with transactions, joins and backups. Dedicated vector databases are a third option. Pick based on data size, filtering needs and what your team already runs.

Watch out for: "RAG needs a vector database." The original RAG paper used a FAISS index. Many production systems use the Postgres they already have.

17. Exact vs approximate nearest neighbour search: how does HNSW work?

Strong answer: Exact search compares the query with every vector. pgvector does this by default, which "provides perfect recall", but it slows down as data grows. Approximate nearest neighbour (ANN) indexes trade a little recall for speed. HNSW (Malkov and Yashunin, 2016) builds a stack of graph layers. The bottom layer holds every vector; each higher layer holds a smaller random subset with longer links. A search starts at the top and walks down, and the paper reports logarithmic scaling. pgvector's docs compare it with IVFFlat: HNSW gives a better speed-recall trade-off but builds slower and uses more memory.

Watch out for: "Adding an index cannot change results." pgvector's README warns that after adding an approximate index, "you will see different results for queries".

18. How much memory do 10 million embeddings need?

Strong answer: Do the arithmetic out loud: count × dimensions × bytes per number. Assume 768 numbers per vector:

# index_size.py: raw memory for 10 million embeddings of 768 numbers each
n, dim = 10_000_000, 768
for name, bytes_per_number in [("float32", 4), ("float16", 2), ("1-bit", 1 / 8)]:
    total = n * dim * bytes_per_number
    print(f"{name:<8} {dim * bytes_per_number:>6.0f} bytes/vector  "
          f"{total / 1e9:>6.2f} GB  ({total / 2**30:.2f} GiB)")

Output:

float32    3072 bytes/vector   30.72 GB  (28.61 GiB)
float16    1536 bytes/vector   15.36 GB  (14.31 GiB)
1-bit        96 bytes/vector    0.96 GB  (0.89 GiB)

Raw float32 vectors need 30.72 GB before any index overhead. Half precision halves that. Binary quantization keeps one bit per number, a 32 times saving, but loses detail. pgvector supports both (halfvec and binary_quantize) and shows a pattern for the loss: fetch 20 candidates by the binary code, then re-rank them with the original vectors.

Watch out for: Forgetting the index itself. An HNSW graph stores neighbour links on top of the vectors, so real memory use is higher.

19. What happens when you switch to a new embedding model?

Strong answer: You must re-embed every chunk. Vectors from two different models live in different spaces, so a query embedded by model B cannot be compared with documents embedded by model A. Plan it like a database migration: build the new index alongside the old one, run your evaluation set on both, then switch traffic. Store the model name and version with every vector so you can tell them apart.

Watch out for: "Only embed new documents with the new model." Mixing models in one index silently breaks search for all old documents.

Evaluation

20. How do you evaluate a RAG system?

Strong answer: Evaluate retrieval and generation separately, because they fail separately. For retrieval, ask whether the right chunk is in the top k, using recall@k and MRR. For generation, ask whether the answer is supported by the retrieved context and whether it addresses the question. The Ragas paper (Es et al., 2023) names three dimensions: faithfulness, answer relevance and context relevance. It uses an LLM as the judge, so no hand-written reference answers are needed.

Watch out for: Judging only the final answer. If an answer is wrong, you then cannot tell whether search or the model caused it.

21. Compute recall@k and MRR for a retriever.

Strong answer: recall@k is the share of relevant documents found in the top k. MRR, mean reciprocal rank, averages 1 / rank of the first relevant result: 1 for rank 1, 0.5 for rank 2, 0 if never found. This program scores the BM25 retriever from question 10 on 7 labelled questions:

# evaluate.py: recall@k and MRR for the BM25 retriever on 7 labelled questions
from bm25 import BM25, DOCS

# question -> the article(s) a correct answer needs (labelled by hand)
LABELS = {
    "how long does a refund take": {"d2"},
    "refund for cash on delivery order": {"d3"},
    "when will I get my money back": {"d2"},
    "can I cancel after the restaurant accepts": {"d1"},
    "my food came damaged": {"d5"},
    "is delivery free for gold members": {"d6"},
    "what time can I talk to someone": {"d10"},
}


def recall_at_k(ranked, relevant, k):
    return len(set(ranked[:k]) & relevant) / len(relevant)


def reciprocal_rank(ranked, relevant):
    for rank, d in enumerate(ranked, start=1):
        if d in relevant:
            return 1 / rank
    return 0.0


bm25 = BM25(DOCS)
r1 = r3 = rr = 0.0
print(f"{'question':<42} {'top 3':<16} {'rank':>4}")
for q, rel in LABELS.items():
    ranked = [d for d, _ in bm25.search(q, k=10)]
    rank = next((i for i, d in enumerate(ranked, start=1) if d in rel), "-")
    print(f"{q:<42} {','.join(ranked[:3]):<16} {rank:>4}")
    r1 += recall_at_k(ranked, rel, 1)
    r3 += recall_at_k(ranked, rel, 3)
    rr += reciprocal_rank(ranked, rel)
n = len(LABELS)
print(f"recall@1 = {r1 / n:.3f}  recall@3 = {r3 / n:.3f}  MRR = {rr / n:.3f}")

Output:

question                                   top 3            rank
how long does a refund take                d3,d2               2
refund for cash on delivery order          d3,d7,d8            1
when will I get my money back              d6,d2               2
can I cancel after the restaurant accepts  d1,d8               1
my food came damaged                       d5                  1
is delivery free for gold members          d6,d1,d4            1
what time can I talk to someone                                -
recall@1 = 0.571  recall@3 = 0.857  MRR = 0.714

Four questions hit rank 1, two hit rank 2 and one found nothing. So MRR = (4 × 1 + 2 × 0.5 + 0) / 7 = 0.714. The miss is a pure vocabulary problem: "talk to someone" shares no word with "Contact support". This is the kind of miss that vector search is meant to catch (question 11).

Watch out for: Reporting accuracy on 7 questions as if it meant something. A real evaluation set needs enough questions to cover your main question types; 7 is only enough to check the code.

22. What is faithfulness, and how is it different from correctness?

Strong answer: Faithfulness asks whether every claim in the answer is supported by the retrieved context. Correctness asks whether the answer is true. They can disagree. If the help centre still has last year's refund policy, a faithful answer is wrong. In Ragas, an LLM splits the answer into short statements and checks each against the context. Faithfulness is supported statements divided by total statements.

Watch out for: Treating an LLM judge as ground truth. Spot-check its verdicts by hand, because the judge can be wrong too.

23. How do you build an evaluation set?

Strong answer: Start from real user questions, from search logs or support tickets, not from questions you wrote while looking at the documents. Label which chunks answer each one. Include hard cases on purpose: synonyms, typos, multi-part questions, and questions the documents cannot answer, where the right output is "I don't know". Re-run the set on every change to chunking, embeddings or prompts.

Watch out for: Only testing questions you know the system handles. An evaluation set with no failures tells you nothing.

Production and failure modes

24. What are the most common ways a RAG system fails?

Strong answer: Walk through the pipeline in order.

  • Missing content: the answer is not in the documents at all.
  • Missed retrieval: the answer exists but is not in the top k (bad chunking, vocabulary mismatch).
  • Lost in context: the right chunk is retrieved but the model ignores it (question 25).
  • Stale or conflicting documents: two versions of a policy, and retrieval picks the old one.
  • Over-answering: the model fills gaps from its own memory instead of saying it does not know.

Then say how you would detect each one: retrieval metrics, faithfulness checks and logging of retrieved chunks.

Watch out for: Blaming "the LLM" for every bad answer. Most can be traced to retrieval once you log what was retrieved.

25. What is the "lost in the middle" problem?

Strong answer: Liu et al. (2023) tested models on multi-document question answering. Performance was often highest when the relevant passage was at the start or end of the input. It dropped significantly when the passage sat in the middle of a long context, even for models built for long context. Practical fixes: retrieve fewer, better chunks, rerank so the best chunk comes first, and do not pad the prompt.

Watch out for: "More context is always safer." Past a point, extra chunks hide the useful one.

26. How can a retrieved document attack your system?

Strong answer: Through indirect prompt injection. Greshake et al. (2023) showed attackers can plant instructions in data likely to be retrieved, such as a web page the system might fetch. The model reads that text as instructions. They showed it can lead to data theft and can control how other APIs are called. Defences: treat retrieved text as data and wrap it in clear delimiters. Give the model the fewest tools and permissions it needs. Require human approval for any action with side effects.

Watch out for: "Our system prompt tells the model to ignore injected instructions." That helps a little, but the paper reported that effective mitigations were lacking. Limit what a fooled model can do.

27. How do you make sure users only see documents they are allowed to see?

Strong answer: Filter by permission at retrieval time, using metadata such as team, tenant or role stored with each chunk. Never retrieve everything and ask the model to hide what the user should not see. There is a catch with approximate indexes. pgvector applies filters after the index scan. Its README gives an example: if a condition matches 10% of rows, HNSW with the default hnsw.ef_search of 40 returns about 4 rows on average. Fix it with iterative index scans (pgvector 0.8.0 and later), a separate index per tenant, or a larger search size.

Watch out for: Relying on the prompt for security. Anything placed in the prompt can leak in the answer.

28. How do you keep the index fresh and control latency and cost?

Strong answer: For freshness, re-index only changed documents: store a content hash per document and re-embed when it changes. Delete the vectors of removed documents too, or old policies keep coming back. For latency, retrieve fewer chunks, cache answers to frequent questions, and use a reranker only on a short candidate list. For cost, remember that every retrieved chunk adds prompt tokens on every call. Measure cost and quality together before raising k.

Watch out for: Rebuilding the whole index nightly "to be safe" without measuring. It works for small data but becomes slow and expensive as the corpus grows.

Agentic RAG

29. What is agentic RAG? How do Self-RAG and CRAG differ?

Strong answer: Plain RAG retrieves once, then answers. In agentic RAG, search becomes a tool the model calls when it chooses. It can skip retrieval, rewrite the query, or search several times for a multi-part question. It builds on the ReAct pattern (Yao et al., 2022), where the model alternates reasoning steps with actions such as calling a search API. Two research versions are worth naming:

  • Self-RAG (Asai et al., 2023) trains one model to retrieve only when needed and to critique its retrieved passages and its own output using special "reflection tokens".
  • CRAG, Corrective RAG (Yan et al., 2024), adds a lightweight evaluator that scores how good the retrieved documents are. Based on that confidence, it can trigger other actions, including a web search.

Watch out for: "Agentic RAG is always better." Each extra step adds model calls, latency and new ways to fail.

30. When would you use GraphRAG, and when is agentic RAG overkill?

Strong answer: Plain RAG struggles with global questions about a whole collection, like "What are the main themes in the dataset?". No single chunk holds that answer. GraphRAG (Edge et al., 2024) uses an LLM to build an entity graph from the documents, then writes summaries for groups of related entities. A question is answered from those summaries. Agentic steps are overkill when one retrieval already answers most questions. Measure plain RAG on your evaluation set first. Then target the specific question types it gets wrong.

Watch out for: Choosing an architecture before measuring. Interviewers like candidates who say "I would check the failing queries first".

Where RAG breaks: limits to admit in an interview

  • Retrieval does not check truth. If the documents are wrong or outdated, RAG quotes them with confidence.
  • Small, stable knowledge may not need it. The CAG paper's point is that a preloaded cache can beat retrieval when everything fits in the context window.
  • Every chunk costs tokens. Larger k and long chunks raise the bill on every call.
  • Security is not solved. Retrieved text can carry injected instructions, and permission filters must run before retrieval, not in the prompt.
  • Global questions need more than top-k search, which is why approaches like GraphRAG exist.

Saying these out loud signals that you have built or debugged a real system.

FAQ

What are the most asked RAG interview questions?

Expect "what is RAG", "RAG vs fine-tuning", how chunking works, how vector search works, and how you would evaluate a RAG system. Experienced candidates also get failure modes, hybrid search with reranking, access control and agentic RAG. Practise answering with a trade-off and a number, and be ready to write recall@k or cosine similarity by hand.

Is RAG still needed now that models have long context windows?

Often, yes. Long context and CAG work well when the whole knowledge base fits in the window and changes rarely. RAG still wins when knowledge is large, changes often or needs per-user permissions. Research also shows models can miss facts placed in the middle of long inputs. Many teams combine a preloaded base context with retrieval.

What is CAG in AI?

CAG means cache-augmented generation. It was proposed in the paper "Don't Do RAG" (arXiv 2412.15605). All documents are loaded into the model's context once, and the model's key-value cache is saved. Each question then reuses that cache, so there is no retrieval step. Its authors say it becomes impractical for significantly larger datasets.

Which vector database should I learn for RAG interviews?

Learn the concepts first: embeddings, cosine similarity, exact versus approximate search, and HNSW. Then get hands-on with one tool. pgvector is a practical choice because it adds vector search to PostgreSQL, which many companies already run. FAISS is worth knowing as a library. Interviewers care more about trade-offs than brand names.

What should experienced candidates prepare for RAG interviews?

Prepare to design a system end to end and defend each choice with numbers. Expect questions on chunking strategy, hybrid search, rerankers, evaluation sets, index memory, permission filtering and prompt injection. Have one real project story ready: what failed, how you measured it, and what you changed. Knowing RAG-Sequence versus RAG-Token also helps.

Is there a PDF of these RAG interview questions?

There is no separate PDF. This page works as one: use your browser's Print option and choose "Save as PDF". The code blocks stay copyable on the page itself. We suggest running each program rather than only reading it, because interviewers often ask you to change one line and predict the output.

Keep going

For the full beginner build, with a small pipeline and a local model, read Crio's RAG explained, with code. To see where retrieval fits in a bigger AI project, read how to build your own Jarvis by learning LLMs. Then read the future of AI for software developers.

If you want to build RAG systems, agents and LLM apps on real projects with mentor reviews, look at Crio's AI Engineering program.

You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.