When investigating cases where the model answered incorrectly, I sometimes run into this situation: the retrieval results are all correct, several passages are present, and the standard answer is in one of them. If I reorder these passages and feed them back to the model, it answers correctly. The only difference is the order—in production, they are concatenated by similarity from highest to lowest.
After that day, I stopped thinking of RAG as just a retrieval pipeline. It is more like preparing a temporary set of materials for the model: what to find, in what order to place it, and how much to include are all editorial decisions.
Chunking Sets the Ceiling
Chunking is the least sexy part, and the hardest to change later. Once the index is built and hundreds of thousands of records have been loaded, changing the chunking strategy is basically rebuilding the knowledge base. So it deserves a few extra days at the very beginning of the project—probably the highest-return days in the entire pipeline.
Fixed-length chunking is simple, but it does not understand documents. When the body of a clause and its exception are split into two chunks, retrieval hits the first half, and the model answers from that half—with a confident tone. These errors are the hardest to spot because they read fluently, just incompletely.
Semantic or recursive chunking is better, prioritizing splits at headings, paragraphs, and sentences. Overlapping windows can mitigate information loss at boundaries, typically at a ratio of 10–20%. The cost is index redundancy: the same text is stored multiple times, the diversity of recall results drops, and deduplication must be added after recall.
Chunking strategies should be separated by document type. Legal clauses and API docs suit hierarchical chunking—one clause or one endpoint per chunk; meeting minutes and customer service logs have no clear hierarchy, so chunking by speaker or time window is more natural; product manuals mix text and images, so captions must first be linked to the body text. Using one set of parameters for all types usually means it is not good enough for any of them.
There is no universal chunk size. Chinese and English have different character information density, and the semantic boundaries of code and technical docs are another matter entirely. Copying someone else’s numbers often just means repeating their mistakes. I start from a middle value and use an evaluation set to look at two types of errors: noise from chunks that are too large, and missing context from chunks that are too small—then tune toward whichever side has fewer errors.
Reading order in multi-column PDFs also often goes wrong. Extracting text by coordinates easily interleaves the left and right columns into one passage, completely garbling the semantics. For these files, I would rather use a layout analysis tool to restore the reading flow before chunking—slower, but trustworthy.
What I use more often now is small-chunk indexing with large-chunk recall. Index at a very fine granularity; after a hit, trace back to the section it belongs to and hand the model more complete context. Retrieval sensitivity and the amount of information generation needs can then be tuned separately, without compromising on a single chunk size. The trouble is maintaining the mapping between chunks and parent chunks—when deleting a document, you must cascade the cleanup, or you will recall orphaned fragments.
Tables need separate handling. Direct OCR followed by chunking destroys row-column relationships; the model sees a string of numbers and does not know which column is the amount. A more reliable approach is to generate a natural-language summary for each table, index the summary, and after a hit, feed the original structured table to the model rather than chopped text. The summary is only responsible for being retrieved; the answer is still based on the original table.
Heading hierarchy should be attached to each chunk as metadata. A chunk containing only “the price is 500 yuan” cannot tell which product it belongs to; with the section path attached, retrieval relevance improves noticeably. This costs very little and pays off more than I expected. Likewise, document source, version, update time, and permission labels should all be written in during chunking—all later filtering depends on them.
The failure rate of the parsing stage is often underestimated. In any batch of PDFs, there are always a few scanned files or ones with strange font encodings that parse into gibberish. My current approach is to run a quality check on parsing results first: anything with an abnormal character ratio or too much empty text goes straight to a manual queue, never silently into the database. Dirty data does not throw an error when it goes in; it just becomes an inexplicable bad case months later.
Duplicate documents also need handling. The same policy stored five times on a shared drive becomes five nearly identical sets of vectors after chunking; all are recalled during retrieval, crowding out the content that actually differs. Deduplication cannot rely on filenames alone—it must look at body-text similarity while keeping the latest version.
The entire data pipeline thus becomes heavier. Parsing, summarization, metadata extraction—each step can fail, and each must support reruns. I have spent far more time on this than on tuning embedding models.
Reranking Buys Precision at the Cost of Latency
The goal of the retrieval stage is not to miss anything; the goal of the reranking stage is not to be wrong. These two things should be done separately—measuring them with the same metric only lets them mask each other’s flaws.
A dual-encoder architecture computes document vectors offline; at query time it only computes the query vector, and a single approximate nearest-neighbor search can pull candidates from millions of records. It is fast, but coarse at judging subtle differences. A cross encoder concatenates query and document and runs them through the model together, capturing word-to-word correspondences with high precision—but every pair must be computed in real time, making a full-library scan impossible.
So the standard approach is a funnel: recall dozens to hundreds, rerank, and keep only a few. The input size of reranking directly determines cost; going from a thousand objects to fifty changes latency by an order of magnitude. This number is not pulled out of thin air—it depends on how much of the latency budget can be allocated to it.
The latency budget should be allocated before implementation. Given an end-to-end total budget, write down how much retrieval, reranking, and generation each get before you start. Once you do, you will find that reranking gets very little room—and you will understand why many teams use it only for high-risk queries.
Query types can also be routed. Queries containing IDs, model numbers, or error codes go through keyword search first, then vector search; purely natural-language open questions go straight to vector search plus lightweight reranking. A single routing rule suffices—no model needed, near-zero cost—and it saves a lot of unnecessary reranking.
When not to add reranking: when the corpus is small, queries are straightforward, and the latency budget is extremely tight. In these three cases, the marginal gain from reranking does not justify the P99 jitter it introduces. Reranking models usually need a dedicated GPU—a fixed cost for small teams, not pay-as-you-go. Before adding one, ask: who pays when that machine sits idle?
Hybrid retrieval follows the same logic. Adding a BM25 path compensates for weak exact matching; fusion uses RRF (reciprocal rank fusion) to merge by rank, sidestepping the scale mismatch between the two score types. How many results to take from each path and how to set weights—I grid-search on a validation set, looking at recall rather than total score. This process is crude, but more reliable than guesswork, and easy to recalibrate after switching embedding models.
Weighted summation is not unusable. It preserves the strength information of both score types and is more nuanced than rank fusion on some queries, but it requires score normalization—and normalization parameters drift with the data. RRF sacrifices that information in exchange for determinism and almost no parameter tuning. For me, that trade is worth it, because I do not trust a parameter that needs retuning every month.
The combined cost falls on the engineering side: two sets of indexes, two sets of tuning, double the write path. There is also a hidden cost—if the two recall paths disagree a lot, the reranking model receives contradictory candidates, making judgment harder.
Approximate search parameters also quietly affect recall. Shrinking the search scope of a graph index or the number of probed clusters in an inverted index lowers latency, at the cost of missing high-scoring documents—and missing them randomly. Such problems are not obvious in offline evaluation but show up online as “occasionally answering off-topic.” My habit is to put these parameters in configuration, record them alongside evaluation results, and require a benchmark run with every change.
Every layer added to the retrieval pipeline trades maintenance cost for accuracy. Before adding one, ask: if this layer breaks, who fixes it?
The choice of reranking model affects the experience more than its parameters do. Small models are fast and memory-friendly, but they can’t distinguish documents that are “similar in meaning but opposite in conclusion”; large models judge more accurately, but latency and cost rise together. I usually start with a small one on the evaluation set, check whether the top few rankings are correct, and switch if it’s not enough.
Reranking performance should be evaluated separately. Fix the same batch of retrieval results and look only at ranking changes before and after reranking—that’s the only way to tell whether the problem is in reranking or retrieval. Mixed into end-to-end metrics, changes on either side mask each other, and in the end no one knows which step did the work.
Context is a layout problem
Long windows haven’t solved the problem of attention allocation. As context grows longer, the model’s use of the middle portion actually declines, and information at the beginning and end is more likely to be adopted. This isn’t a defect of a particular model; it’s a general phenomenon.
So I treat context construction as layout: put the two most relevant passages at the head and tail, and the next most relevant in the middle, rather than simply stacking by score from high to low. This change requires no training and no model swap—just modify a concatenation function.
Another habit is to set a threshold rather than always taking the top k. When scores are generally low, I’d rather supply three passages than pad out ten. Once noise gets in, the model won’t tell you it’s been disturbed; it will just answer more vaguely. Thresholds should be set separately by query type—stricter for factual queries, looser for open discussion.
In multi-turn conversations, the query used for retrieval can’t just be the user’s last sentence. Follow-ups like “What about this one” or “What about the second option” are meaningless out of context. I use the last two or three turns of dialogue to have the model rewrite a self-contained query, then use that for retrieval. This step is cheap, has a big impact on the experience of continuous follow-ups, and is the step most easily skipped.
The context should also indicate the relationships between passages. If two passages on the same topic from different versions are simply concatenated in order, the model can’t tell which is newer. I habitually add a line of source information before each passage: document name, version, section, update time. It doesn’t use many tokens, but it noticeably reduces “cited an old version” errors.
The “two-end layout” yields different benefits across models. Some models are insensitive to order, others very sensitive. I don’t tune layout for individual models—switching models would mean retuning, and the maintenance cost is too high. Fixing one approach—“strong information at both ends, weak information in the middle”—is good enough.
I don’t use context compression much. Having the model extract first and then answer amounts to an extra inference pass and introduces new distortion. It’s only worth doing when the context truly exceeds the budget and all sources must be retained. If I do it, I keep the original citation numbers for traceability.
Just because it fits doesn’t mean the model will read it.
I’ve said this many times in reviews. Window size is a capacity metric, not an effectiveness metric. Solutions that sell window size as a feature usually haven’t seriously done context ordering.
A truncation strategy is also needed. When truly over budget, drop low-score passages first, then duplicates, and compress last. Reverse the order and you’ll compress the only useful passage into a one-sentence summary.
Guardrails and evaluation are both grind work
The first layer is prompt constraints: answer only based on the given material, and say you don’t know if the material doesn’t contain it. It works but is unreliable. The model is weak at judging “absence,” especially when the material contains related but incomplete content—it tends to fill in the gaps.
The second layer is citation. Require every conclusion to be tagged with a source number, then check in code whether the number actually exists in this retrieval list. This turns a generation problem into a verification problem and can block some fabricated citations. What it can’t block is “correct citation but excessive conclusion.” To be more thorough, you could further check whether the cited passage actually contains the key entities in the answer, but that requires additional model judgment, and both cost and false positives rise.
The third layer is post-hoc verification. Use a small model or a natural language inference (NLI) model to judge whether the answer is supported by the material, or sample the same question several times to see whether the conclusions are consistent. Both methods are expensive and only suitable for high-risk scenarios. Self-consistency voting has a side effect: multiple samples amplify the model’s own preferences—if it’s wrong in the same place every time, voting only makes the error more confident.
With all three layers, cost and latency become considerable. Most teams stop at the first layer, which is a rational choice—provided they accept its miss rate and give users an entry point in the product to check the original text.
Refusal can also be graded. When retrieval confidence is high and the answer has clear citations, answer directly; when confidence is medium, give a conditional answer with the original text attached; when confidence is low, switch to search or hand off to a human. Hard refusal looks safe, but the user’s question isn’t solved—just pushed back. Graded handling is more trouble, but the experience is closer to the real capability boundary.
I keep the evaluation set at around fifty items, all from real questions. Fabricated questions have neat sentence structures and accurate terminology, resembling exam questions; real users omit subjects, mix in colloquialisms, and point ambiguously. The two distributions are far apart—a system tuned on the former will be broken by the latter after launch.
Each question is labeled with three things: the standard answer, the key conditions that must appear, and the documents that must be cited. Scoring doesn’t look at intermediate scores, only at whether the final answer satisfies these conditions. This way the results don’t depend on any framework’s implementation details, and switching tools doesn’t require redoing them.
Retrieval and generation should be evaluated separately. Recall can be inflated by loosening thresholds, but answer accuracy won’t follow. Looking only at the total score makes it easy to get the illusion that “the system is improving.”
Evaluation should go into the pipeline, not be saved up until before a release. Every time you change chunking, change a prompt, or swap a model, run it automatically and compare metrics with the last run. People won’t remember to run it every time; the process will. The maintenance cost of this is mainly in the test cases, not the scripts.
Batch run costs also need control. A full evaluation finishing overnight is acceptable, but running it on every commit adds up fast. I usually split cases into two tiers: a small, fast tier for every commit; a full tier for the daily job.
Another easily overlooked dimension is timeliness. For the same question, the vector similarity between an old document and a new one may differ only slightly, and the old document, being better written, is actually more likely to be retrieved. My approach is to force the update time into the index, then filter by time at retrieval, or add a decay term to the ranking score. Hard filtering is more deterministic but blocks queries that “genuinely need a historical version,” so I only use it on policy-type knowledge bases.
The hardest part of this evaluation system isn’t building it—it’s maintaining it. Questions expire, answers change, and the people labeling change. I haven’t yet found a way to update it automatically; I can only go through it manually every quarter. It doesn’t produce new features, but it’s the only thing that can show the system hasn’t gotten worse.
Further reading: A few questions to tell whether someone has done RAG, Doing RAG on a personal blog: four pitfalls exposed by a small corpus
Comments