Retrieval-augmented generation
Read first: Search indexes, Serving LLMs
Retrieval-augmented generation chunks documents, embeds the chunks, retrieves a few, optionally reranks them, and asks the model to answer from those passages. The vector store is a derived index, not the source of truth, and it lags the documents. Score whether the right passage showed up separately from whether the sentence followed from the passages you actually sent.
The model does not know your runbooks. It knows what you put in front of it on this request, plus whatever was in its weights. Retrieval-augmented generation is how you put the right paragraphs in front of it. When the answer is wrong, the paragraph was missing, the paragraph was stale, or the model did not use the paragraph. Those are different bugs, and a single “the bot was wrong” ticket will not tell you which one you have.
Core concepts
Keep the source of truth outside the index. The document lives in a database or in object storage. The pipeline that follows is a derived view of those bytes, in this order.
Chunk. Cut each document into the units you are willing to embed and to show the model. A chunk should hold one thought the user might need in full. Split a procedure in the middle and the thought is gone even if both halves are stored. Leave a whole manual in one chunk and the embedding describes a mush of topics, so “near” stops meaning “about this question.”
Embed. Turn each chunk into a vector, a point that stands in for the text. Questions land near a chunk when the embedding model treats them as similar, including when the words do not match. That is the reason to embed. Exact identifiers still want an inverted index: order ids, error codes, function names. Search indexes are that structure, term to postings, and they lag writes because indexing is asynchronous. Many systems keep both, lexical for the rare token and vector for the paraphrase. There is no universal formula for mixing the two scores. You measure which one placed the right id.
Retrieve. Take a few nearest chunks for the question. How many is a product choice. A wider net raises the chance the right passage is in the set. It also lengthens the prompt. Serving LLMs is where that length shows up: prefill work and KV cache both grow with the prompt, and a prompt that does not fit the batch does not get to skip the line.
Rerank. Optionally run a slower, more careful scorer over those candidates and keep the best few. You spend a hop on the user path so the generator sees evidence instead of a neighborhood. Skip the rerank and the model reads whatever happened to be near, including neighbors that share vocabulary and are not evidence for the claim.
Generate. Ask the model to answer from the passages you kept. It can ignore them. The weights have their own answer, and a sentence in the prompt that says “use only the context” is a wish. A check is code: the answer must point at a passage id you actually sent, and a claim with no supporting passage is dropped or refused. The check runs after generation. It is not a paragraph in the system prompt.
Four failures cover almost every bad ticket.
- Bad chunks. The boundary cut the warning off the command, or glued two policies into one vector. Retrieval is “working.” The evidence is mutilated.
- Stale index. The source changed. The embedding still describes yesterday. Indexing is asynchronous, so this lag is normal unless you built something tighter. The model cites the old passage faithfully.
- Neighbors that are not evidence. The point is nearby in vector space and the text does not answer the question, or it answers it for a different tenant. Nearness is not proof and it is not authorization.
- The model ignores the passages. The right text was in the prompt. The sentence contradicts it or adds a fact from the weights.
Evaluate the two stages separately. Retrieval asks: did the known-good passage id show up in the set you kept? You can score that without judging prose. The answer asks: given the passages that were actually present, does the sentence follow from them and stop there? A right sentence with the wrong passages is a model that got lucky in its weights. It will also be lucky when the weights and the corpus disagree. A wrong sentence with the right passages is a generation failure. Editing the prompt does not insert a passage that retrieval never fetched.
The vector store is not the source of truth. You can rebuild it by chunking and embedding the documents again. You cannot rebuild a deleted policy from a vector. If the index and the source disagree, the source wins and the index is stale or corrupt. Deletes have to reach the index, or the model keeps quoting a ghost. Access control has to reach the query, or a neighbor from another tenant shows up because it was nearby.
flowchart LR
source[Source document] --> chunk[Chunk]
chunk --> embed[Embed]
embed --> index[Vector index]
question[Question] --> retrieve[Retrieve]
index --> retrieve
retrieve --> rerank[Rerank]
rerank --> generate[Generate]
The diagram is also the eval cut. Everything up to rerank is “did the right id survive.” Generate is “did the sentence follow.” A metric that only grades the final paragraph makes every upstream bug look like a prompt bug.
A worked example
You are building the retrieval path for an internal agent that answers from runbooks. The agent loop comes later. This page is the part that decides which paragraphs the model is allowed to see.
Assumptions:
- 8,000 runbooks, and you chunk each into about 5 pieces. Both numbers are assumptions about your corpus, not a rule.
- 1,000,000 questions a day.
- You retrieve 20 chunks and rerank down to 4. That is a choice you will measure.
- A passage you send to the model is about 500 tokens. Assumption, so you can see the prefill, not a property of a named embedding model.
- The indexer runs every 15 minutes. Assumption about your job, and the staleness window that comes with it.
1 day = 86,400 s
shortcut ≈ 100,000 s
1,000,000 questions / 86,400 ≈ 11.6/s ≈ 12 questions/s
assumption: 8,000 runbooks × 5 chunks = 40,000 chunks in the index
assumption: keep 4 passages × 500 tokens = 2,000 tokens of evidence
those 2,000 tokens are prefill on every question
they are also KV cache that has to fit beside the resident batch
Twelve questions a second is a small serving rate. The failure mode is not QPS. It is sending 2,000 tokens of the wrong text, or 2,000 tokens that no longer match the page a human has open.
A bad chunk. A volume runbook says: take a snapshot, then delete the volume, and deleting first destroys the only copy. The splitter cuts after “delete the volume.” The retrieved chunk is an imperative with no warning. The warning is a different vector and did not make the top 4. The model tells the user to delete. The source document was correct. The chunker destroyed the thought, and a prompt that says “be careful” cannot restore a sentence you did not retrieve. Fix the boundaries so a procedure and its precondition land in the same chunk, then re-score retrieval. Overlap is the other knob: too little and a sentence that crosses the cut is in neither chunk intact; too much and you store near-duplicate points that crowd the top 4 with three copies of one paragraph. Pick a width, label it as an assumption, and check whether a full procedure still fits inside one chunk.
The same cut on a policy sentence is worse because the two halves contradict each other. The travel policy says employees may not expense alcohol, except when a client is present and the amount is under the cap in the travel table. A fixed window ends after “alcohol,” so one chunk is the ban and the next chunk opens with “except.” Retrieval returns the ban. The model forbids the client dinner. The source allowed it, under the cap, and the table that states the cap never traveled with the sentence. A chunk that starts with “except” is not a thought. Chunk on the sentence, and keep the table with the sentence that points at it.
A stale index. At 10:00 the on-call shortens the refund window in the source from 30 days to 14. The human-facing page says 14. Your indexer runs on a 15-minute cadence, so until 10:15 the vector still says 30. A question at 10:05 retrieves the old chunk. The model cites it. Your “must name a passage id” check passes, because the citation is faithful to the index and wrong about the source. Freshness is a retrieval property. Put the expected passage text, not just the id, in the eval, and include the update time.
Closing that window means the index update has to be tied to the source write. A dual write, source then vector, fails open: the source commits, the embed call errors, and you are stale until someone notices. The transactional outbox shape fits. Write the document and an outbox row in one database transaction. A worker reads the outbox, embeds, and upserts. The vector store is still not the source of truth. You have only made the lag visible and retryable. If a reader cannot tolerate those minutes, read that one hot document from the source on the request path and use the index for the long tail. You pay a lookup. You stop quoting a policy that has already changed.
Neighbors that are not evidence. A question about rotating a signing key retrieves a chunk that mentions keys and rotation in a marketing post, plus a chunk from another team that is genuinely about rotation and is not this asker’s runbook. Reranking may demote the marketing post. It will not invent an access check. The tenant or the ACL has to be in the query before you treat a neighbor as evidence. Vector search is the page for how a filter interacts with the index. Here, the rule is simpler: if the passage would not be legal to paste into the ticket, it is not legal to paste into the prompt.
The model ignores the passages. The four chunks say 14 days. The model answers 90, because a generic policy in the weights said 90. The passage ids are right, so a retrieval score is green and the user-facing answer is wrong. The fix is the post-check, or a generation eval on frozen passages, not a wider k.
Score a labeled set before you touch the prompt. Assume 200 questions where a person marked the chunk id that must appear.
retrieval score: of 200, how many have the marked id in the 4 you kept
answer score: only on the questions where the id was present,
did the sentence follow from those passages and add nothing else
if 40 of 200 retrieve the marked id, prompt edits are not the next change
the chunk, the embed, the filter, or the stale job is
Forty is not a target. It is an illustration of the cut. Publish the two counts. Do not average them into one health number. A prompt change that lifts the answer score while retrieval stays at 40 made the model more articulate about the wrong pages.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Small chunks | A hit is about one fact, so the prompt stays specific | Procedures split, and the warning lives in a chunk you did not rank |
| Large chunks | A procedure stays together | The vector averages several topics, and nearness gets mushy |
| Rerank a wide candidate set | Better evidence in the four passages you keep | Another hop on the path the user waits for, and another failure point |
| Lexical index beside vectors | Exact ids and error codes still hit | Two indexes to keep fresh, and no free formula for merging them |
| Outbox from the source write | Staleness is bounded by a worker you can see | The index still lags, and the vector store is still derived |
| Answer only from cited passages | Invented facts get dropped | You refuse questions the corpus almost answers |
| Rebuild the index from source | Recovery when the vectors drift | Compute, and a window where you must not serve a half-built index |
Sending 20 passages straight to the model looks simpler than reranking to 4. You pay for it in prefill, in cache, and in the chance a distracting neighbor outshouts the real procedure. Reranking costs latency. Measure that hop against the time-to-first-token budget before you put it on the user path. If it does not fit, rerank offline is not a consolation for an interactive agent. Cut k, or move the agent off the interactive budget.
Pitfalls
- Treating the vector store as the system of record. It is rebuildable. The documents are not. A restore plan that starts from the index has no plan.
- One eval on the final sentence. A lucky weight and a bad retrieval look like success. A good retrieval and a model that ignored it look like a prompt problem. Split the score.
- Shipping a citation check and calling freshness done. A citation of a stale chunk passes the check and contradicts the page the user is looking at.
- Dual-writing the source and the vector with no outbox. The source commits, the embed fails, and the index quotes the previous policy until a human notices.
- Forgetting deletes. The runbook is gone, the point remains, and the model quotes a ghost with confidence.
- Stuffing every neighbor into the prompt. The right passage is “in there” and the prefill no longer fits the batch, so the request waits or fails for a serving reason that looks like a model outage.
- Filtering tenants in the application after you already took the top hit. The first neighbor can be the wrong tenant’s text. If that later filter fails open, you have pasted it into the prompt.
- Editing the prompt because one dramatic question failed, without counting how often the marked passage was absent.
In the interview
Say the pipeline in order, and say where truth lives. Documents are truth. Chunk, embed, retrieve, rerank, generate. The vector store is a lagging index you can rebuild. Then say you evaluate retrieval and the answer separately, and name the four failures: split chunks, stale index, neighbors that are not evidence, model ignores the passages.
Skip the brand of vector database and any recall percentage you did not measure. Skip a lecture on the embedding architecture.
The question that usually follows is “the document changed a minute ago” or “the answer cited something wrong.” Walk the stale path: asynchronous index, outbox if you need a bounded lag, source wins. If they push on a wrong answer with the right pages present, say you would change generation or the post-check, and you would not rechunk a pipeline that already retrieved the id.
Check yourself
A labeled question retrieves the marked passage, and the model states a refund window that appears in none of the passages. Which stage failed, and what should you not change first?
Generation failed. The model ignored the passages or added a fact from its weights. Retrieval did its job. Rechunking or swapping the vector index does not fix a sentence that contradicted text you already sent. Change the post-check or the generator, and re-score the answer on frozen passages.
The same question is answered correctly, but the marked passage id was not in the retrieved set. Why is that not a retrieval pass?
The sentence came from the weights, not from the corpus. The day the weights and the source disagree, the same path will be confidently wrong, and a citation check will have nothing honest to cite. Count it as a retrieval miss. Do not let a lucky answer greenwash the index.
Your indexer runs every 15 minutes. A policy page is updated at 10:00 and a user asks at 10:05. The model cites a passage. Why can that citation still be wrong?
The index still holds the previous chunk until the job runs. The citation is faithful to the vector store and stale relative to the source. The vector store is not the source of truth. The page the human updated is. A check that only verifies “this id was retrieved” cannot see that the bytes behind the id are the old policy.
A runbook says to snapshot a volume and then delete it, and that deleting first destroys the copy. Users are being told only to delete. Where is the bug?
The chunk boundary split the warning from the command, and retrieval returned the imperative alone. The source document was whole. Widen or retarget the chunk so the precondition and the action stay together, then re-score whether the marked passage id shows up. A sterner prompt cannot quote a sentence you never retrieved.
You keep 4 passages of about 500 tokens on a path that already fills the model batch. What serving failure does a fatter prompt turn into?
Four times 500 is about 2,000 tokens of extra prefill, and that many extra tokens of KV cache, under the assumption that a passage is 500 tokens. If the device does not have that room beside the resident batch, the request does not fit. Time to first token becomes queue time, or the server refuses. Cutting passages is an admission decision as well as a relevance decision.
Based on: Retrieval-augmented generation; Inverted indexes and asynchronous indexing; Transactional outbox.