SysDesignAtlas

Retrieval Architecture (RAG)

Chunking, hybrid search, reranking, and evaluation — the pipeline between a question and a grounded answer, and why retrieval quality caps everything downstream.

HLDHard11 min readairagretrievalreranking
Confidence

#The pipeline

Retrieval-augmented generation is a search problem with a language model at the end. The model gets most of the attention; retrieval quality sets the ceiling on the whole system. If the right passage isn't in the context, no amount of prompting recovers it.

Query Transform rewrite · expand · decompose Retrieve dense + lexical, top 100 Rerank cross-encoder, top 10 Assemble dedupe · order · budget Generate with citations
Six stages. Most RAG systems implement two of them and wonder why quality is poor.

#Chunking

The most consequential and least glamorous decision. Chunks are the unit of retrieval, so chunk boundaries determine what can ever be retrieved together.

   TOO SMALL (100 tokens)          TOO LARGE (2,000 tokens)

   precise embeddings              embedding averages many topics
   but context is missing          → matches everything weakly
   → "It requires a restart."      → retrieves a whole chapter
     What does? Lost.                to answer one question
   → many chunks per answer        → wastes context budget
                                   → "lost in the middle" within
                                      the chunk itself

Strategies, in increasing sophistication:

StrategyHowWhen
Fixed size + overlap512 tokens, 15% overlapThe baseline. Works surprisingly well
StructuralSplit on headings, paragraphs, code blocksAlmost always better — respects the author's own boundaries
SemanticSplit where consecutive-sentence embedding similarity dropsBetter on unstructured prose; slower to build
RecursiveTry paragraph, then sentence, then token boundaries until under the size capGood general-purpose default

Two kinds of search, with complementary blind spots. Dense retrieval is the embedding-based kind — it matches meaning, and it's bad at exact identifiers, rare words, and negation. Lexical retrieval is old-fashioned keyword matching, usually scored with BM25 (the standard formula that ranks documents by how often they contain the query's words, weighting rare words more). It nails exactly those cases and fails at synonyms and paraphrase.

Hybrid means running both and combining the results, which is why it's the default in serious systems.

   Query: "error E-4471 when saving"

   DENSE ONLY
     finds passages about "save failures" and "write errors"
     does NOT reliably find the one mentioning E-4471
     → the error code is just an unusual token to it

   BM25 ONLY
     finds every passage containing "E-4471" exactly
     misses "persistence failure" phrased differently

   HYBRID
     both, fused → the exact match AND the paraphrases

Combining them is harder than it sounds, because the two systems produce scores on incomparable scales. Reciprocal Rank Fusion sidesteps that entirely by throwing the scores away and using only positions — something ranked second by both lists beats something ranked first by one and fiftieth by the other:

Hybrid retrieval is close to free to add and reliably improves recall. It should be the default, not an optimisation.

#Reranking

First-stage retrieval must be fast over millions of documents, so it uses a bi-encoder — query and document embedded independently, compared by distance. That independence is what allows precomputation: a document's embedding doesn't depend on the query, so you can embed every document once, ahead of time, and at query time embed only the query. It's also the quality limitation: the model never sees the query and document together, so it can't notice, say, that the document answers a slightly different question.

   BI-ENCODER (retrieval)           CROSS-ENCODER (reranking)

   embed(query)   ─┐                model([query, document])
   embed(doc)     ─┴─► cosine         → attends across BOTH
                                      → a single relevance score
   docs precomputed                 nothing precomputable
   millions in milliseconds         ~10-50 ms per pair
   ✗ no query-document interaction  ✓ full interaction, much
                                       more accurate

The two-stage pattern: retrieve 100 candidates with the fast bi-encoder, rerank them with the slow cross-encoder, keep the top 10. Stage one supplies recall — its job is just to get the right document somewhere into the 100. Stage two supplies precision — its job is to move that document to the top.

Rerankers are usually the highest return per unit of effort in a RAG system. They routinely move retrieval precision by 10–30 points and require no index changes, no re-embedding, and no retraining — you add a model call on 100 documents.

The cost: 100 documents at ~20 ms each is 2 seconds serially, so batch them, and consider a smaller reranker or fewer candidates if latency is tight. ColBERT sits between the two. It uses late interaction: it precomputes an embedding for every token of each document (not one per document), and at query time compares each query token against those token embeddings. That's more accurate than a bi-encoder and much faster than a cross-encoder, at the cost of a considerably larger index — one vector per token instead of one per chunk.

#Query transformation

