🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

RAG System Design

AI System DesignRetrieval-Augmented GenerationđŸŸĸ Free Lesson

RAG System Design

Module 13 - Building Production Retrieval-Augmented Generation Systems

What You'll Learn

  • 1Size a vector index from corpus size, chunk length, and overlap before writing any code
  • 2Build an end-to-end latency budget for embedding, retrieval, re-ranking, and generation
  • 3Fuse dense and sparse results with reciprocal rank fusion and justify the constant k
  • 4Score a RAG system with recall@k, context precision, and faithfulness

Why This Matters

RAG grounds LLM responses in factual, up-to-date knowledge without retraining. It's the dominant pattern for enterprise AI - enabling chatbots over documents, code assistants over internal repos, and search engines over proprietary data. Designing RAG well requires balancing retrieval quality, generation accuracy, latency, and cost.

The arithmetic is unforgiving. A 100,000 document corpus averaging 2,000 words is about 266 million tokens, which at a 512 token chunk with 50 tokens of overlap becomes roughly 576,000 chunks and 2.2 GiB of float32 vectors before index overhead. Every query then pays embedding, search, re-ranking, and generation in sequence, so a slow retriever is 40 ms you cannot hide behind an 1,800 ms language model call, but a slow re-ranker on 50 candidates is.


System Architecture Overview

RAG System ArchitectureUser QueryText / Voice / ImageQuery ProcessingRewrite, Expand, HyDEQuery Embeddingdense-001 / BGE / CohereHybrid RetrievalDense + Sparse + BM25Chunking Strategies+- Fixed-size: 512 tokens, 50 overlap+- Semantic: paragraph/section breaks+- Recursive: markdown headers+- Agentic: LLM-based splitting+- Parent-child: small chunks + context+- Hypothetical: generate answers firstBest: Recursive + overlap for most casesTrade-off: granularity vs. contextVector Database+- Pinecone: managed, serverless+- Weaviate: hybrid, GraphQL+- Milvus/Zilliz: distributed, scalable+- pgvector: PostgreSQL extension+- Qdrant: Rust, high performance+- Chroma: lightweight, dev-friendlyIndex types: HNSW, IVF, PQFilters: metadata, time, accessRe-Ranking Layer+- Cross-encoder rerankers| Cohere Rerank, bge-reranker+- LLM-based reranking| GPT-4 judge, LLaMA reranker+- Reciprocal Rank Fusion| Combine dense + sparse scores+- Score normalizationReduces retrieved docs to top-k (5-10)Context-Aware Generation+------------------------------------------+| System Prompt + Retrieved Chunks + Query || -> LLM -> Answer with Citations |+------------------------------------------+RAG Evaluation- Retrieval: Recall@K, MRR, NDCG- Generation: Faithfulness, Relevance- End-to-end: RAGAS, TruLens, Phoenix- Grounding: citation accuracy, hallucination rateContinuous Improvement PipelineUser feedback -> Query log analysis -> Chunk quality scoring -> Re-indexing -> A/B testing -> Model updatesData pipeline: ETL -> Chunk -> Embed -> Index -> Serve -> Monitor -> Retrain

RAG Pipeline Implementation

A RAG pipeline processes queries through multiple stages: query expansion (generating alternative queries for better recall), hybrid retrieval across the vector store, deduplication via Reciprocal Rank Fusion (RRF), re-ranking with a cross-encoder model, and context-aware generation. RRF merges the ranked lists from the dense retriever and the BM25 retriever without ever having to compare their raw scores, which live on incompatible scales:

Here is the rank of document under retriever and is a smoothing constant, conventionally 60. With a document at rank 1 scores 0.0164 and one at rank 10 scores 0.0143, so being first is worth only about 15 percent more than being tenth; raising flattens the list further, and lowering it to 1 makes rank dominate. Retrieved documents are then formatted with source citations and fed to the LLM with a system prompt that instructs it to answer based on the provided context.


Chunking Implementation

Semantic chunking splits documents by markdown headers first, then further splits long sections by paragraphs while respecting a maximum chunk size (e.g., 512 tokens). Overlapping chunks (e.g., 50 tokens) preserve context across chunk boundaries by prepending words from the previous chunk. Each chunk is assigned a unique ID and carries metadata including chunk index.


Re-ranking

Re-ranking uses a cross-encoder model (e.g., BAAI/bge-reranker-v2-m3) that takes query-document pairs and produces relevance scores. Unlike bi-encoders used for initial retrieval, cross-encoders attend to both query and document simultaneously, providing more accurate relevance judgments at higher computational cost. Results are re-sorted by cross-encoder score and the top-k are selected. A cross-encoder on 50 candidate pairs at 512 tokens costs roughly 60 ms on one GPU, so keep the candidate list short: recall gains past 50 candidates are usually smaller than the latency you pay for them.


Index Sizing

Chunk count is a pure arithmetic question. With corpus token count , chunk size , and overlap :

Storage follows from the embedding dimension and bytes per element :

