Slides · GenAI system design

Designing a RAG QA system

Designing a RAG QA system

How to turn a blank page into a defensible design: numbers first, then boxes, then the details that rushed answers skip.

By the end you can:

  • turn requirements into a scale estimate and say which decision each number drives,
  • lay out the ingest and query paths, with hybrid retrieval, reranking, citations and an abstain path,
  • place permission filtering inside retrieval and explain what breaks otherwise,
  • plan evaluation that separates retrieval from generation, and name failure modes with a signal and a degraded mode.

Concept

The blank page problem

  • The brief: an assistant over a company’s internal documents, where each employee may only see what they are allowed to see.
  • A list of boxes (“vector database, reranker, LLM”) shows you have read about RAG.
  • A chain of reasons (“2 million chunks fit in memory on one node, so I do not shard yet”) shows you can build one.
  • Every number in this lesson is illustrative. Say “assume”, then show the multiplication.

Mental model: a reference librarian at a members-only library. Check which shelves this member may enter, search only those, bring back a few passages, cite the pages, and say “not found” instead of guessing.

Concept

Requirements first, with assumptions aloud

AspectAssumption for this design
FunctionAnswer from wiki pages, PDFs and tickets, and cite the passage
AccessNever answer from a document the user cannot open
FreshnessAn edit is searchable within 15 minutes
LatencyFirst token within 3 seconds at p95, streamed
Quality barA wrong answer is worse than none, so abstaining is allowed
Out of scopeActions in other systems; non-English documents

Writing “out of scope” is part of the answer. These requirements decide which numbers you need next.

Worked example

Scale step 1: how big is the index?

Assumptions (illustrative): 5,000 employees, 200,000 documents, about 10 chunks per document, a 1,024-dimension embedding stored as 4-byte floats.

QuantityCalculationResultDecision it drives
Chunks200,000×10200{,}000 \times 102,000,000Size of the index
Raw vectors2,000,000×1,024×42{,}000{,}000 \times 1{,}024 \times 4 bytesabout 8.2 GBFits in memory on one machine, so no sharding yet
With ANN overheadassume 1.5 to 2 times rawabout 12 to 16 GBOne node plus a replica for availability

The overhead factor is an assumption; measure it on your own index.

Worked example

Scale step 2: how much traffic?

QuantityCalculationResult
Active users5,000×30%5{,}000 \times 30\%1,500
Queries per day1,500×51{,}500 \times 57,500
Busy-period rate80% of 7,500 = 6,000 queries over 8 hours (28,800 s); 6,00028,800\dfrac{6{,}000}{28{,}800}about 0.21 per second
Peak5×0.215 \times 0.21about 1 per second

At about 1 query per second, throughput is not the hard part. A distributed vector database here would be a design flaw, not a strength.

Worked example

Scale step 3: tokens and cost per query

Assumptions: 500 tokens of instructions, 5 retrieved chunks of 500 tokens, a 100-token question, 300 output tokens. Hypothetical prices: $3 per million input tokens, $15 per million output tokens.

PartCalculationResult
Input tokens500+5×500+100500 + 5 \times 500 + 1003,100
Input cost3,100×$31,000,000\dfrac{3{,}100 \times \$3}{1{,}000{,}000}$0.0093
Output cost300×$151,000,000\dfrac{300 \times \$15}{1{,}000{,}000}$0.0045
One query$0.0093 + $0.0045$0.0138
One day7,500×$0.01387{,}500 \times \$0.0138$103.50
One month (22 days)165,000×$0.0138165{,}000 \times \$0.0138$2,277

The retrieved chunks are 2,500 of the 3,100 input tokens. The LLM call is the cost.

Compare

What the numbers tell you to do

LeverArithmeticEffectTrade-off
Fewer chunks in the prompt5 to 3 chunks: 2,100 input tokens; 2,100×$31,000,000+$0.0045=$0.0108\dfrac{2{,}100 \times \$3}{1{,}000{,}000} + \$0.0045 = \$0.0108About 22% cheaper per queryQuality may drop, so measure it
Re-embed everything once2,000,000×500=12{,}000{,}000 \times 500 = 1 billion tokens; at an assumed $0.10 per million$100 onceNone worth designing around
Daily re-embedding2%×200,000=4,0002\% \times 200{,}000 = 4{,}000 documents, 40,000 chunks, 20 million tokensAbout $2 per dayFreshness is engineering, not cost
50 million chunks50,000,000×1,024×4=204.8 GB50{,}000{,}000 \times 1{,}024 \times 4 = 204.8\ \text{GB} raw; 1.5 to 2 times overhead gives about 300 to 400 GBBeyond one node’s memoryShard, quantize, or use a disk-based index

State the numbers, then say what would change them.

Check yourself

Check: what does quantization buy?