The user's question is often not the best search query.

  • Rewriting. "what about the second one" is meaningless standalone. Rewrite against conversation history into a self-contained query. Mandatory for multi-turn retrieval and frequently forgotten.
  • Decomposition. "Compare our Q3 and Q4 margins" needs two retrievals, not one. Split, retrieve separately, combine.
  • HyDE. Generate a hypothetical answer to the question, embed that, and search with it. Answers look like documents; questions don't. Often a solid gain, at the cost of one extra model call.
  • Expansion. Add synonyms and related terms, mainly to help the lexical side.
  • Agentic retrieval. Give the model search as a tool and let it run several queries — read the results, refine, search again. That's the pattern behind the "deep research" products of 2025, and it handles multi-hop questions that one retrieval can't. It costs several times the latency and tokens, so route only hard questions to it and keep single-shot retrieval for the common ones.

#Assembling the context

Retrieved chunks are not a prompt. Assembly matters more than it appears:

  • Deduplicate. Overlapping chunks and near-duplicate documents waste budget and bias the model by repetition.
  • Order deliberately. Given lost-in-the-middle, put the strongest results first and last, weakest in the middle.
  • Budget explicitly. System prompt + retrieved chunks + history + question + room for the answer.
  • Attach metadata. Source, date, and section heading, so the model can cite and can reason about recency.
  • Say what to do when there's nothing. "If the context doesn't contain the answer, say so" measurably reduces fabrication — and it's one line.

#Evaluating retrieval separately

The most common diagnostic failure in RAG: measuring only end-to-end answer quality. When the answer is wrong you can't tell whether retrieval missed the passage or the model ignored it, and those need completely different fixes.

   MEASURE EACH STAGE

   Retrieval    recall@k    is the right chunk in the top k?
                MRR / nDCG  how high is it ranked?
                            → needs query→relevant-chunk labels

   Reranking    same metrics, before vs after
                            → is the reranker earning its latency?

   Generation   faithfulness  is the answer supported by the
                              retrieved context?
                answer quality is it actually a good answer?

   → If recall@10 is 0.6, your ceiling is 0.6 regardless of
     the model. Fix retrieval first. Every hour spent on
     prompt engineering above a broken retriever is wasted.

#Failure modes worth knowing

FailureSymptomFix
Chunk boundary splits the answerAnswers are half-rightOverlap, structural chunking, small-to-big
Query and corpus vocabulary differNothing relevant retrievedHybrid search, query expansion, fine-tuned embeddings
Retrieval returns near-duplicates10 chunks say the same thingDedupe; MMR (maximal marginal relevance — pick each next result for being relevant and unlike those already picked)
Model ignores the contextAnswer contradicts a retrieved passageReorder, reduce count, prompt for citations
Stale indexConfidently outdated answersFreshness SLA, show document dates
No relevant documents existConfident fabricationScore threshold plus an explicit "I don't know" path

That last row is the one that damages trust. If the top result's score is below a threshold, don't generate an answer. Say you couldn't find it. The threshold needs calibrating per model (scores aren't comparable across models), and it's worth the effort.

#Check yourself

What sets the ceiling on a RAG system?Show answer
Retrieval quality: if the right passage isn't in the context, no prompt recovers it. If recall@10 is 0.6, the system's ceiling is 0.6.
Which chunking strategies work best?Show answer
Structural splitting on headings, paragraphs and code blocks usually beats fixed size; recursive splitting is a good default; keep tables and code whole.
How do you decouple what you embed from what you return?Show answer
Small-to-big (embed 200-token chunks, return the parent section), contextual retrieval (prefix each chunk with a document summary) and hypothetical questions (embed the questions a chunk answers).
Why reciprocal rank fusion for hybrid search?Show answer
BM25 and cosine scores are on incomparable scales; RRF sums 1/(k + rank) per system, so ranks fuse with no calibration or drift.
Why is a reranker usually the best return on effort?Show answer
A cross-encoder reads query and passage together — far more accurate than a bi-encoder — and reranking ~100 candidates to 10 lifts precision 10–30 points with no index change.
Name three query transformations.Show answer
Rewrite multi-turn questions into standalone queries, decompose comparisons into separate retrievals, HyDE (search with a hypothetical answer), expansion, and agentic retrieval for multi-hop questions.
How should retrieved context be assembled?Show answer
Deduplicate, put the strongest passages first and last, budget explicitly with room for the answer, attach source and date metadata, and say what to do when the answer isn't there.
How do you build a retrieval evaluation set quickly?Show answer
Take ~200 real queries and label which chunks answer them, or bootstrap by generating a question per chunk and inverting the mapping; then measure recall@k and MRR separately from answer faithfulness.

#What to carry forward

  • Retrieval quality caps the whole system. Measure it separately from answer quality.
  • Decouple what you embed from what you return — small-to-big, contextual summaries, hypothetical questions.
  • Hybrid dense + BM25 with RRF should be the default; ranks fuse better than scores.
  • A reranker is the highest return per unit of effort in most RAG systems.
  • Rewrite multi-turn queries into standalone ones before retrieving.
  • Assembly matters: dedupe, order strongest first and last, budget for the answer.
  • Build a 200-query labelled set. It converts arguments into experiments.
00:00
/ 11m