Skip to content
← All insights

AI Engineering 8 min read

Optimizing RAG (Retrieval-Augmented Generation) in Production

A practical guide to the parts of a RAG system that decide answer quality after the prototype: ingestion, chunking, hybrid retrieval, reranking, context assembly, evaluation and operations.

Diagram: documents are chunked, embedded and indexed; a question goes through hybrid retrieval, reranking to top-k, and a grounded answer with citations.
Retrieval-augmented generation in production — original TechSol diagram.

Retrieval-augmented generation (RAG) gives a language model access to your documents at question time: retrieve the most relevant passages, put them in the prompt, and ask the model to answer from them. The idea was formalised in a 2020 paper by Lewis et al., and today it is the standard way to build assistants over company knowledge.

A prototype takes an afternoon. A system people trust takes more work, because answer quality is mostly decided before the model sees the prompt — by what was ingested, how it was split, what was retrieved and in which order. This article goes through those stages one at a time.

This is an engineering guide based on published research and vendor documentation. It does not report our own benchmarks; the numbers in examples (such as 50 candidates or top 5) are illustrative starting points to evaluate, not recommendations.

Two pipelines, one index

Two pipelines sharing one index. Ingestion: sources, parse and clean, chunk, embed, index (vector plus BM25). Query: optional query rewrite, hybrid search for 50 candidates, reciprocal rank fusion, cross-encoder rerank to top 5, LLM answer with citations. Below: evaluation and monitoring of retrieval, answer quality, latency and cost.
Ingestion runs offline or on change; the query path is latency-sensitive. Both must use the same embedding model, and both are measured. Select the image to open it full size.

A production RAG system is really two systems:

  • Ingestion runs offline or whenever content changes. It turns sources into searchable chunks and keeps the index in sync.
  • Query runs on every request and is latency-sensitive. It finds the best evidence and produces an answer with citations.

They meet at the index, and they share one hard constraint: queries and documents must be embedded with the same model (and the same preprocessing). Store the embedding model’s name and version with every vector, and treat a model change as a re-index.

1. Ingestion: garbage in, confident garbage out

Most “the model hallucinated” reports trace back to ingestion. Common problems: navigation menus and footers indexed as content, tables flattened into unreadable text, scanned PDFs with no text layer, and outdated versions of a document sitting next to the current one.

  • Parse each format with a tool suited to it; keep tables as tables (or as Markdown) rather than as a stream of cells.
  • Strip boilerplate, but keep structure: titles and section headings are valuable context.
  • Attach metadata to every chunk: source, URL, section path, last-modified date, language, and who is allowed to see it.
  • Update incrementally. A content hash tells you what actually changed:
import hashlib

def content_hash(text: str) -> str:
    # Normalise whitespace so formatting-only changes don't trigger re-embedding
    normalised = " ".join(text.split())
    return hashlib.sha256(normalised.encode("utf-8")).hexdigest()

def needs_reindex(doc_id: str, text: str, stored_hashes: dict[str, str]) -> bool:
    return stored_hashes.get(doc_id) != content_hash(text)

When a document is deleted or replaced, delete its old chunks too. Stale chunks are a common source of answers that are confidently out of date.

2. Chunking: split along meaning, not just length

A chunk is the unit of retrieval. Too large, and one chunk mixes several topics, so its embedding matches nothing well and it wastes context space. Too small, and a chunk loses the context that makes it understandable.

Good defaults:

  • Split on structure first — headings, paragraphs, list items — and only then enforce a size limit.
  • Use a modest overlap between neighbouring chunks so that sentences near a boundary are not orphaned.
  • Prefix each chunk with its heading path (“Pricing › Enterprise › Billing cycle”). This helps both the embedding and the reader.
  • Treat chunk size and overlap as parameters you evaluate, not constants you copy from a tutorial.
def chunk_section(heading_path: list[str], paragraphs: list[str],
                  max_words: int = 220, overlap_words: int = 40) -> list[str]:
    """Pack whole paragraphs into chunks of up to max_words, with a word overlap.
    A single paragraph longer than max_words stays whole (split it first if needed)."""
    prefix = " › ".join(heading_path)
    chunks, current = [], []
    for para in paragraphs:
        words = para.split()
        if current and len(current) + len(words) > max_words:
            chunks.append(prefix + "\n\n" + " ".join(current))
            current = current[-overlap_words:]          # carry the tail forward
        current.extend(words)
    if current:
        chunks.append(prefix + "\n\n" + " ".join(current))
    return chunks

Word counts are only a proxy for tokens; if your context budget is tight, count tokens with the tokenizer of the model you use.

3. Retrieval: hybrid beats either half

