Back to Blog
    AI Engineering

    Engineering Production-Grade RAG: Hybrid Retrieval, Re-Ranking and Measurable Faithfulness

    Alexandra Chen
    Jan 5, 2025
    9 min read
    Engineering Production-Grade RAG: Hybrid Retrieval, Re-Ranking and Measurable Faithfulness

    Retrieval-augmented generation (RAG) has become the default architecture for putting large language models to work on private enterprise data. The idea is simple: instead of relying on what a model memorised during pre-training, retrieve the relevant passages from your own corpus at query time and condition the model's answer on them. The demo takes an afternoon. A system that answers correctly, cites its sources, respects access rights and stays within a latency budget takes considerably more engineering.

    This article walks through the pipeline stage by stage and focuses on the decisions that actually move answer quality.

    Why Naive RAG Fails

    The canonical tutorial pipeline — split documents into fixed 500-token chunks, embed them, take the five nearest neighbours by cosine similarity and paste them into a prompt — fails in predictable ways:

    • Vocabulary mismatch: dense embeddings capture meaning but are weak on exact identifiers such as part numbers, error codes, contract clauses or people's names.
    • Context fragmentation: a fixed-size splitter cuts tables in half and separates a heading from the paragraph that gives it meaning.
    • Ranking noise: the nearest neighbour in embedding space is often topically related but does not contain the answer.
    • Lost in the middle: Liu et al. (2023) showed that language models use information at the beginning and end of a long context far more reliably than information placed in the middle, so stuffing twenty chunks into the prompt can make answers worse.
    • Silent failure: without an evaluation harness, nobody notices that a re-index or a model upgrade has degraded quality.

    Each of these has an engineering answer.

    Stage 1: Ingestion and Structure-Aware Chunking

    Retrieval quality is bounded by the units you index. Rather than splitting on token count, split on document structure: headings, list boundaries, table rows and section numbering. A practical recipe is a recursive splitter that respects structure first and only falls back to token limits for oversized sections, producing chunks of roughly 200–400 tokens with an overlap of 10–15%.

    Two refinements have an outsized effect:

    • Contextual headers: prepend each chunk with its document title and heading path, for example "Employee Handbook › Travel › Per Diem Rates". The embedding then encodes where the text lives, not just what it says.
    • Parent–child retrieval: index small chunks for precise matching, but hand the larger parent section to the model so it sees the surrounding context.

    Metadata extracted at ingestion time — document type, effective date, department, language and the access-control list — should be stored alongside each vector. You will need it for filtering later.

    Stage 2: Embeddings and Approximate Nearest Neighbour Search

    An embedding model maps text into a vector space, typically of 384 to 3,072 dimensions, in which semantic similarity corresponds to geometric proximity. Two considerations matter more than a model's position on a public leaderboard:

    • Domain fit: a general-purpose model may place "termination" of employment and "termination" of a contract close together. Evaluating two or three candidate models on a few hundred real queries from your domain is cheap and decisive.
    • Asymmetric encoding: many modern models expect different prefixes or instructions for queries and for passages. Omitting them quietly costs several points of recall.

    Exact nearest-neighbour search is linear in corpus size, so production systems use approximate indices. The most common is HNSW (Hierarchical Navigable Small World), a multi-layer proximity graph that is searched greedily from a sparse top layer down to a dense bottom layer. Its behaviour is governed by three parameters:

    • M: the number of neighbours stored per node. Higher values improve recall and increase memory; 16–32 is a sensible range.
    • efConstruction: the size of the candidate list while building the graph. Higher values produce a better-connected graph at the cost of indexing time.
    • efSearch: the size of the candidate list at query time. This is the main recall-versus-latency dial, and it can be tuned per query without rebuilding the index.

    For very large corpora, product quantisation compresses each vector by splitting it into sub-vectors and replacing every sub-vector with the index of its nearest centroid. Memory falls by an order of magnitude at a measurable cost in recall, so a common pattern is to search the compressed index and re-score the best candidates with full-precision vectors.

    Stage 3: Hybrid Retrieval and Rank Fusion

    Lexical search with BM25 and dense vector search fail in complementary ways. BM25 excels at exact identifiers and rare terms; dense retrieval handles paraphrase and synonyms. Running both and fusing the results is one of the most reliable improvements available.

    Because the two systems produce scores on incomparable scales, the simplest robust fusion method is Reciprocal Rank Fusion (Cormack, Clarke and Büttcher, 2009). Each document receives a score equal to the sum, across retrievers, of 1 / (k + rank), where rank is its position in that retriever's list and k is a smoothing constant, conventionally 60. RRF uses only ranks, needs no score calibration and is remarkably hard to beat with more elaborate schemes.

    Access control belongs at this stage. Apply the user's permissions as a filter inside the retrieval query (pre-filtering), not after the top results have been selected (post-filtering). Post-filtering leaks information through timing and result counts, and it can return an empty set when every top candidate happens to be forbidden.

    Stage 4: Re-Ranking with Cross-Encoders

    Embedding models are bi-encoders: the query and the document are encoded independently, which is exactly what makes a pre-computed index possible. The price is that the model never sees the query and the document together. A cross-encoder feeds the concatenated pair through a transformer and outputs a single relevance score, capturing fine-grained interactions such as negation, or whether a passage actually answers the question rather than merely mentioning its subject.

    Cross-encoders are far too slow to run over a whole corpus, but they are ideal as a second stage: retrieve 50–100 candidates with the hybrid retriever, re-rank them, and pass only the best three to eight to the generator. In our experience this two-stage design is the single largest quality lever after hybrid search, and it directly mitigates the lost-in-the-middle effect by keeping the context short and dense.

    Stage 5: Grounded Generation

    The generation prompt should make the contract explicit: answer only from the supplied passages, cite the passage identifier for every claim, and say so when the passages do not contain the answer. Requesting structured output — an answer field plus a list of cited passage identifiers — makes citations machine-verifiable.

    Two further techniques are worth the effort:

    • Query rewriting: conversational follow-ups such as "and what about contractors?" are meaningless on their own. Rewrite them into standalone queries using the conversation history before retrieval.
    • Abstention thresholds: if the best re-ranker score falls below a calibrated threshold, decline to answer or route the question to a human. A confident wrong answer costs far more trust than an honest "I could not find this".

    Stage 6: Evaluation as a Discipline

    A RAG system cannot be improved if it cannot be measured, and it should be measured in two separate layers.

    Retrieval metrics are computed against a labelled set of queries and their relevant passages:

    • Recall@k: the fraction of queries for which a relevant passage appears in the top k. If the answer is never retrieved, no generator can recover it.
    • MRR (Mean Reciprocal Rank): the mean of 1 / rank of the first relevant result, rewarding systems that place the right passage first.
    • nDCG@k: a graded metric that discounts relevant results logarithmically by position, useful when relevance is not binary.

    Generation metrics are usually scored by a separate model acting as a judge and spot-checked by humans:

    • Faithfulness: is every claim in the answer supported by the retrieved context?
    • Answer relevance: does the answer address the question that was actually asked?
    • Citation precision: do the cited passages really support the sentences they are attached to?

    LLM-as-judge scoring has documented biases — towards longer answers, towards the first option in a pairwise comparison, and towards text produced by its own model family — so calibrate the judge against a few hundred human-labelled examples and track its agreement rate over time. Then run the whole suite in continuous integration on every change to the chunker, embedding model, prompt or generator. A golden set of 200–500 representative questions is enough to catch most regressions before users do.

    Stage 7: Retrieved Text Is Untrusted Input

    The most underestimated risk in enterprise RAG is indirect prompt injection. Any document in the corpus — an email, a support ticket, a supplier PDF — can contain text crafted to look like instructions to the model. Once retrieved, it sits in the same context window as your system prompt.

    There is no complete defence today, so design for containment:

    • Treat the model's output as untrusted. Never let it trigger side-effecting actions such as sending email or modifying records without deterministic authorisation checks and, for high-impact actions, explicit human confirmation.
    • Delimit retrieved content clearly in the prompt and state that it is data, not instructions. This reduces the risk but does not eliminate it.
    • Apply least privilege to tools and connectors: a model that can only read cannot be talked into writing.
    • Log the retrieved passage identifiers with every answer, so that any incident can be traced back to its source document.

    Latency and Cost Budget

    A typical interactive budget of two seconds to the first token might break down as follows: 50–100 ms for query rewriting with a small model, 20–50 ms for hybrid retrieval, 100–200 ms for cross-encoder re-ranking of 50 candidates on a GPU, and the remainder for generation. Semantic caching — reusing answers for queries whose embeddings are nearly identical and whose source documents have not changed — can eliminate a large share of repeated questions entirely, provided the cache key includes the user's permission scope.

    Conclusion

    Production RAG is less about the language model than about information retrieval, a field with decades of rigorous methodology behind it. Structure-aware chunking, hybrid retrieval with rank fusion, cross-encoder re-ranking, explicit grounding, layered evaluation and a security model that treats retrieved text as hostile are what separate a convincing demo from a system people can rely on. Teams that build the measurement harness first find that every subsequent decision becomes an experiment rather than a guess.