Production RAG: Chunking, Hybrid Search, Reranking, and Evaluation
Derar SattoufUpdated AI engineering

Retrieval-augmented generation (RAG) looks easy in a demo: split documents, embed them, find the nearest chunks, paste them into a prompt. Then real users ask real questions, and the answers are confidently wrong. The usual culprit is not the language model. It is the retrieval pipeline, which fed it the wrong context, or too little, or too much.
Most RAG failures are retrieval failures, so debug and measure retrieval separately from generation. That starts with parsing: broken PDFs, lost tables and stripped headings are garbage in, garbage out. Chunk by structure (headings, sections) with modest overlap, and attach metadata and a short contextual header to each chunk.
For search, use hybrid retrieval (BM25 keyword plus vector) fused with Reciprocal Rank Fusion, then a reranker (cross-encoder) over the top 30-100 candidates, and pass the best 5-10 to the model. Rewrite queries before searching: expand them, decompose them, and resolve conversation references.
On the answer side, require citations, allow "I don't know", and enforce permissions at retrieval time. And build a golden dataset, then track recall@k, MRR, answer faithfulness, and latency in CI so you can improve deliberately.
Architecture at a glance
Ingestion (offline)
sources -> parse -> clean -> chunk -> enrich metadata -> embed -> index (vector + BM25)
Query time (online)
user question
-> query rewrite / decomposition
-> hybrid retrieval (vector + keyword, with ACL filters)
-> fuse rankings (RRF)
-> rerank top N with cross-encoder
-> assemble context (dedupe, order, budget)
-> LLM generation with citations
-> verification / guardrails -> answerTreat each stage as independently testable. When quality drops, you want to know which stage did it.
Parsing: the unglamorous foundation
Common failure sources: PDFs (multi-column layouts read in the wrong order, headers and footers repeated in every chunk, tables flattened into nonsense, scanned pages with no text), HTML (navigation, cookie banners, and footers dominating the text), and slides and spreadsheets, where meaning lives in layout and cell relationships.
Practices:
- Use a layout-aware parser (for example Docling, Unstructured, or a cloud document-AI service) and inspect samples by eye. Spend an afternoon reading what your parser produced; it pays back immediately.
- Convert to Markdown with headings preserved and tables rendered as Markdown tables (or serialized rows with column headers repeated).
- Strip boilerplate (headers, footers, nav). Keep title, section path, page number, URL, last-updated date, and author as metadata.
- For images and charts, generate captions or descriptions with a vision model and index those as text, linking back to the source.
- OCR scanned documents and flag low-confidence pages for review.
Chunking: the decision that matters most
Chunks are the unit of retrieval. Too small and they lose context; too large and they dilute the embedding and waste prompt budget.
Strategies
| Strategy | Pros | Cons |
|---|---|---|
| Fixed size (e.g. 500 tokens) + overlap | Trivial | Cuts through sentences and sections |
| Recursive character/sentence splitting | Respects paragraphs | Still structure-blind |
| Structure-aware (by heading/section) | Chunks match how humans organize info | Needs good parsing |
| Semantic splitting (embedding shifts) | Topic-coherent | Costlier, less predictable |
| Parent-child (small chunks retrieved, larger parent returned) | Precise match, rich context | More bookkeeping |
A strong default: split on headings first, then on paragraphs, targeting roughly 200-500 tokens per chunk with 10-15 percent overlap, never splitting inside a code block or table.
type Chunk = {
id: string;
docId: string;
text: string;
sectionPath: string[]; // ["Billing", "Refunds", "Annual plans"]
page?: number;
updatedAt: string;
acl: string[]; // who may see this
};
export function chunkMarkdown(doc: ParsedDoc, maxTokens = 400, overlapTokens = 50): Chunk[] {
const chunks: Chunk[] = [];
for (const section of splitByHeadings(doc.markdown)) {
for (const piece of packParagraphs(section.paragraphs, maxTokens, overlapTokens)) {
chunks.push({
id: `${doc.id}:${chunks.length}`,
docId: doc.id,
text: piece,
sectionPath: section.path,
page: section.page,
updatedAt: doc.updatedAt,
acl: doc.acl,
});
}
}
return chunks;
}Contextual chunk headers
A chunk saying "The limit is 30 days" is ambiguous in isolation. Prepend context before embedding (and optionally generate it with an LLM, an approach popularized as "contextual retrieval"):
Document: Acme Billing Policy (updated 2026-09-01)
Section: Refunds > Annual plans
The limit is 30 days from the purchase date...Embedding the header-plus-text improves matching considerably for little cost. Store the clean text separately for display.
Parent-child retrieval
// Index small chunks (~200 tokens) for precise matching,
// but return the surrounding section (~800 tokens) to the model.
const hits = await search(queryEmbedding, { limit: 20 });
const parents = dedupe(hits.map(h => h.parentId));
const context = await loadParents(parents.slice(0, 6));Embeddings and indexing
- Choose an embedding model suited to your language(s) and domain; evaluate on your data rather than leaderboard averages. Consider dimension (storage and latency) and whether the model supports matryoshka truncation to cut vector size.
- Embed documents and queries consistently; some models need different prefixes or instructions for queries vs documents.
- Normalize vectors and use cosine (or inner product) consistently with your index.
- Store vectors where your operational story is strongest: Postgres with
pgvectorfor simplicity and transactional consistency with metadata, or a dedicated vector database at larger scale. Use an HNSW index and tuneef_searchfor recall vs latency. - Version your embeddings. When you change models, you must re-embed everything; keep
embedding_modelin metadata and build the new index alongside the old, then switch.
CREATE TABLE chunks (
id TEXT PRIMARY KEY,
doc_id TEXT NOT NULL,
text TEXT NOT NULL,
section TEXT[],
acl TEXT[] NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
embedding vector(1024),
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', text)) STORED
);
CREATE INDEX chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX chunks_tsv_gin ON chunks USING gin (tsv);
CREATE INDEX chunks_acl ON chunks USING gin (acl);Hybrid retrieval and fusion
Vector search captures meaning ("how do I get my money back" matches "refund policy") but fumbles exact tokens: product codes, error messages, names, acronyms. Keyword search (BM25 or Postgres full-text) nails those. Use both.
-- Vector candidates
WITH vec AS (
SELECT id, row_number() OVER (ORDER BY embedding <=> $1) AS rnk
FROM chunks
WHERE acl && $3 -- permissions applied BEFORE ranking
ORDER BY embedding <=> $1
LIMIT 50
),
-- Keyword candidates
kw AS (
SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS rnk
FROM chunks, websearch_to_tsquery('english', $2) q
WHERE tsv @@ q AND acl && $3
ORDER BY ts_rank_cd(tsv, q) DESC
LIMIT 50
)
-- Reciprocal Rank Fusion
SELECT c.id, c.text,
COALESCE(1.0 / (60 + vec.rnk), 0) + COALESCE(1.0 / (60 + kw.rnk), 0) AS score
FROM chunks c
LEFT JOIN vec ON vec.id = c.id
LEFT JOIN kw ON kw.id = c.id
WHERE vec.id IS NOT NULL OR kw.id IS NOT NULL
ORDER BY score DESC
LIMIT 40;Reciprocal Rank Fusion (RRF) scores each item as the sum of 1 / (k + rank) across lists (k is typically 60). It needs no score normalization and holds up well, which is why it's the common default.
Additional knobs: metadata filters (product, version, language, date range), recency boosts for time-sensitive corpora, and per-collection weighting.
Reranking
First-stage retrieval (bi-encoder vectors, BM25) is fast but approximate. A cross-encoder reranker reads the query and each candidate together and scores relevance much more accurately, at higher cost. Retrieve 30-100 candidates, rerank, keep the top 5-10.
export async function retrieve(query: string, user: User) {
const candidates = await hybridSearch(query, { limit: 50, acl: user.groups });
const scores = await reranker.score(
candidates.map((c) => ({ query, passage: c.contextualText }))
);
return candidates
.map((c, i) => ({ ...c, rerankScore: scores[i] }))
.sort((a, b) => b.rerankScore - a.rerankScore)
.filter((c) => c.rerankScore > MIN_SCORE) // allow "nothing relevant found"
.slice(0, 8);
}A reranker typically delivers the biggest quality jump per unit of effort after good chunking. Apply a relevance threshold so that weak matches result in "I couldn't find that" rather than a hallucination built on irrelevant text. Watch latency: batch reranker calls and cap candidate counts.
Query understanding
Users write vague, conversational, multi-part queries. Transform them before retrieval:
- Contextualize follow-ups: "what about for annual plans?" needs the prior turn. Rewrite into a standalone query.
- Expand or paraphrase to cover vocabulary mismatch (generate 2-3 variants, retrieve for each, fuse).
- Decompose multi-hop questions ("compare the refund policy with the cancellation policy") into sub-queries, retrieve for each, then synthesize.
- HyDE (hypothetical document embeddings): have the model draft a plausible answer, embed that, and search; useful when queries are short and answers are long.
- Route by intent: some questions need SQL or an API call (structured data), not document retrieval.
const rewrite = await llm.json({
system: "Rewrite the user's latest message as a standalone search query using the chat history. Also list up to 3 alternative phrasings.",
schema: z.object({ standalone: z.string(), alternatives: z.array(z.string()).max(3) }),
input: { history, message },
});Keep the rewriting model small and fast; it sits on the critical path.
Generation: grounded, cited, and honest
Prompt structure that works:
You answer questions using ONLY the provided context.
- If the context does not contain the answer, say you don't know. Do not guess.
- Cite sources as [1], [2] matching the numbered context blocks.
- Quote exact numbers, dates, and policy terms from the context.
- If sources conflict, say so and prefer the most recently updated.
<context>
[1] (Billing Policy > Refunds, updated 2026-09-01)
...text...
[2] (FAQ > Cancellations, updated 2026-03-14)
...text...
</context>
Question: {standalone query}Good practices:
- Order context deliberately: models attend best to the start and end of long contexts, so put the strongest chunks first and avoid padding with marginal ones. More context is not better context.
- Number the sources and verify citations after generation (does each cited claim appear in the cited chunk?). Cheap checks or an LLM-as-judge pass can catch fabricated citations.
- Return source links to users so they can verify, which also builds trust.
- Use structured output when downstream code consumes the answer.
- Treat retrieved text as untrusted: it can contain prompt injection. Keep instructions and data clearly separated and avoid giving the generation step powerful tools. See the prompt injection post on this blog.
Access control and freshness
- Enforce permissions at retrieval time, via filters on the query (the
aclfilter above), not by asking the model to withhold information. A chunk the user cannot see must never enter the prompt. - Propagate ACL changes quickly: when a document's permissions change, update chunk metadata promptly.
- Incremental ingestion: detect changed documents by hash or
updated_at, re-chunk and re-embed only those, and delete stale chunks. Stale content silently erodes trust. - Track document freshness in the answer (for example "per the policy updated 2026-09-01").
Evaluation: measure retrieval and generation separately
Build a golden set of 100-300 real questions (from support tickets, search logs, domain experts) with the expected source passages and ideal answers. Evolve it as production reveals failures.
Retrieval metrics
| Metric | Question it answers |
|---|---|
| Recall@k | Did the right chunk appear in the top k? (most important) |
| MRR | How high did the first right chunk rank? |
| nDCG@k | Is the ordering good when several chunks are relevant? |
| Context precision | How much of the retrieved context was actually useful? |
export function recallAtK(results: string[], relevant: Set<string>, k: number) {
const top = new Set(results.slice(0, k));
const hits = [...relevant].filter((id) => top.has(id)).length;
return relevant.size === 0 ? 1 : hits / relevant.size;
}
export function mrr(results: string[], relevant: Set<string>) {
const idx = results.findIndex((id) => relevant.has(id));
return idx === -1 ? 0 : 1 / (idx + 1);
}Generation metrics
- Faithfulness / groundedness: is every claim supported by the retrieved context?
- Answer relevance and correctness against reference answers.
- Refusal accuracy: does it decline when the corpus lacks the answer, and answer when it does?
- Citation accuracy.
LLM-as-judge works for scale if you calibrate it against human labels on a sample. Run the suite in CI on every change to chunking, embeddings, prompts, or models, and track results over time. Also monitor production: thumbs up/down, "no answer" rate, queries with low rerank scores (content gaps), and latency percentiles.
Common failure modes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Right doc exists, never retrieved | Poor chunking, vocabulary mismatch | Contextual headers, hybrid search, query expansion |
| Exact IDs/error codes not found | Vector-only retrieval | Add BM25 |
| Relevant chunk at rank 15 | No reranker | Add cross-encoder rerank |
| Answers mix old and new policy | Stale index, no recency handling | Incremental ingestion, date metadata, recency boost |
| Confident wrong answer | No relevance threshold, weak prompt | Threshold + "say you don't know" + faithfulness checks |
| Tables garbled | Parser | Layout-aware parsing, table-to-Markdown |
| Multi-part questions half-answered | Single retrieval pass | Query decomposition |
| Latency too high | Too many candidates / big reranker | Cap candidates, cache, smaller models, streaming |
| User sees data they shouldn't | ACL not applied in retrieval | Filter in the query layer |
Build order
- Parse a representative sample and read the output.
- Structure-aware chunking with metadata.
- Create the golden set before tuning anything.
- Baseline: vector search only. Record recall@k.
- Add BM25 + RRF. Re-measure.
- Add a reranker. Re-measure.
- Add query rewriting. Re-measure.
- Harden generation: citations, refusal behavior, injection resistance.
- Add ACL filtering, incremental ingestion, monitoring.
- Only then consider heavier techniques (graph retrieval, agentic multi-step retrieval, fine-tuned embeddings).