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.
#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.
#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 itselfStrategies, in increasing sophistication:
| Strategy | How | When |
|---|---|---|
| Fixed size + overlap | 512 tokens, 15% overlap | The baseline. Works surprisingly well |
| Structural | Split on headings, paragraphs, code blocks | Almost always better — respects the author's own boundaries |
| Semantic | Split where consecutive-sentence embedding similarity drops | Better on unstructured prose; slower to build |
| Recursive | Try paragraph, then sentence, then token boundaries until under the size cap | Good general-purpose default |
#Hybrid search
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 paraphrasesCombining 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 accurateThe 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
| Failure | Symptom | Fix |
|---|---|---|
| Chunk boundary splits the answer | Answers are half-right | Overlap, structural chunking, small-to-big |
| Query and corpus vocabulary differ | Nothing relevant retrieved | Hybrid search, query expansion, fine-tuned embeddings |
| Retrieval returns near-duplicates | 10 chunks say the same thing | Dedupe; MMR (maximal marginal relevance — pick each next result for being relevant and unlike those already picked) |
| Model ignores the context | Answer contradicts a retrieved passage | Reorder, reduce count, prompt for citations |
| Stale index | Confidently outdated answers | Freshness SLA, show document dates |
| No relevant documents exist | Confident fabrication | Score 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
Which chunking strategies work best?Show answer
How do you decouple what you embed from what you return?Show answer
Why reciprocal rank fusion for hybrid search?Show answer
Why is a reranker usually the best return on effort?Show answer
Name three query transformations.Show answer
How should retrieved context be assembled?Show answer
How do you build a retrieval evaluation set quickly?Show answer
#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.