All articles
12 min read
#RAG#Retrieval#LLM#Production

How I Diagnose RAG Retrieval: Chunking, Ranking, and Embeddings

I diagnose RAG retrieval with a fixed query set, inspect document boundaries, and test ranking and embedding changes against quality, latency, and cost.

On this page

Scope. This is a diagnostic guide with illustrative examples, not a report of client results or a published benchmark. The proposed investigation order is a starting hypothesis; measurements on the target workload must confirm or change it.

Why this matters

I start a retrieval investigation by saving the failed query, expected evidence, actual candidates, and final context. Changing a model before collecting that record makes it harder to identify which part of the pipeline needs attention.

Consider an illustrative document query whose relevant clause is split across chunks or buried below near-matches. I would inspect document boundaries and candidate ranking before choosing an intervention. This example does not establish that chunking or re-ranking outperforms an embedding change.

The interventions rebuild different artifacts. An embedding change requires new vectors for affected content; a chunking change can require both preprocessing and new vectors. A separate query-time re-ranker can be changed without rebuilding the vector index. I estimate these costs for the actual corpus rather than assigning a universal duration.

Here's the debugging order I now follow, and why.

1. The diagnostic before any optimization

Before changing anything, I establish a baseline. "The retrievals feel wrong" is not a diagnostic. It's a symptom. When I have suitable reference answers and contexts, I use the RAGAS framework alongside latency, cost, and failure-case analysis to separate three failure modes before I touch a config:

  • Context Precision: checks the relevance of retrieved contexts; I record the exact variant and whether it considers rank. See the metric definition.
  • Context Recall: estimates coverage against reference information, rather than all unknown relevant content in a corpus. See the reference requirements.
  • Faithfulness: checks whether answer claims are supported by retrieved context. It does not establish that the context is true or current. See the metric definition.

I run RAGAS on a representative query set before doing anything else when I have suitable reference data. The diagnostic tells me where to investigate:

  • Low precision → investigate re-ranking, candidate generation, and chunking.
  • Low recall → investigate chunking, query coverage, and the embedding model.
  • Both low → I usually investigate chunking first, then evaluate whether re-ranking is needed.
  • Good precision and recall, low faithfulness → investigate prompting, model behavior, and context construction rather than retrieval alone.

I save the corpus snapshot, query set, reference labels, evaluator version, and judge configuration alongside the results. Model-based metric judgments can be wrong, so I inspect disagreements and individual failures. I do not treat an aggregate score as proof of correctness.

2. Chunking is usually the first structural intervention

A fixed size limit can separate a clause from its definition or a table heading from its rows. I inspect actual splitter output instead of assuming a size parameter preserves document structure.

A 512-token chunk in a financial document can be messy. It might start mid-sentence in a clause, include a table header but no rows, and end before the definition that gives the clause its meaning. The embedding for that chunk is semantically incoherent. I do not expect an embedding model to recover reliable retrieval from incoherent inputs.

# Character-based limit; this is not a token count
from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=50)
chunks = splitter.split_text(document_text)  # inspect boundaries on the actual documents

# Alternative: split Markdown using explicit heading metadata
from langchain_text_splitters import MarkdownHeaderTextSplitter

splitter = MarkdownHeaderTextSplitter(
    headers_to_split_on=[("##", "section"), ("###", "subsection")]
)
chunks = splitter.split_text(markdown_text)  # splits at heading boundaries

I would test clause boundaries for contracts, function boundaries for API documentation, speaker turns for transcripts, and paragraphs for prose. These are candidate strategies, not measured winners. The recursive splitter measures characters by default and tries larger separators first; chunk_size=512 in this example does not mean 512 tokens.

The second structural problem is metadata. A chunk without provenance — document ID, section title, creation date, source type — is just floating text. If retrieval returns a chunk from a superseded policy dated 2022, I need metadata to filter it at query time. In my pipelines, I add source, date, section, and document type to every chunk. I filter before similarity search when I can, and after similarity search when I must.

To evaluate a chunking change, I hold queries, references, retrieval settings, and the embedding model fixed where possible. I compare evidence coverage and inspect regressions; this guide reports no measured increase in recall.