Dense (embedding) search is good at meaning: “how do I get my money back” finds the refund policy. Keyword search such as BM25 is good at exact terms: product codes, error messages, names and acronyms that embeddings can blur. Production systems usually run both and merge the results.

The simplest robust way to merge two ranked lists is Reciprocal Rank Fusion (RRF), introduced by Cormack, Clarke and Büttcher (SIGIR 2009). Each document scores 1 / (k + rank) in every list it appears in, and the scores are summed. It needs no score normalisation, which matters because BM25 scores and cosine similarities are not on the same scale. Elasticsearch, for example, implements RRF with a default rank constant of 60.

from collections import defaultdict

def reciprocal_rank_fusion(result_lists: list[list[str]], k: int = 60) -> list[str]:
    """Merge ranked lists of document IDs. Rank starts at 1."""
    scores: dict[str, float] = defaultdict(float)
    for results in result_lists:
        for rank, doc_id in enumerate(results, start=1):
            scores[doc_id] += 1.0 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

# fused = reciprocal_rank_fusion([bm25_ids, vector_ids])[:50]

Two retrieval details that are easy to miss:

  • Apply access control in the query, as a metadata filter, not after generation. If a user cannot open a document, its chunks must never reach the prompt.
  • Approximate nearest-neighbour indexes (HNSW is the most common) trade a little recall for a lot of speed. Their parameters affect recall, so include them in evaluation.

4. Reranking: precision where it counts

First-stage retrieval is built for recall: get the right passage somewhere in the top few dozen. A reranker — typically a cross-encoder that reads the query and each candidate passage together — then reorders that short list for precision, and you keep only the top few.

Reranking costs one model call per candidate, so it adds latency. That is why it runs on a small candidate set (tens, not thousands) and why its benefit should be measured on your own questions before you pay for it.

5. Context assembly: order and budget

What you put in the prompt, and where, still matters. Liu et al. (“Lost in the Middle”, 2023) found that models used information at the beginning or end of a long context more reliably than information in the middle. Practical consequences:

  • Fewer, better passages usually beat many mediocre ones.
  • Put the strongest evidence first.
  • Remove near-duplicate chunks, which waste budget and over-weight one source.
  • Give every passage an ID and ask the model to cite IDs, so answers can link back to sources and you can check them.
  • Tell the model what to do when the evidence is insufficient — say so, rather than guess.
  • Treat retrieved text as data, not instructions: documents can contain text that looks like commands (prompt injection). Keep system instructions separate and never give retrieved content authority over tools or actions.

6. Evaluation: measure retrieval and answers separately

You cannot improve what you only judge by eye. Build a test set of real questions — ideally from logs or from the people who will use the system — with the passages that should be found and, where possible, a reference answer. Then measure the two halves separately, so you know which one to fix:

StageMetricWhat it tells you
RetrievalRecall@kIs the right passage among the top k results at all?
RetrievalMRR (mean reciprocal rank)How high does the first right passage appear?
AnswerFaithfulnessIs every claim in the answer supported by the retrieved context?
AnswerAnswer relevanceDoes the answer actually address the question?
OperationsLatency (p95) and cost per queryCan you afford to run it at the quality you measured?
A minimal evaluation set. Frameworks such as RAGAS define reference-free variants of the answer metrics.

Run the evaluation on every change that matters — chunking, embedding model, retrieval parameters, reranker, prompt — and keep the results, so that “it feels better” becomes “recall@5 went from x to y”.

7. Operations: freshness, cost and failure modes

  • Freshness. Monitor the delay between a source change and the index update. Show the source date next to citations.
  • Caching. Cache embeddings of repeated queries and, where answers are not personalised, whole responses — with a short lifetime and invalidation on re-index.
  • Observability. Log the query, the retrieved IDs and scores, the final prompt size and the answer (respecting your privacy obligations). Without the retrieved IDs, you cannot debug a wrong answer.
  • Fallbacks. Decide what happens when retrieval returns nothing relevant: a clear “I couldn’t find this” with a route to a person is better than a fluent guess.

A production checklist

  • Ingestion keeps structure and metadata, updates incrementally, and deletes stale chunks.
  • Queries and documents use the same, versioned embedding model.
  • Hybrid retrieval (keyword + vector) with a simple fusion such as RRF.
  • Access control is enforced as a retrieval filter.
  • A reranker is used only where evaluation shows it pays for its latency.
  • The prompt has few, deduplicated, cited passages, strongest first, and retrieved text is treated as data.
  • A test set measures retrieval and answer quality separately, on every significant change.
  • Freshness, latency, cost and empty-retrieval rate are monitored.

Sources