Justine Acosta
JUSTINE ACOSTA · GMT+8 ·
All articles
BLOG / ARTICLE

Retrieval That Survives Production

RAG demos are easy to build and hard to keep honest. Most of what separates the two is ordinary information retrieval, not model work.

6 min readAIRAGRetrieval

A retrieval prototype comes together in an afternoon. Embed the documents, drop them in a vector store, embed the question, take the top five, hand them to a model. It answers questions about your data and it feels like magic.

Then you point it at the real corpus and the answers get vague, or confidently wrong, or cite the right document and misread it. The instinct is to reach for a better model or a longer prompt. Usually the problem is upstream of both.

Retrieval is a search problem first

The generation step can only work with what you hand it. If the right passage isn't in the context, no amount of prompt engineering recovers it: the model will produce something plausible from what it does have, which is the worst possible failure because it looks like an answer.

So the useful framing is: this is an information retrieval system with a language model on the end. Decades of search practice apply, and most production wins come from applying them rather than from anything model-specific.

Chunk on structure, not character count

The default is splitting every N tokens with some overlap, and it's the single biggest source of quality loss. Fixed-size splits cut sentences in half, separate a heading from the paragraph it introduces, and split tables from the rows that give them meaning.

Split on what the document already tells you about itself:

  • Markdown and HTML have headings. Use them, and keep a section with its heading.
  • PDFs have page and section structure worth extracting before you touch the text.
  • Code has functions and classes.
  • Transcripts have speaker turns and timestamps.

Then carry context down into the chunk. A section about refund windows inside a document about billing policy should say so in its own text:

Document: Billing Policy 2026
Section: Refund windows
---
Refunds are processed within 14 days of the original charge...

That prefix costs a handful of tokens and dramatically improves both retrieval and the model's ability to attribute the passage correctly. Without it, a chunk that opens with "Refunds are processed within 14 days" matches a hundred other policy documents equally well.

Vector search finds things that mean the same thing. It is genuinely poor at finding things that are the same thing.

Someone searching for an order number, an error code, a product SKU, or a surname needs exact matching, and embeddings will happily return a dozen semantically similar passages containing none of those strings. Keyword search handles it trivially.

Run both and merge. Reciprocal rank fusion is the standard approach and it's about fifteen lines:

function fuse(rankings: string[][], k = 60) {
  const scores = new Map<string, number>();
  for (const ranking of rankings) {
    ranking.forEach((id, i) => {
      scores.set(id, (scores.get(id) ?? 0) + 1 / (k + i + 1));
    });
  }
  return [...scores.entries()].sort((a, b) => b[1] - a[1]).map(([id]) => id);
}

No tuning, no weights to argue about, and it reliably beats either input on its own. If you make one change to a struggling retrieval system, make it this one.

Filter before you search, never after

This is the part with security consequences, so it's worth being blunt about the ordering.

Every retrieval query needs the tenant, workspace, and permission constraints applied inside the search, not as a filter over the results. Retrieving the top fifty and then removing what the user isn't allowed to see produces two problems: you get fewer results than you asked for, and the day someone forgets the post-filter, private content is summarized into an answer.

Most vector stores support metadata filtering as part of the query. Use it, and make the permission scope a required argument to your retrieval function so it can't be omitted by accident:

async function retrieve(query: string, scope: { orgId: string; userId: string }) {
  // scope is not optional - there is no unscoped path
}

Rerank when precision matters

Vector search optimizes for recall across a large corpus. It's fast and approximate, and the ordering within the top results is often not great.

A cross-encoder reranker takes the top 30-50 candidates and scores each one against the query directly. It's slower per item, which is why it runs on a shortlist rather than the whole index, and it usually improves precision more than swapping in a larger generation model would.

The pattern: retrieve broadly with hybrid search, rerank down to the handful you actually pass to the model. Retrieving 50 and passing 5 beats retrieving 5.

Measure retrieval on its own

When an answer is wrong, the first question is whether the right passage was even retrieved. You can only answer that if you measure the two stages separately.

Build a small set of questions paired with the document that should answer them: thirty is enough to be useful. Then track recall at k: how often the correct passage appears in the top k results. This number is independent of the model, independent of the prompt, and it tells you immediately which half of the system to work on.

Teams that skip this end up tuning prompts to compensate for a chunking bug, which works just well enough to hide the problem and not well enough to fix it.

Decide what happens when nothing matches

Sometimes the corpus genuinely doesn't contain the answer. The system needs a defined behaviour for that, or it will invent one.

Two things help. Set a relevance floor and treat results below it as no results, rather than passing weak matches along because they were the best available. And instruct the model explicitly that declining is an acceptable outcome: that answering from the provided context only, and saying when the context is insufficient, is what you want.

"I don't have information about that in these documents" is a correct answer, and a system that can't produce it will produce a wrong one instead.

Where I'd start

If you have a retrieval system that isn't performing, in this order:

  1. Add keyword search alongside the vector search and fuse the rankings.
  2. Rechunk on document structure, with heading context in each chunk.
  3. Build the thirty-question set and measure recall at k.
  4. Add a reranker over a wider candidate set.
  5. Only then look at the prompt or the model.

The first two usually account for most of the gap, and neither requires changing anything about how you're calling the model.