3. Re-ranking: the retrieval step many pipelines skip

Vector similarity search retrieves documents whose embeddings are close to the query embedding in high-dimensional space. That's a useful approximation for semantic relevance. It is not a ranker I trust by itself.

As described in the Sentence Transformers guide, a bi-encoder encodes query and document separately. A cross-encoder scores a query-document pair jointly. I test whether that additional scoring stage improves the selected context enough to justify its measured cost; I do not assume a quality gain.

The example pipeline is straightforward: retrieve the top 50 candidates with vector search, then re-rank those 50 with a cross-encoder to get the top 5. The final 5 go into the LLM context window.

from sentence_transformers import CrossEncoder

# Stage 1: fast retrieval — top 50 candidates via vector search
candidates = vectorstore.similarity_search(query, k=50)

# Stage 2: cross-encoder re-ranking — top 5 from those 50
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
scores = reranker.predict([(query, doc.page_content) for doc in candidates])
ranked = sorted(zip(scores, candidates), key=lambda x: x[0], reverse=True)
top_5 = [doc for _, doc in ranked[:5]]

What to measure: the example adds inference for 50 query-document pairs. The candidate count and final cutoff of 5 are illustrative. I would record latency distributions, throughput, hardware, model revision, and quality changes before accepting this stage. No CPU latency result is reported here.

If re-ranking exceeds the latency budget, I compare fewer candidates, a different scoring model, or a retrieval-only configuration. I measure quality and latency for each option rather than assuming the direction or size of the tradeoff.

A re-ranker can reorder retrieved candidates but cannot recover evidence absent from that candidate set. I therefore measure candidate coverage separately from final-context precision.

4. Hybrid search: when BM25 helps and when it doesn't

Pure vector search can underperform on exact-match queries — product SKUs, case numbers, person names, specific version strings. When I see a corpus full of identifiers, I test a keyword component.

Hybrid search combines dense retrieval with sparse retrieval. Dense retrieval uses vector similarity. Sparse retrieval uses BM25 keyword scoring. The result lists are then merged, often with Reciprocal Rank Fusion. Several vector databases support hybrid retrieval directly; I verify the behavior and fusion options for the version I deploy. I prefer a direct implementation when it is available instead of maintaining a custom one.

I test a keyword component when failures involve identifiers. I also include paraphrases and ambiguous names in the evaluation set. An exact-match success does not establish that the same configuration handles semantic queries.

Fusion is implementation-specific. A weighted blend may expose an alpha parameter; Reciprocal Rank Fusion uses ranks and a different configuration. I record score normalization, weight direction, and fusion settings rather than assuming that a numeric weight transfers across systems. I tune on a development set and evaluate the chosen configuration on held-out queries.

Adding another retriever does not by itself repair missing source boundaries. I inspect the evidence returned by each component before accepting a more complex pipeline.

5. Metadata filtering before you scale

When query latency grows with an index, I inspect the query plan, filter selectivity, index configuration, and workload before choosing more hardware. Corpus size alone does not identify the cause.

Metadata filtering — filtering to a subset of documents before or after similarity search — can be cheaper than better hardware. It also solves a class of problems that embedding improvements cannot address.

Illustrative pre-filtering examples: documents from Q3 2024 and policy documents for customer tier Premium. I check whether the database applies these filters efficiently before similarity scoring. Post-filters can exclude superseded documents, but can also leave fewer results than expected. Access constraints must still hold on the final context.

Both require a metadata schema designed at index time for the filters I will need at query time. I design it before I need it. If I index documents with a created_at date but the most frequent query type is "show me current regulations", I also need a policy-status concept such as effective_through or an equivalent field. Without it, I end up filtering by date when I should be filtering by status, and the fix usually requires a full reindex.

6. Embedding model selection: follow the diagnosis

The diagnostics may point to an embedding change at any stage. My preference for inspecting source structure first is an investigation strategy, not evidence that it always has a larger effect.

I include domain vocabulary and multilingual queries when those are part of the workload. I compare candidate models on those slices rather than inferring suitability from model size or a general benchmark.

