Retrieval-augmented generation in production: scores, index memory, token budgets and failure analysis
A practical guide to RAG systems that hold up: choosing and converting similarity metrics, sizing vector indexes through rebuilds, budgeting the rendered prompt, and finding which stage actually fails.
Consolidates and expands four notes first published in Issue 002 on November 7, 2026. See the archive record.
Retrieval-augmented generation looks simple on a whiteboard: embed the documents, find the closest ones to a question, paste them into the prompt, let the model answer. In production each arrow in that diagram hides a decision that can fail independently. A similarity score can rank the wrong document first. An index that fits comfortably at steady state can run out of memory during its nightly rebuild. A prompt that fits on paper can overflow once the template and tools are rendered. And when an answer is wrong, teams routinely replace the retriever when the problem was somewhere else.
This guide works through those four places in pipeline order, with numbers you can check and a calculator for index memory.
1. Similarity scores ask different questions
A ranking you can verify by hand
Take a query q = (1, 0) and two stored vectors, A = (2, 2) and B = (1, 0.1). These are constructed coordinates, not real embeddings.
| Score | A | B | Winner |
|---|---|---|---|
| Inner product (larger wins) | 2 | 1 | A |
| Cosine (larger wins) | 0.7071 | 0.9950 | B |
| Squared L2 (smaller wins) | 5 | 0.01 | B |
A wins on inner product because it is longer, even though it points in a less similar direction. Cosine ignores length; L2 penalizes distance. None of them is wrong. They answer different questions, and an embedding model is trained with one of them in mind.
Thresholds do not transfer between metrics
Faiss documents that its L2 index reports squared distance, not the distance itself [1]. That leaves rankings unchanged but breaks thresholds: a distance cut-off of 0.2 corresponds to a squared cut-off of 0.04.
For unit-length vectors, squared L2 and inner product are tied together:
‖x − y‖² = ‖x‖² + ‖y‖² − 2(x·y) = 2 − 2(x·y)
On that unit sphere, maximizing inner product and minimizing squared L2 give the same exact ranking. Faiss describes normalizing both stored and query vectors to search by cosine with an inner-product index [1]; normalizing only the query cannot remove length differences among stored vectors.
Equivalent ranking does not mean equivalent scores. A cosine threshold of 0.8 becomes a squared-L2 threshold of 0.4, with the comparison reversed. A downstream filter still checking “greater than 0.8” will now accept and reject the wrong items.
A short diagnostic before blaming the index
- Keep a small reference set whose scores you can compute directly, and check the embedding output, stored representation, query transformation and returned score separately.
- Use an exact flat index for that test so metric mistakes are not confused with approximate-search recall loss.
- Check whether the reranker expects a similarity or a distance, whether filters run before or after top-k selection, and whether anything labeled “confidence” is calibrated. A cosine value is geometry, not a probability of being right.
- Decide how zero vectors are handled; normalization is undefined for them.
- When migrating embedding models, keep the old version and its test set, and compare relevance judgments and score distributions side by side.
2. Vector index memory: plan for the rebuild
One copy of the vectors
Consider a hypothetical corpus of one million 768-dimensional vectors stored as float32. Faiss lists its flat indexes at 4d bytes per vector [2]:
1,000,000 × 768 × 4 = 3,072,000,000 bytes ≈ 2.861 GiB
That excludes the documents themselves, metadata, query buffers and process overhead. At ten million vectors it becomes 30.72 GB, about 28.6 GiB. Count and dimension multiply; neither is a detail.
What different index types add
| Index (Faiss notation) | Bytes per vector | One million 768-d vectors |
|---|---|---|
| Flat (float32) | 4d | 2.861 GiB |
| IVF Flat | 4d + 8 (stored ID) | 2.868 GiB + quantizer |
| HNSW Flat | 4d + graph overhead | Depends on graph degree; measure |
| PQ, M = 96, 8 bits | ceil(M × b / 8) codes | 91.6 MiB + codebooks |
The figures follow the Faiss index summary [2]. Product quantization’s roughly 32-fold reduction in code size is real, but it is not a 32-fold reduction in deployment memory if full vectors are kept for reranking, and it is certainly not evidence of equal retrieval quality.
The peak is during the update
The awkward moment for capacity is usually the rebuild, not steady-state search. The old index keeps serving while the new one is built, and the build often keeps its own input matrix.
| Copies held at once | float32 payload |
|---|---|
| Serving index only | 2.861 GiB |
| Serving + replacement | 5.722 GiB |
| Serving + replacement + build input | 8.583 GiB |
These are accounting scenarios, not a claim about any library’s copying behavior. Replicas on other machines consume fleet memory without increasing one process’s working set; two indexes inside one process do. Budget both boundaries, and size the machine for the peak.
Attach relevance evidence to the memory saving
Before adopting a compressed index, measure which true nearest neighbors it misses against an exact-search reference on representative queries. Then test answer quality, because matching nearest vectors does not prove the retrieved documents answer the question. Record build time, peak resident memory, serialized size and serving memory separately, and run a rebuild under realistic load. A credible plan names the representation, acceptable retrieval loss, required live copies and update procedure. “The vectors fit” is only the first line.
3. Budget the prompt that is actually sent
Count after rendering, not before
The visible conversation is only part of what reaches the model. Chat templates add role markers and control tokens; tools add their definitions; retrieval adds evidence with labels and separators. Hugging Face’s chat-template documentation shows how structured messages become a model-specific token sequence [3], and warns that tokenizing the formatted text again with default settings can duplicate special tokens.
So the admission check belongs at the send boundary: render the final prompt, count it with the compatible tokenizer, reserve the output, and reduce or reject before sending. Recount after any change to template, tools, history or evidence. If exact remote counting is unavailable, label the local count as an estimate and keep headroom based on observed differences. Keep the tokenizer revision and template with the model revision, because a count from a different tokenizer does not bind another provider’s limits or billing.
A worked reservation
Assume a model with a shared 16,384-token window for input and output.
| Item | Tokens |
|---|---|
| Shared window | 16,384 |
| Reserved for the answer | −2,048 |
| Application safety margin | −512 |
| Available for input | 13,824 |
| Rendered instructions, history and tool definitions | −3,200 |
| Available for evidence | 10,624 |
If each retrieved chunk occupies 700 tokens including its labels and separators, fifteen chunks use 10,500 and leave 124. A sixteenth exceeds the budget by 576. Some interfaces have separate input and output caps instead of a shared window; read the actual contract.
Decide what is dropped
Tokenizer APIs offer truncation strategies such as longest-first or one-side-only [4]. Choosing one prevents an error, but it does not choose the right evidence. Clipping arbitrary characters can remove the exception, unit or date that qualified a passage while leaving the sentence that seems to support an answer. Prefer dropping whole lower-priority evidence units and keep each passage’s source and qualifications attached. Log counts and truncation decisions without copying private text into logs.
Chunking is an evidence decision
How documents are split before embedding decides what can be retrieved at all. Chunks that are too small separate a statement from its qualification: the rule in one chunk, the exception in the next. Chunks that are too large dilute the embedding with unrelated material and spend the token budget on text the answer does not need.
A few practices hold up across most corpora:
- Split on the document’s own structure (sections, headings, list items, table rows) before falling back to fixed lengths.
- Carry context into each chunk: the document title, section heading and effective date, so that a retrieved fragment still says where it came from and when it applied.
- Keep tables whole or convert them deliberately. A table row without its header is a list of numbers without units.
- Store the chunk boundaries with the index version, so a retrieval failure can be traced to the exact text that was available.
Chunking changes are re-indexing events. They deserve the same relevance evaluation as a new embedding model.
Freshness is part of correctness
A retrieval system answers from what it has indexed, not from what is currently true. If a policy document was updated this morning and the index rebuilds weekly, every answer until the rebuild is grounded in an obsolete source, and it will cite that source convincingly.
Decide, per document type, how stale an index may be, and design the update path to meet it: incremental insertion for frequently changing content, full rebuilds for structural changes. Store an effective date with each chunk, prefer the newest version when several match, and test with questions whose correct answer changed recently. Deleting superseded content matters as much as adding new content; an index that retains both versions leaves the model to choose between them.
Permissions belong inside retrieval
In a business deployment, the set of documents a user may see is part of the query. Filtering permissions after retrieval is fragile: if the top results are all documents the user cannot see, removing them leaves few or none, and the system may answer from weaker evidence without saying so. Applying the permission filter inside the search, so that only permitted documents compete for the top positions, avoids that failure and avoids accidentally exposing restricted text in prompts or logs. Test it with users who have narrow access, not only with administrators.
4. When the answer is wrong, find the stage
Three conditions for a grounded answer
For a defined question set, let:
- R: retrieval returns sufficient, permitted evidence;
- C: context assembly preserves that evidence and its qualifications;
- A: the answer uses it correctly.
For success that requires all three, the chain rule gives:
P(success) = P(R) × P(C | R) × P(A | R, C)
This does not assume the stages are independent. It also deliberately excludes answers produced from the model’s own memory when retrieval fails; those are outside the definition of a grounded answer.
A worked failure budget
Suppose an evaluation finds conditional rates of 0.90, 0.95 and 0.85. End-to-end success is 0.72675, or about 72.7%. Describing each component as “around 90%” hides that more than a quarter of answers fail.
| Change, others held fixed | New success rate | Gain |
|---|---|---|
| Baseline | 72.68% | — |
| Retrieval 0.90 → 0.95 | 76.71% | +4.04 pts |
| Answer use 0.85 → 0.90 | 76.95% | +4.28 pts |
In this example improving how the model uses evidence is worth slightly more than a better retriever, which is often the more expensive change. These are sensitivity checks, not predictions: improving retrieval may change which questions reach the later stages. Measure the changed pipeline rather than multiplying old rates.
The audit that produces these numbers
The original RAG work combined learned parameters with retrieved external memory [5]; that architecture makes evidence inspectable but does not validate claims by itself. “Lost in the Middle” found that the models it tested used information differently depending on its position in a long context [6], which is a reason to test the same evidence in different positions rather than a universal rule about current models.
For each failed question, keep the retrieved documents, the assembled prompt and the answer. Then classify: was the right source absent, truncated, crowded out, contradicted by a newer version, or present and misused? Two further checks matter in business settings. Evidence must come from the right tenant and the right time, so access control and document dates belong in retrieval, not just topical similarity. And the question set should include questions without an answer in the corpus, because a system that always answers fluently looks strong only when abstention is never rewarded.
Build the evaluation set before tuning
Every tuning decision in this guide, from metric to chunk size to number of retrieved passages, needs a fixed set of questions with known correct sources. Build it early: collect real questions from logs or from the people who will use the system, record which document and passage answers each one, and include questions whose answer is absent from the corpus. A few hundred well-labeled questions are enough to compare configurations, provided the uncertainty is reported honestly; our benchmark guide shows how wide the interval is at that size.
What one RAG query costs
The cost of answering a question with retrieval has more parts than the model call:
| Component | Scales with |
|---|---|
| Embedding the question | Query length; small per query |
| Vector search | Index size and type; memory-resident cost is mostly fixed |
| Reranking (if used) | Number of candidates × reranker size |
| Prompt processing | Rendered prompt length, dominated by evidence |
| Answer generation | Output length |
| Index maintenance | Corpus change rate and rebuild frequency, amortized over queries |
The largest variable term is usually prompt processing of the retrieved evidence. In the worked budget above, evidence is 10,500 of roughly 13,700 input tokens. Retrieving fifteen chunks when five would answer the question roughly triples that term for no gain. Measuring answer quality as the number of chunks varies is one of the cheapest optimizations available, and it reduces both cost and the chance that relevant evidence is crowded out.
Infrastructure notes
RAG moves load from the model to the data path. Index rebuilds create memory peaks on CPU servers that are easy to forget when GPU capacity dominates planning, and embedding a large corpus is a batch job with its own accelerator hours and power draw. When a team proposes re-embedding everything with a new model, the cost includes a full rebuild at peak memory, a period with two indexes live, and a relevance evaluation before switching. Scheduling that work for off-peak hours is cheaper on most commercial tariffs and gentler on shared infrastructure.
Sources and limitations
- Faiss: MetricType and distances: squared L2, inner product and cosine normalization; live wiki checked November 2026.
- Faiss index summary: bytes-per-vector table and identifier notes; live wiki checked November 2026.
- Transformers chat templates, version 4.57.1: formatting, control tokens and duplicate special-token warning.
- Transformers tokenizer API, version 4.57.1: truncation options.
- Retrieval-Augmented Generation, version 4: parametric and non-parametric memory.
- Lost in the Middle, version 1, §§3–4: position-sensitive results in the evaluated models.
Vectors, corpus sizes, token budgets and failure rates are constructed for explanation. No index was built and no model was evaluated for this guide. It consolidates and expands four shorter notes first published on November 7, 2026, whose addresses now redirect here.
Continue exploring
- Fine-tuning on a budget: LoRA, gradient accumulation, number formats and shipping the result
- How to read an AI benchmark: sample sizes, paired comparisons, latency tails and hidden workload mixes
- Where the memory goes when you serve a large language model