Retrieval-augmented generation is conceptually trivial: fetch facts at query time and put them in the prompt. Operationally it is a search engine, a derived-data pipeline and an access-control system glued onto a probabilistic consumer. It is the most common pattern in production AI, and most of its incidents come from the pipeline around the model rather than the model itself: stale indexes, leaked permissions, uncalibrated thresholds and latency budgets eaten before the first token.
Knowledge can live in three places: the weights (fine-tuning), the prompt (long context), or an external store queried per request (retrieval). The useful way to compare them isn't quality in the abstract. Ask what each one does to the three properties you have to operate: update latency (how long from a source edit to a changed answer), deletability (can you prove a fact is gone), and per-user scoping (can two users asking the same question see different facts). Weights score badly on all three. You can't un-train a leaked contract clause on a deadline, and every tenant shares one set of weights. Long context scores well on update latency and deletability, since the next request simply omits the text, but badly on scoping once each user needs a different slice. Retrieval is the only option that is good on all three, and it pays for that with a derived-data pipeline you now own.
Architect's note
Where the conventional advice is wrong: "always RAG" predates large windows and prompt caching. Run the arithmetic (illustrative numbers). A 150k-token handbook stuffed into every request is ~40× the input tokens of a 4k-token retrieved context. But if the provider bills cached prefix tokens at a steep discount and your traffic keeps the cache warm, the effective premium can drop to a small multiple. You also get to delete an embedding pipeline, an index, a reranker and a whole class of retrieval misses. The break-even is set by three things: corpus size, how often the corpus changes (every change invalidates the cached prefix), and whether each user sees a different slice of it. Per-user ACLs make one shared cached prefix impossible, and that alone often decides the question.
Worked, with illustrative prices: input at $3 per million tokens, cached-prefix reads billed at 10% of that, 1M requests a month. Stuffing an uncached 150k-token handbook into every request costs $0.45 a request, or $450k a month. A warm cache brings that to about $0.045, or $45k. A RAG prompt with 4k tokens of retrieved context costs $0.012, or $12k, plus the pipeline: embedding, an index cluster, a reranker fleet, and the on-call engineer who owns them. For a single-tenant corpus, a gap of $33k a month is often smaller than the fully loaded cost of running retrieval well. The cached option has two hidden conditions. First, warmth. Provider caches expire after minutes of inactivity (check your provider's TTL), so the discount only holds when each distinct prefix sees steady traffic. Spread 1,000 tenants, each with its own corpus, over the same 1M requests and most prefixes go cold between visits, so you pay full price, often plus a cache-write premium. Second, quality at depth. Answer quality over a 150k-token prompt is not guaranteed to match quality over 4k tokens of well-chosen evidence, so measure it on your own questions before you trust it.
Long context + prompt cache
no index to run
RAG, or cached long context per tenant
measure both
RAG
only option that fits
Long context + cache
cache rebuilt daily
RAG
incremental upserts
RAG + CDC ingest
freshness SLO
Fetch live, no index
tool call to source
RAG + ACL filter at query
leak risk
RAG + ACL filter + CDC
hardest cell
Fine-tuning appears in no cell: it changes behaviour, not knowledge. The bottom row is where most RAG incidents come from — the index is a derived copy of data whose permissions and existence change underneath it.
RAG is two pipelines that meet at the index. The offline one runs parse → chunk → embed → upsert. The online one runs embed → retrieve → rerank → assemble → generate. They have opposite operating profiles. Offline work is throughput-bound, rate-limited by your embedding quota, and only needs to be fresh by some SLO. Online work is latency-bound, driven by p99, and has to be correct for this user right now. Most organisational trouble comes from one team owning both pipelines with one set of SLIs.
Offline · build the index
Documents
pdf · web · db
Chunk
split + overlap
Embed
→ vectors
Vector DB
ANN index
Online · answer a query
Query
Embed
ANN search
top-k
Rerank
cross-encoder
Build context
+ prompt
LLM
Answer
+ citations
Treat the index as what it is: a materialized view of systems of record, with every consistency problem that implies. Three failures recur in production.
Deletes and revocations lag. A document is deleted or a user loses access, but its chunks remain answerable until every derived copy converges: the CDC or poll interval, the embedding queue, the index segment merge, and the semantic or answer cache nobody put on the diagram. In normal operation that window is minutes. After a bulk re-permissioning event (a reorg, an acquisition, a customer offboarding) the embed queue backs up behind the rewrite and the window stretches to hours. That is exactly when the revoked content is most sensitive. Chunk-level ACL metadata copied at ingest time is only a cache of the permission. The authoritative check has to hit the source at query time, or at least a permission service with its own freshness SLO.
How the cascade unfolds, with illustrative numbers. A reorg moves 400k documents averaging 2k tokens into new permission groups. The ingest pipeline treats any change to a document as a reason to re-chunk and re-embed it, which is the default in most home-grown pipelines and many connectors. That is 800M tokens queued against an embedding quota of, say, 1M tokens a minute: about 13 hours of backlog. The queue is FIFO, so ordinary content edits sit behind it and freshness SLOs fail across the whole corpus. Meanwhile the moved documents still carry their old ACL metadata in the index. Anyone who lost access keeps retrieving them for most of those 13 hours. The on-call engineer sees "embedding queue lag", not "data exposure", because nothing on the dashboard connects the two.
The structural fix is to split the ingest path in two. Metadata-only changes (ACLs, titles, tags, soft deletes) should update index payloads in place, with no re-embedding, in seconds. Content changes go through the embed queue. Deletes and revocations take a priority lane that can't sit behind bulk work. Add content hashing per chunk so that re-ingesting an unchanged document is a no-op. Then the 400k-document reorg becomes 400k payload updates, which is minutes of work, and the embed queue never notices.
Embedding version skew. Query and document vectors are only comparable when the same model produced them. Upgrading the embedding model means re-embedding the whole corpus, and in dollars that is usually cheap. The real cost is the migration: dual-writing to two indexes, backfilling at whatever rate your embedding quota allows, cutting reads over only after recall@k on the golden set matches or beats the old index, and holding 2× storage for the overlap. Teams that upgrade in place and re-embed lazily get an index whose halves live in different vector spaces. Nothing errors. Recall just degrades for the documents that haven't been re-embedded yet. Budget the migration in hours, not dollars. With illustrative pricing of a few cents per million tokens, re-embedding a 1B-token corpus costs tens of dollars. At 1M tokens a minute it also takes about 17 hours of wall-clock time, competing with live ingest for the same quota. And if vendor quotas are per-model, you may need a quota increase before starting.
Silent ingest drift. A parser upgrade starts dropping tables, a PDF source switches to scanned images, or a wiki migration strips headings your chunker split on. Retrieval quality falls for one content type while aggregate metrics barely move. Track chunk counts, mean chunk length and empty-chunk rate per source as ingest SLIs, and alert on step changes.
Chunking fixes the unit of retrieval, which puts a hard ceiling on recall. No reranker can recover an answer split across two chunks when only one of them is retrieved. A single embedding also averages everything in its window. A 2,000-token chunk covering five topics lands somewhere between all five and near none of them, so coarse chunks lose on matching long before they lose on prompt budget. Fine chunks match sharply but arrive stripped of the referents ("it", "the above limit", "this plan") that made them answerable. Overlap and splitting on structure (headings, list items, code blocks, table rows) are the baseline, not the optimisation.
Too big → retrieval returns noise. Too small → a chunk loses the context that made it meaningful. Overlap (and splitting on structure — headings, paragraphs — not fixed character counts) is where quality is won or lost.
Two refinements matter more than tuning the window size. Small-to-big retrieval embeds small units (a paragraph) for precise matching but returns the enclosing parent (the section) to the model. This decouples the granularity you match on from the granularity you read. Contextual headers prepend the document title and heading path to each chunk before embedding, so "the limit is 30 days" carries the fact that it lives under "Refunds › EU customers". Without that, a chunk is ambiguous across a hundred policies that share its wording.
Sizing, worked (illustrative): a corpus of 1B tokens cut into 512-token chunks with ~15% overlap is ~2.25M chunks. At 1,024 float32 dimensions that is ~9 GB of raw vectors before index overhead. Halve the chunk size and you double the vector count, the index memory and the candidates each query must beat. Chapter 4 covers what that does to the ANN index. Chunk size is a capacity decision as much as a quality one.
The second-order effect nobody plans for is boundary stability. Incremental ingest only saves money if an edit changes a few chunk hashes. Fixed-size windows break that promise: insert one paragraph near the top and every later boundary shifts, every hash changes, and the whole document is re-embedded. For a wiki where popular pages get small edits all day, that multiplies embedding volume by the number of chunks per page. It also churns the index, and in HNSW-style graphs heavy delete-and-reinsert degrades graph quality until the next rebuild (Chapter 4). Structure-aware chunking anchors boundaries to headings, so an edit re-embeds only the section it touched.
Content types that break text chunkers, and what to do about each:
Decision rule for size: begin with structural units capped at a few hundred tokens and measure recall@k on the golden set at two or three caps. Move to small-to-big only when the data shows the split. Matching improves at small sizes while answer quality needs larger context: small chunks win recall@k, but end-to-end answers get worse. Don't tune overlap percentages by hand before that. On structurally chunked text, overlap is a patch for bad boundaries, not a lever.
Dense and sparse retrievers fail on disjoint query populations. Dense retrieval misses exact tokens the embedding model has never seen as meaningful: error codes, SKUs, ticket IDs, new product names, and internal acronyms coined after the model was trained. Sparse retrieval misses paraphrase. Enterprise query logs are often full of both, and the identifier queries are the ones users escalate, because "it couldn't find ERR-4471" reads as incompetence rather than fuzziness. Hybrid retrieval is the default. The interesting decisions are in the fusion.
Dense · embeddings
semantic match — "refund" finds "money back"
Sparse · BM25 keyword
exact match — codes, IDs, rare names, "GDPR"
Fuse (RRF)
combine both rankings → recall neither gets alone
Why reciprocal rank fusion rather than adding scores: cosine similarity and BM25 live on incomparable scales, and BM25's scale varies with query length and corpus statistics. RRF throws scores away and sums 1/(k + rank) across retrievers, with k conventionally around 60, so an item ranked well by both beats one ranked first by only one. The failure mode follows directly. On a query where one retriever is useless (BM25 on a paraphrase with no shared terms, or dense on a bare SKU), RRF still promotes that retriever's top ranks at equal weight. Mature systems weight the fusion per query class: route queries that look like identifiers toward sparse and natural-language questions toward dense, then check that the weights help on the golden set.
With k = 60, 1/61 vs 1/70 differ by only ~15%, so fusion behaves close to "how many lists did you appear in". D, ranked 10th and 8th, outscores the exact SKU hit C. That is the right call for a paraphrased question and the wrong one for an identifier lookup.
The table shows the mechanism behind both RRF's robustness and its blind spot. At k = 60 the reciprocal curve is so flat across the top ranks that being first on one list is worth less than being tenth on two. That is ideal when both retrievers are informative and noisy. It is wrong when one retriever is authoritative for this query. A cheap classifier works well as the fix: a regex for identifier shapes, plus a length and stopword heuristic. Illustratively, if more than about 20% of your traffic is identifier-shaped, a per-class fusion weight, or a hard "exact match wins" override, is usually worth its complexity. Below that, a plain RRF and a golden set that includes identifier queries is enough. Lowering k sharpens the top-rank advantage. Treat it as a tuned parameter, not a constant from the original paper.
The other conventional advice to question is "dense retrieval is the modern part, BM25 is the fallback". On narrow technical corpora with heavy jargon, a well-tuned BM25 with the domain's synonyms can match or beat a general-purpose embedding model. Domain vocabulary is exactly what the embedding model saw least of in training. Before paying for embedding fine-tuning, run BM25 alone on the golden set. The answer frequently resets the roadmap.
The reason for two stages is architectural, not a tuning trick. A bi-encoder embeds query and document separately, so document vectors can be precomputed and searched sublinearly, but the model never sees the two together. It can't notice that the query says "not" or "EU only", or asks about version 3. A cross-encoder attends across the query and the candidate jointly, which is far more precise, but its cost is per (query, document) pair and nothing can be precomputed. So stage one buys recall cheaply over millions of chunks, and stage two buys precision expensively over tens.
The reranker is where the latency budget quietly goes. A cross-encoder scores 50 candidates × ~512 tokens, so it processes ~25k tokens per query on the critical path, every query, uncacheable. Add a query-rewrite LLM call in front and the pipeline can spend half its time-to-first-token before generation starts. The candidate count N is the dial: recall into the reranker rises with N and flattens, while rerank latency grows roughly linearly with N. Choose N by plotting recall@N of the first stage on your golden set and stopping where it flattens. Don't take a number from a blog post. Rerank the distinct candidates after fusion and dedup, not the concatenated lists.
Decision criteria (illustrative thresholds): skip query rewriting unless an eval shows it lifts recall on the conversational, follow-up-style queries that need it. Gate it behind a cheap classifier rather than running it on every request. If rerank p99 threatens your SLO, shrink N before downgrading the reranker, because a smaller cross-encoder typically costs more quality than trimming the candidate tail.
Capacity, worked (illustrative throughput): 25k reranker tokens per query at a 50 QPS peak is 1.25M tokens a second of cross-encoder inference. If one GPU sustains 200k tokens a second on your reranker at acceptable batch latency, that is about 7 GPUs at peak before headroom and redundancy. The reranker fleet can easily cost more than the vector index. Three levers, in order of how little quality they cost:
A hosted rerank API moves the GPU problem to the vendor, but it adds a network hop and a rate limit on your critical path. Rerank failure then needs a defined degradation: serve the fused order and mark the answer as lower confidence, rather than failing the request.
When a RAG system invents an answer, the prompt rarely contained the right evidence. A model given nothing relevant still produces fluent text, and fluent text with a citation attached looks like a model defect. So retrieval is evaluated on its own, with a golden set of queries labelled with the chunks that answer them and recall@k as the headline metric. The end-to-end judge (Chapter 7) comes second. Teams that only run the end-to-end metric can't tell a reranker regression from a prompt regression, and they tune the wrong stage.
If the right chunk isn't in the top-k, generation cannot succeed — it will confabulate. Fix retrieval first; it's the cheapest, highest-leverage lever in the whole pipeline.
The golden set is where teams under-invest, and the arithmetic is unforgiving. At recall@5 ≈ 0.84, a 200-query set carries a 95% confidence interval of about ±5 points. The typical change you want to detect is a chunker tweak or a new fusion weight worth one to three points, and that is invisible at this size. You need on the order of a thousand queries before a 2-point change stands out as more than noise.
Two things make this tractable. First, compare old and new pipelines paired, on the same queries. Only the discordant queries, found by one and missed by the other, carry signal, and a McNemar-style test on those needs far fewer queries than two independent estimates. It also gives you the diff to read. Second, mine the set from production rather than writing it. Sample real queries stratified by source and query class, including identifier queries and queries from low-visibility users. Label them with the chunks a reviewer accepts, and refresh a slice every quarter, because a golden set frozen at launch slowly stops representing the traffic. LLM-generated synthetic questions are useful for coverage of new sources. They are systematically easier than real ones, because they are written from the chunk and so share its vocabulary. A synthetic-only golden set flatters dense retrieval.
Failure mode
But the common implementation, a fixed cutoff on raw cosine similarity, is unreliable. Cosine scores aren't calibrated: their distribution shifts with query length, topic density and embedding model, so 0.78 can be a strong match for one query and noise for another, and the right cutoff moves every time you change models. Put the abstain threshold on the reranker score, which is trained to judge relevance, and calibrate it on labelled positives and negatives from your golden set. Choose the operating point from the cost asymmetry: in a support bot a wrong answer usually costs more than "I'm not sure, here's a human", so accept a higher abstain rate.
When an answer is wrong, attribute it before fixing anything. Retrieval miss: the right chunk wasn't in the top-N, so fix chunking, hybrid weights or the query. Assembly miss: it was retrieved but reranked out or truncated by the budget. Generation miss: it was in the prompt and the model ignored or contradicted it. Log the candidate set and the final context for every request, and triage becomes a lookup. Without those logs every bug turns into an argument about the model. Retrieved text is also untrusted input: a poisoned document is an indirect prompt injection with your index as the delivery channel (defences in Chapter 6).
Every enterprise RAG design review eventually comes down to one question: where is the permission check, and what is it checking against? Three answers are common, and only one survives an audit. The first is prompt-level: retrieve everything and tell the model not to reveal what the user can't see. That isn't access control. It's a request, and prompt injection (Chapter 6) exists to override requests. The second is index metadata: ACL tags copied onto chunks at ingest and applied as a filter. That is necessary for performance, but it is a cache with the staleness described in 3.2. The third is query-time verification: filter by index metadata for efficiency, then check the surviving candidates against the source's permission service before anything enters the prompt. That is the one that holds up.
Where the filter runs matters as much as whether it exists. Filtering after top-N retrieval is the easy implementation, and it fails quietly for exactly the users with the narrowest access. If a user can see a fraction f of a shared index, and relevance is roughly independent of permission, the expected number of candidates that survive is N·f.
A user who can see 2% of a shared index gets roughly one candidate, and about a third of their queries get none. Nothing errors. The prompt fills with nothing, or with the abstain path, and the complaint arrives as "the bot is dumb for the new hire" rather than as an ACL bug.
Raising N to compensate works until it doesn't. Keeping 10 expected survivors at f = 0.5% needs N = 2,000, and that is before rerank. The alternatives are filtered ANN search, where the filter is applied during the graph walk (behaviour at low selectivity is covered in Chapter 4), or a physical layout that makes the filter cheap.
Shared index · ACL post-filter
one index, filter after top-N
starves low-visibility users; only safe when f ≳ 20% for nearly everyone
Shared index · filtered ANN
filter inside the graph walk
fine at moderate selectivity; degrades or falls back to brute force at very low f (Ch. 4)
Partition per tenant
tenant key → own shard/namespace
hard isolation, clean deletes; many tiny partitions waste memory and cold-start
Dedicated index per tenant
separate cluster or collection
for the few tenants big or regulated enough to justify it
Tenant boundaries belong in the physical layout (partition or index). Per-user permissions inside a tenant belong in a filter, and the authoritative check still runs against the source at query time.
Decision criteria (illustrative thresholds): put the tenant boundary in the physical layout, always. A partition key or namespace per tenant turns a tenant offboarding into dropping one partition, which is the only delete you can prove to an auditor. Keep intra-tenant permissions as filters. Promote a tenant to a dedicated index when it holds a large share of total vectors, when its query load would dominate a shared cluster, or when a contract demands physical isolation. For very many tiny tenants, per-tenant HNSW graphs waste memory and keep graphs cold. Below some size, often thousands of vectors, exact brute-force search over the tenant's partition is both faster and simpler than an ANN index.
Where caching leaks
Assembly is a knapsack problem with a latency penalty. Every retrieved token is prefilled on every request, so context size is paid in TTFT and dollars at full volume, not amortised. Illustratively, going from 5 to 15 chunks of 500 tokens adds 5k input tokens. At 1M requests a month and $3 per million tokens, that is $15k a month, plus the extra prefill time on every request. It's worth it only if answer quality measurably rises. Position matters too. Published long-context evaluations ("lost in the middle") show models use evidence at the start and end of the context more reliably than evidence buried in the middle. So put the highest-ranked chunk first, not wherever the loop happened to append it. Carry a stable source ID with every chunk so that citations can be checked mechanically: a cited ID that wasn't in the context, or a quoted span that doesn't appear in the cited chunk, is a detectable grounding failure you can alert on.
Two details separate careful assembly from naive assembly. Deduplicate near-identical chunks: templated docs, versioned copies and overlap windows otherwise spend the budget saying the same thing three times and crowd out the second-best distinct fact. And more context is not monotonically better. Past the point where recall saturates, extra chunks mostly add distractors that sit next to the right answer, plus prefill cost and latency on every request. Tune the final k on answer quality, not on retrieval recall. The two curves peak in different places.
The last conventional-advice correction: conflicting evidence is a normal state, not an edge case. The index holds last year's pricing page and this year's, the draft policy and the approved one. Similarity scores can't tell them apart, and the model will often blend them into an answer that matches neither. Resolve it in assembly, not in the prompt. Carry effective date, version and status metadata, suppress superseded versions before ranking, and when two authoritative sources genuinely disagree, surface both with citations rather than letting the model pick one silently.
Recall first
Retrieve wide
Precision
Rerank narrow
Hybrid
Dense + sparse
Cite
Trust + debugging
Design review questions
Where next