A team has 40 million chunks of 1,024-dimension float32 vectors and a 64 GB (decimal) memory budget. The ANN index overhead was measured at 1.5 times raw size for float32. Does it fit? Would storing 1 byte per dimension fit, and what must you check?

Answer

Float32 raw: 40,000,000×1,024×4=163.84 GB40{,}000{,}000 \times 1{,}024 \times 4 = 163.84\ \text{GB}; with 1.5 times overhead, about 246 GB, so it does not fit. At 1 byte per dimension the raw vectors are 40.96 GB. If the overhead shrinks in proportion (1.5 times), the index is about 61.4 GB, which is 57.2 GiB, so it only just fits a 64 GB budget with almost no headroom. But graph links and metadata are per vector and do not shrink with quantization. If the overhead stays at the absolute 0.5×163.84=81.9 GB0.5 \times 163.84 = 81.9\ \text{GB}, the total is about 123 GB and it does not fit. So “fits” rests on an assumption: measure the real index, and measure recall on the golden set too, because compression loses precision. State GB or GiB when you quote a budget.

Diagram

Ingest path: offline and incremental

Diagram: Documents and their permissions enter together, are parsed and split into chunks, and each chunk keeps its allowed groups, source and...

Documents + ACL source

Load and parse

Chunk + metadata
groups, source, version

Embed

Vector + keyword index

Diagram summary: Documents and their permissions enter together, are parsed and split into chunks, and each chunk keeps its allowed groups, source and version as metadata. Chunks are embedded and written to one index that supports both vector and keyword search.

Permissions travel with the chunk from the start. That is what lets retrieval filter later.

Diagram

Query path: online

Diagram: The flow runs downward.

no

yes

User + question

Resolve user groups
from identity system

Hybrid retrieve,
filtered by groups

Rerank 50 to 5,
re-check vs source

Enough evidence?

Say: not found

Answer with ids,
ids checked in code

Diagram summary: The flow runs downward. The user’s groups are resolved first and used as a filter inside the hybrid search. Fifty candidates are reranked to five and the five are re-checked against the source system. An evidence gate then chooses between “not found” and a cited answer, whose cited ids are checked against the retrieved set in code.

Retrieved text is untrusted input: OWASP lists indirect injection through external content, and notes that retrieval and fine-tuning do not fully remove it. Treat chunks as data and restrict any tools.

Source1 LLM01:2025 Prompt Injection

Compare

Why hybrid and rerank, and what each costs

ChoiceWhyCost
Hybrid retrievalVector search matches meaning; keyword search matches exact tokens such as error codes and product names. Elastic describes hybrid search, when done well, as giving better results than either approach alone.A second index to keep in sync; scores need fusing
RerankingA cross-encoder reads the query and each candidate together, which Sentence Transformers documents as performing better than a bi-encoder but too slow to score a whole collectionAdded latency on every query
CitationsUsers can verify; you can measure supportPrompt complexity; a check that cited ids were retrieved
Abstain pathA wrong answer is worse than noneSome answerable questions are refused

Latency levers if over budget: a smaller reranker, fewer candidates, a smaller model for easy questions, and prompt caching of the static prefix. Anthropic’s docs describe caching a repeated prompt prefix to cut processing time and cost, with a model-dependent minimum length, so check the current rules.

Sources2 Elasticsearch hybrid search3 Retrieve & Re-Rank4 Prompt caching

Concept

The abstain gate

  • Decide before generating: if the best reranked score is below a threshold, answer “not found in your documents”.
  • This avoids paying for an LLM call that would guess.
  • Tune the threshold on a golden set that includes unanswerable questions. A threshold tuned only on answerable ones will never learn to refuse.
  • Stricter threshold: fewer wrong answers, more refusals. Say that trade-off aloud.
  • After generation, validate citations in code: any cited id that is not in the list of chunks you put in the prompt marks the answer as unreliable, so flag or drop it.

Concept

The rule: filter inside the retrieval query

  • Only chunks the user may read can ever reach the prompt.
  • Do not ask the model to hide something it was shown. A model that has read a secret can be argued into repeating it.
  • OWASP’s guidance on sensitive information disclosure points the same way: apply least privilege, so that access is granted only where it is “necessary for the specific user or process”.
  • Build it: each chunk stores allowed_groups copied from its document at ingest; the user’s groups, resolved from your identity system, go into the search as a metadata filter.

Mental model: the librarian checks the member’s card at the shelf door, not after reading the books aloud.

Source5 LLM02:2025 Sensitive Information Disclosure

Diagram

Where the filter sits decides safety and recall

Diagram: Three placements are compared side by side.

Inside the query

Filter by
user's groups

Retrieve top k
from allowed

Full k, none
restricted

After search

Retrieve top k
from all

