Slides · GenAI system design
Designing a RAG QA system
1 / 27
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.
Process
The chain of nine links
- Requirements: who uses it, what counts as wrong, what is out of scope.
- Scale estimate: a few numbers, each tied to a decision.
- Components: two paths, ingest and query.
- Data flow: what moves between boxes, including the permission check.
- Failure modes: what breaks, how you notice, what happens then.
- Evaluation: a golden set, stage metrics, online signals.
- Cost and latency: a budget per stage.
- Security: controls in code, not in the prompt.
- Rollout: shadow, canary, rollback.
Ask in this order. The rest of the deck walks the links that carry the most weight for RAG.
Concept
Requirements first, with assumptions aloud
| Aspect | Assumption for this design |
|---|---|
| Function | Answer from wiki pages, PDFs and tickets, and cite the passage |
| Access | Never answer from a document the user cannot open |
| Freshness | An edit is searchable within 15 minutes |
| Latency | First token within 3 seconds at p95, streamed |
| Quality bar | A wrong answer is worse than none, so abstaining is allowed |
| Out of scope | Actions 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.
| Quantity | Calculation | Result | Decision it drives |
|---|---|---|---|
| Chunks | 200,000×10 | 2,000,000 | Size of the index |
| Raw vectors | 2,000,000×1,024×4 bytes | about 8.2 GB | Fits in memory on one machine, so no sharding yet |
| With ANN overhead | assume 1.5 to 2 times raw | about 12 to 16 GB | One 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?
| Quantity | Calculation | Result |
|---|---|---|
| Active users | 5,000×30% | 1,500 |
| Queries per day | 1,500×5 | 7,500 |
| Busy-period rate | 80% of 7,500 = 6,000 queries over 8 hours (28,800 s); 28,8006,000 | about 0.21 per second |
| Peak | 5×0.21 | about 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.
| Part | Calculation | Result |
|---|---|---|
| Input tokens | 500+5×500+100 | 3,100 |
| Input cost | 1,000,0003,100×$3 | $0.0093 |
| Output cost | 1,000,000300×$15 | $0.0045 |
| One query | $0.0093 + $0.0045 | $0.0138 |
| One day | 7,500×$0.0138 | $103.50 |
| One month (22 days) | 165,000×$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
| Lever | Arithmetic | Effect | Trade-off |
|---|---|---|---|
| Fewer chunks in the prompt | 5 to 3 chunks: 2,100 input tokens; 1,000,0002,100×$3+$0.0045=$0.0108 | About 22% cheaper per query | Quality may drop, so measure it |
| Re-embed everything once | 2,000,000×500=1 billion tokens; at an assumed $0.10 per million | $100 once | None worth designing around |
| Daily re-embedding | 2%×200,000=4,000 documents, 40,000 chunks, 20 million tokens | About $2 per day | Freshness is engineering, not cost |
| 50 million chunks | 50,000,000×1,024×4=204.8 GB raw; 1.5 to 2 times overhead gives about 300 to 400 GB | Beyond one node’s memory | Shard, 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 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 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
Permissions travel with the chunk from the start. That is what lets retrieval filter later.
Diagram
Query path: online
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.
Compare
Why hybrid and rerank, and what each costs
| Choice | Why | Cost |
|---|---|---|
| Hybrid retrieval | Vector 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 |
| Reranking | A 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 collection | Added latency on every query |
| Citations | Users can verify; you can measure support | Prompt complexity; a check that cited ids were retrieved |
| Abstain path | A wrong answer is worse than none | Some 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.
Sources[2] Elasticsearch hybrid search[3] Retrieve & Re-Rank[4] 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_groupscopied 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.
Diagram
Where the filter sits decides safety and recall
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.
| Step | Value |
|---|---|
| Candidate list size | 40 |
| Share of rows matching the filter | 10% |
| Expected matching rows returned | 40×0.10=4 |
| Same logic at 1% matching (extrapolation, not from the README) | 40×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.
Source[6] pgvector: open-source vector similarity search for Postgres
Process
Permissions change after ingestion
- Sync from the source of truth. Event-driven permission updates with a stated lag target.
- 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.
- Fail closed. On a mismatch, drop the chunk.
- 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.
- 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.
| Stage | Question | Metric |
|---|---|---|
| Retrieval | Is the gold passage found, and how high? | recall@k, MRR, per permission group |
| Generation | Is the answer supported by the context? | Faithfulness, answer correctness, citation accuracy |
| Security | Does user A ever see user B’s document? | Fixed probes; expected result is zero leaked passages |
| Online | Are 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.
Source[7] RAGAs: Automated Evaluation of Retrieval Augmented Generation
Math
Three metrics, computed
recall@k=all queriesqueries with the gold passage in the top kMRR=∣Q∣1i=1∑∣Q∣ranki1faithfulness=all claims in the answerclaims supported by the context| Symbol | Meaning |
|---|---|
| k | How many results are kept, for example 3 |
| ∣Q∣ | Number of queries in the golden set |
| ranki | Position of the first gold passage for query i; 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=43=0.75.
- MRR=41+31+0+21=41.833≈0.458.
- An answer with 5 claims, 4 of them supported by the retrieved context, has faithfulness 54=0.8.
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
| Failure | Detection signal | Degraded mode |
|---|---|---|
| Index or retriever down | Health check, timeouts | Keyword-only search, or “search unavailable” |
| Reranker slow or down | Stage p95 latency | Skip rerank, serve hybrid results |
| LLM outage or rate limit | Error rate, 429 responses | Backoff, fallback model, or cited snippets only |
| Stale index | Ingestion-lag alarm against the 15-minute target | Freshness warning; refuse for sensitive sources |
| Permission sync lag | Lag metric, source re-check mismatches | Fail closed: drop the chunk |
| Weak retrieval | Low rerank score, high abstention | Clarifying question or “not found” |
| Injection in a document | Output checks, red-team probes | Chunks are data; restrict tools; filter outputs |
| Embedder changed, no re-index | Recall drop on golden set | Block release; roll back index alias |
Stale index and permission lag are the two failures users cannot see, so they need alarms.
Worked example
Latency budget and rollout
| Stage (illustrative) | Budget |
|---|---|
| Auth and query embedding | 100 ms |
| Retrieval | 100 ms |
| Rerank | 300 ms |
| LLM time to first token | 1,200 ms |
| Sum | 1,700 ms |
| Margin for network and queueing | 1,300 ms |
| p95 target | 3,000 ms |
Check: 100+100+300+1,200=1,700, and 3,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
| Decision | One side | Other side |
|---|---|---|
| Chunk size | Small: precise, loses context | Large: more context, diluted match, more tokens |
| Freshness | Near-real-time sync: more machinery | Nightly batch: simpler; ask what users need |
| Retrieval | Hybrid: better exact-term recall | Vector only: one fewer index |
| Abstain threshold | Strict: fewer wrong answers | Loose: fewer refusals |
| Rerank depth | More candidates: better recall | Fewer: 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)
LLM01:2025 Prompt Injection (opens in a new tab)
OWASP GenAI Security Project2025Documentation
https://genai.owasp.org/llmrisk/llm01-prompt-injection/
Used for Indirect prompt injection arrives through external content such as retrieved documents, and retrieval or fine-tuning do not fully mitigate it.
Elasticsearch hybrid search (opens in a new tab)
Valentin Crettaz2025Article
https://www.elastic.co/search-labs/blog/hybrid-search-elasticsearch
Used for Hybrid search combines lexical and semantic queries, and their scores must be fused.
Retrieve & Re-Rank (opens in a new tab)
Sentence Transformers2026Documentation
https://sbert.net/examples/applications/retrieve_rerank/README.html
Used for Retrieve with a fast bi-encoder, then rerank a shortlist with a more accurate but slower cross-encoder.
Prompt caching (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Used for Prompt caching of a repeated prefix reduces processing time and cost; minimum length depends on the model.
LLM02:2025 Sensitive Information Disclosure (opens in a new tab)
OWASP GenAI Security Project2025Documentation
https://genai.owasp.org/llmrisk/llm022025-sensitive-information-disclosure/
Used for Limiting access to sensitive data by least privilege, for the specific user or process.
References
References & Sources (2 of 2)
pgvector: open-source vector similarity search for Postgres (opens in a new tab)
pgvector2026Repository
https://github.com/pgvector/pgvector
Used for With approximate indexes, filtering is applied after the index is scanned, so filtered queries can return fewer rows than expected.
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
arXiv 2309.15217 (opens in a new tab)https://arxiv.org/abs/2309.15217
Used for RAG evaluation has separate dimensions: retrieval, faithfulness to context, and generation quality.
Mean reciprocal rank (opens in a new tab)
Wikipedia2026Article
https://en.wikipedia.org/wiki/Mean_reciprocal_rank
Used for Definition of mean reciprocal rank, with reciprocal rank 0 when no relevant result is returned.
Faithfulness (opens in a new tab)
Ragas2026Documentation
https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/faithfulness/
Used for Faithfulness is the share of an answer's claims supported by the retrieved context.
Keys: ← → move, Home End first and last, F full screen.