
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.
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:
Each of these has an engineering answer.
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:
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.
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:
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:
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.
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.
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.
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:
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:
Generation metrics are usually scored by a separate model acting as a judge and spot-checked by humans:
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.
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:
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.
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.

What really happens between a satellite signal and the dot on a phone screen, and how sensor fusion, probabilistic map matching and uncertainty-aware geofencing turn noisy fixes into reliable automated decisions.

A technical look at the attack classes that actually breach modern applications — broken object-level authorisation, token replay, SSRF and supply-chain compromise — and the controls that stop them.