Drop forbidden
chunks

Fewer than k,
maybe none

After generation

Retrieve from
everything

Model reads
restricted text

Answer may
paraphrase it

Diagram summary: Three placements are compared side by side. Filtering after generation is unsafe: the model has already read restricted text and may paraphrase it. Filtering after the search but before the prompt is safe but lossy, because slots are wasted on forbidden chunks. Filtering inside the query, the recommended option, means only allowed chunks are candidates, so the result is both safe and complete.

Worked example

“Filtered search” is not automatically exact

The pgvector README gives a concrete case. An approximate HNSW index first collects a candidate list (default size 40), and the filter is applied to those candidates.

StepValue
Candidate list size40
Share of rows matching the filter10%
Expected matching rows returned40×0.10=440 \times 0.10 = 4
Same logic at 1% matching (extrapolation, not from the README)40×0.01=0.440 \times 0.01 = 0.4

The README’s remedies include indexing the filter column, exact search for very selective filters, partial indexes, and iterative index scans that keep scanning until enough rows match.

Why it matters here: a permission filter is often selective (a user can read a small share of the corpus). Whatever the database, test filtered recall and latency on your own index, for the smallest permission groups first, and never trade the filter’s correctness for speed.

Source6 pgvector: open-source vector similarity search for Postgres

Process

Permissions change after ingestion

  1. Sync from the source of truth. Event-driven permission updates with a stated lag target.
  2. Re-check the final five. Before the prompt is built, confirm each chunk against the source system. Five checks per query is cheap insurance against sync lag.
  3. Fail closed. On a mismatch, drop the chunk.
  4. Scope caches by identity. A semantic cache that hands user B’s answer to user A is an access-control bug. Key the cache on the permission set, or cache only stages that contain no restricted text.
  5. Alarm on lag. Permission-sync lag is invisible to users until it hurts.

Check yourself

Check: where do the groups come from?

An engineer proposes that the web client sends a groups list in each request, which the search service uses as its metadata filter. What is wrong, and what should the service do?

Answer

The client controls the request body, so a user could send any groups and read anything. The service should resolve the user’s identity from the authenticated session and look up the groups in the identity system itself. The filter is then built from data the user cannot edit.

Compare

Evaluate the stages separately

The RAGAs paper frames RAG evaluation along separate dimensions: whether retrieval finds focused, relevant context, whether the model uses that context faithfully, and the quality of the generated answer.

StageQuestionMetric
RetrievalIs the gold passage found, and how high?recall@k, MRR, per permission group
GenerationIs the answer supported by the context?Faithfulness, answer correctness, citation accuracy
SecurityDoes user A ever see user B’s document?Fixed probes; expected result is zero leaked passages
OnlineAre users served?Thumbs, abstention rate, rephrasing, weekly trace sample

When quality drops, stage metrics tell you whether to fix ingestion, retrieval or generation. Failures join the golden set.

Source7 RAGAs: Automated Evaluation of Retrieval Augmented Generation

Math

Three metrics, computed

recall@k=queries with the gold passage in the top kall queries\text{recall@}k = \frac{\text{queries with the gold passage in the top } k}{\text{all queries}}MRR=1∣Q∣∑i=1∣Q∣1ranki\mathrm{MRR} = \frac{1}{|Q|} \sum_{i=1}^{|Q|} \frac{1}{\mathrm{rank}_i}faithfulness=claims supported by the contextall claims in the answer\text{faithfulness} = \frac{\text{claims supported by the context}}{\text{all claims in the answer}}
SymbolMeaning
kkHow many results are kept, for example 3
∣Q∣\lvert Q \rvertNumber of queries in the golden set
ranki\mathrm{rank}_iPosition of the first gold passage for query ii; the reciprocal rank is 0 if none is returned

Worked (illustrative): four queries have gold passages at ranks 1, 3, not found, and 2.

  • recall@3=34=0.75\text{recall@}3 = \dfrac{3}{4} = 0.75.
  • MRR=1+13+0+124=1.8334≈0.458\mathrm{MRR} = \dfrac{1 + \frac{1}{3} + 0 + \frac{1}{2}}{4} = \dfrac{1.833}{4} \approx 0.458.
  • An answer with 5 claims, 4 of them supported by the retrieved context, has faithfulness 45=0.8\dfrac{4}{5} = 0.8.

Sources8 Mean reciprocal rank9 Faithfulness

Check yourself

Check: which stage broke?

The team switches to a new embedding model for queries but forgets to re-embed the stored chunks. Recall@5 on the golden set falls from 0.88 to 0.41, while faithfulness on whatever context is retrieved stays near 0.9. Which stage is at fault, what is the safe response, and which control would have blocked the release?

Answer

Retrieval: query vectors and chunk vectors now come from different models, so similarity is meaningless. Revert the query embedder; re-embed the chunks and swap the index alias together with the new embedder. A release gate on golden-set recall would have blocked the change. Faithfulness stayed flat because it only measures the context that was retrieved, not whether the right context was found.

Compare

Failure modes: signal and degraded mode

FailureDetection signalDegraded mode
Index or retriever downHealth check, timeoutsKeyword-only search, or “search unavailable”
Reranker slow or downStage p95 latencySkip rerank, serve hybrid results
LLM outage or rate limitError rate, 429 responsesBackoff, fallback model, or cited snippets only
Stale indexIngestion-lag alarm against the 15-minute targetFreshness warning; refuse for sensitive sources
Permission sync lagLag metric, source re-check mismatchesFail closed: drop the chunk
Weak retrievalLow rerank score, high abstentionClarifying question or “not found”
Injection in a documentOutput checks, red-team probesChunks are data; restrict tools; filter outputs
Embedder changed, no re-indexRecall drop on golden setBlock release; roll back index alias

Stale index and permission lag are the two failures users cannot see, so they need alarms.

Source1 LLM01:2025 Prompt Injection

Worked example

Latency budget and rollout

Stage (illustrative)Budget
Auth and query embedding100 ms
Retrieval100 ms
Rerank300 ms
LLM time to first token1,200 ms
Sum1,700 ms
Margin for network and queueing1,300 ms
p95 target3,000 ms

Check: 100+100+300+1,200=1,700100 + 100 + 300 + 1{,}200 = 1{,}700, and 3,000−1,700=1,3003{,}000 - 1{,}700 = 1{,}300. Stream the answer so users perceive the first token.

Rollout: offline evaluation, then shadow traffic, then a small canary, with every component versioned for rollback. A change to the chunker, embedder, prompt or model passes the same gate.

Compare

Trade-offs to say aloud

DecisionOne sideOther side
Chunk sizeSmall: precise, loses contextLarge: more context, diluted match, more tokens
FreshnessNear-real-time sync: more machineryNightly batch: simpler; ask what users need
RetrievalHybrid: better exact-term recallVector only: one fewer index
Abstain thresholdStrict: fewer wrong answersLoose: fewer refusals
Rerank depthMore candidates: better recallFewer: lower latency

Interview note (common industry pattern, no company-specific claim): requirements before components, numbers that drive choices, permission filtering inside retrieval and an abstain path are the details rushed answers often skip.

Summary

Recap

  • Nine links: requirements, scale, components, data flow, failures, evaluation, cost and latency, security, rollout.
  • Estimate only numbers that change a decision, and label them illustrative.
  • Filter permissions inside the retrieval query, re-check the final chunks, and scope caches by identity.
  • Abstain below a tuned evidence threshold, and verify cited ids.
  • Evaluate retrieval and generation separately, with unanswerable and cross-permission cases.
  • Every failure gets a detection signal and a degraded mode.

References

References & Sources (1 of 2)

  1. LLM01:2025 Prompt Injection (opens in a new tab)

    OWASP GenAI Security Project2025Documentation

    Used for Indirect prompt injection arrives through external content such as retrieved documents, and retrieval or fine-tuning do not fully mitigate it.

  2. Retrieve & Re-Rank (opens in a new tab)

    Sentence Transformers2026Documentation

    Used for Retrieve with a fast bi-encoder, then rerank a shortlist with a more accurate but slower cross-encoder.

  3. Prompt caching (opens in a new tab)

    Anthropic2026Documentation

    Used for Prompt caching of a repeated prefix reduces processing time and cost; minimum length depends on the model.

  4. LLM02:2025 Sensitive Information Disclosure (opens in a new tab)

    OWASP GenAI Security Project2025Documentation

    Used for Limiting access to sensitive data by least privilege, for the specific user or process.

References

References & Sources (2 of 2)

  1. pgvector: open-source vector similarity search for Postgres (opens in a new tab)

    pgvector2026Repository

    Used for With approximate indexes, filtering is applied after the index is scanned, so filtered queries can return fewer rows than expected.

  2. RAGAs: Automated Evaluation of Retrieval Augmented Generation (opens in a new tab)

    Shahul Es, Jithin James, Luis Espinosa-Anke, Steven Schockaert2024EACL 2024 (System Demonstrations)Paper

    Used for RAG evaluation has separate dimensions: retrieval, faithfulness to context, and generation quality.

  3. Mean reciprocal rank (opens in a new tab)

    Wikipedia2026Article

    Used for Definition of mean reciprocal rank, with reciprocal rank 0 when no relevant result is returned.

  4. Faithfulness (opens in a new tab)

    Ragas2026Documentation

    Used for Faithfulness is the share of an answer's claims supported by the retrieved context.