A public embedding benchmark can suggest candidates, but it does not establish their ranking on the target corpus. I need an evaluation with fixed queries and relevant evidence for that comparison.

When fine-tuning is worth it: I only consider fine-tuning when I have a labeled retrieval dataset, such as query → relevant document pairs, with enough examples to evaluate changes reliably. Fine-tuning a bi-encoder on the domain can improve recall, but it adds real cost: dataset collection, training infrastructure, and re-indexing the full corpus on every model update.

Before investing in fine-tuning, I run RAGAS after chunking and re-ranking when I have suitable reference answers and contexts. If recall is still low, I investigate structural problems, query coverage, and the embedding model. I do not expect fine-tuning to fix broken document boundaries or missing metadata. If recall is already high and the remaining failures are narrow, fine-tuning may not be worth the cost. The case where I consider it seriously is a well-structured pipeline with a documented domain-specific retrieval gap.

The category frame

Retrieval-Augmented Generation is often treated as a single monolith. In practice, I treat it as a stack of independent choices: chunking strategy, embedding model, retrieval mechanism (vector, keyword, hybrid), and re-ranker. Each has its own failure modes, cost structure, and tuning levers.

My proposed investigation order is: measure first, fix chunking, add re-ranking, consider hybrid search if keyword queries are failing, and tune the embedding model last if at all. That sequence keeps high-cost interventions for problems that the earlier diagnostics did not resolve.

If I can help you debug a RAG pipeline in production when RAGAS numbers do not match user experience — or help design one with reproducible evals from the start — write me.

FAQ

How should I diagnose poor RAG retrieval before changing configs?

When I have suitable reference answers and contexts, I measure with RAGAS on a representative query set, alongside latency, cost, and failure-case analysis. I separate Context Precision, Context Recall, and Faithfulness before touching a config. Low precision leads me to investigate re-ranking, candidate generation, and chunking. Low recall leads me to investigate chunking, query coverage, and the embedding model. When both are low, I usually investigate chunking first and then evaluate re-ranking. Low faithfulness with good retrieval metrics leads me to investigate prompting, model behavior, and context construction.

Why do I fix chunking before switching embedding models?

I do not expect an embedding model to recover reliable retrieval from incoherent inputs. Fixed-size chunks can split clauses, tables, definitions, or other semantic units. I choose a strategy that preserves document structure, such as clause-level chunks for contracts, function-level chunks for API docs, or paragraph chunks with sentence overlap for dense prose.

When should I add a cross-encoder re-ranker to a RAG pipeline?

I add re-ranking when precision is low and retrieved context contains too much noise. The illustrative pipeline retrieves the top 50 candidates with vector search, then uses a cross-encoder to select the top 5 for the LLM context window. I treat the added query-time latency as workload-specific and measure it before shipping.

I test hybrid search when misses involve exact identifiers, and compare it on both identifier and semantic-query slices. I inspect chunking, candidate coverage, and fusion settings before concluding which component helps.

When is embedding model tuning worth considering?

I choose an embedding intervention when the diagnosis and held-out evaluation support it. I consider fine-tuning only when I have a labeled retrieval dataset, enough examples to evaluate reliably, and a well-structured pipeline with a documented domain-specific retrieval gap.

Share this article

Related articles

  • I Keep Query JSON as a Retrieval Receipt

    I keep the public RAGFS query JSON as a retrieval receipt: query, file, score, content, and line range. I do not invent a quality benchmark.

    Oct 4, 20265 min read
    #RAG#FUSE#Linux#Retrieval
  • Six Function-Calling Patterns I Evaluate

    I examine six tool-interface patterns with illustrative code: schemas, typed results, concurrency, loop limits, routing, and tool choice.

    Nov 25, 202413 min read
    #LLM#Function Calling#OpenAI#Production
  • How I Design Source Checks for Autonomous Research Agents

    I describe a planner-executor-critic workflow for checking source support. Examples define routing and retained evidence, without measured detection accuracy.

    Nov 15, 202410 min read
    #AI Agents#Research#LLM#Production