An HNSW index on top of that adds about 128 bytes per chunk for level-0 links at M = 16 (32 links of 4 bytes), or 74 MB. The graph is therefore 3 percent of the vector payload, which is why quantizing vectors to INT8 or PQ matters far more than tuning the graph. If the corpus grows 10x to 5.8 million chunks, raw vectors alone hit 22 GiB and you have moved from one node to a sharded deployment.


End-to-End Latency Budget

A RAG request pays four stages in series, so the budget adds:

StageImplementationp50p99Share of budget
Embed querySingle-vector encoding25 ms60 ms1.3%
Hybrid searchHNSW plus BM25 over 576K chunks40 ms120 ms2.1%
Re-rankCross-encoder on 50 pairs60 ms140 ms3.1%
Generate3,000 token prefill and 400 token decode1,800 ms3,400 ms93.5%
TotalFull request1,925 ms3,720 ms100%

The generator is 93 percent of the budget, so shaving 20 ms off retrieval changes nothing a user notices, while cutting the prompt from 3,000 to 1,500 tokens saves about 700 ms of prefill. Optimize the prompt before you optimize the index.


Retrieval Quality Metrics

Retrieval is graded against the set of documents that actually contain the answer:

Moving k from 5 to 20 typically lifts recall from about 0.72 to 0.91 on a well-tuned hybrid index, but it also quadruples the re-rank bill and pushes three times as many distractors into the prompt, where the model may quote them. The usual compromise is to retrieve k = 20, re-rank, and pass the top 5 chunks to the generator with their citation ids.


Common Mistakes

Fixing chunk size by convention

Fix: Derive chunk count from corpus tokens: 266M tokens at 512 with 50 overlap is 575,758 chunks and 2.2 GiB of vectors, so size the fleet from that.

Retrieving the top 50 straight into the prompt

Fix: Retrieve 20, re-rank with a cross-encoder, and pass only the top 5 chunks, or distractors start being quoted.

Evaluating with end-to-end answer quality only

Fix: Score retrieval separately with recall@k and context precision, otherwise a good generator hides a broken retriever.

Best Practices

  • Track recall@k and faithfulness on a fixed labeled set of 100 to 200 questions so every chunking change is comparable
  • Version chunks by document id so an edited document deletes its old chunks instead of leaving stale siblings
  • Re-embed only the changed partition on content updates, then schedule a nightly full re-index to catch drift

Key Takeaways

  • Chunk count is corpus tokens divided by (chunk minus overlap): 266M tokens gives 575,758 chunks at 512/50
  • Vector storage is chunks x dims x bytes, which is 2.20 GiB for 1,024 dim float32 and grows linearly with the corpus
  • End-to-end latency is embed + search + rerank + generate, and generation is 93 percent of a 1,925 ms budget
  • RRF sums 1 / (k + rank) across retrievers with k = 60, so it never compares raw dense and BM25 scores

Frequently Asked Questions

How many chunks should I retrieve before re-ranking?

Retrieve 20 to 50, re-rank, then pass 5 to the generator. Recall@20 on a tuned hybrid index is usually around 0.91 against 0.72 at k = 5, so the wide net is where the missing facts come from. The cross-encoder then throws the noise away: 20 pairs at 512 tokens costs about 25 ms, while 50 pairs costs 60 ms and rarely buys more than one extra point of recall.

Why does hybrid search beat pure vector search?

Dense embeddings collapse exact identifiers: an error code like ECONNRESET 14, a part number, and a misspelled product name all land near generic neighbors. BM25 matches those tokens exactly, and dense retrieval still handles paraphrase. Because the two score scales are incompatible, you fuse ranks rather than scores with reciprocal rank fusion, and the combination typically gains 5 to 12 points of recall@10 over either retriever alone.

How often should I re-embed the corpus?

Re-embed on content change, not on a calendar: hash each document, re-chunk and re-embed only the ones whose hash moved, and upsert by document id. Run a full re-index once a month or after any embedding model upgrade, because mixing vectors from two models in one index corrupts every neighbour relationship. A model upgrade always means a full re-embed; there is no partial migration.

Interview Questions

Q1: How do you evaluate RAG system quality?

Score the two halves separately. Retrieval gets recall@k, MRR, and context precision against a labeled question-to-source set; generation gets faithfulness and answer relevance through RAGAS or an LLM judge. Then add citation accuracy and an A/B test on task completion, since a faithful answer to the wrong question still fails the user.

Q2: How do you handle multi-hop reasoning in RAG?

Decompose the question into sub-queries, retrieve and answer each hop, and feed every answer back as context for the next retrieval. Two or three hops at 1,900 ms each is still under 6 seconds, which beats one flat retrieval that misses the second entity entirely. For entity-relationship questions, a graph RAG over the same chunks usually wins.

Q3: How do you handle document updates in a RAG system?

Key chunks by document id plus chunk index, re-chunk the changed document, re-embed only its chunks, upsert, and delete the ids that no longer exist. Never key on chunk id alone, because a shorter replacement leaves orphans. Run a nightly full re-index as a consistency check and compare recall@10 against the incremental build.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement