Back to Articles

RAG Architecture for Enterprise Data

Contents

Why RAG Instead of Fine-Tuning

Both approaches try to make a model useful against your data; they solve it in structurally different ways:

Fine-TuningRAG
Where the knowledge livesBaked into the model's weights during trainingRetrieved from an external store at query time and injected into context[1]
FreshnessFrozen at training time — stale the moment a source document changesAs current as the last time the document was re-ingested — can be near real-time
CitabilityNo — the model can't point to a source for a fact it learned during trainingYes — the retrieved passage is known, so the answer can cite it directly
Cost and effortA training run, GPU time, and a labeled dataset — expensive to redoAn ingestion pipeline and a vector store — cheaper to keep current
Best fitTeaching a model a new skill, format, or style it can't get from context aloneAnswering questions about specific, changing, citable content

For the dominant enterprise use case — "answer questions about our documents, accurately and with a source" — RAG is the practical default: it's cheaper to build, trivially kept current by re-ingesting changed documents, and produces answers you can verify against a cited passage. Fine-tuning remains the right tool for a genuinely different problem: teaching a model a behavior, format, or domain-specific reasoning pattern that context alone can't convey — and the two are not mutually exclusive; a fine-tuned model can still use RAG for the facts.

The Pipeline: Ingest, Chunk, Embed, Store, Retrieve, Generate

Every RAG system is the same six-stage pipeline, regardless of the specific tools:

  1. Ingest. Pull source documents from wherever they live — a wiki, a document store, a ticketing system — and extract clean text, preserving structure (headings, tables) where possible.
  2. Chunk. Split each document into passages small enough to embed and retrieve meaningfully, covered in detail below.
  3. Embed. Run each chunk through an embedding model, which converts the text into a vector — a point in high-dimensional space where semantically similar text ends up near other semantically similar text.
  4. Store. Persist the vectors (and the original text, and metadata like source document and access permissions) in a vector store that supports fast similarity search.
  5. Retrieve. At query time, embed the user's question with the same embedding model, and search the vector store for the nearest chunks.
  6. Generate. Inject the retrieved chunks into the model's context alongside the question, and let the model produce an answer grounded in that context.

The quality of the final answer is bounded by the weakest stage — a perfect generation step can't compensate for chunks that never contained the right passage, and a great retrieval step can't compensate for a model that ignores the context it was given. Each stage below is a real design decision, not a default to accept unexamined.

Chunking Strategy

How you split documents determines what's retrievable, and it's the decision most first RAG builds get wrong by defaulting to whatever the library ships:

  • Fixed-size chunking. Split every N tokens or characters, with some overlap between adjacent chunks so a fact sitting on a chunk boundary isn't lost entirely. Simple to implement, but blind to document structure — it can split a table or a step-by-step procedure mid-thought.
  • Semantic / recursive chunking. Split on natural boundaries — paragraphs, then sentences if a paragraph is still too long — preserving more coherent units of meaning. Better retrieval quality in most cases, at the cost of more complex chunk sizes to reason about.
  • Structure-aware chunking. Use the document's own structure — headings, sections, table boundaries — as chunk boundaries, and attach the heading path as metadata so a retrieved chunk carries its context ("Section 4.2: Refund Policy") even in isolation. This is the highest-effort, highest-quality option, and it's worth the effort for structured content like documentation and policies.

The core tradeoff to hold in mind: chunks too small lose surrounding context and produce fragmented, hard-to-use retrieval results; chunks too large dilute relevance (a long chunk about five topics matches poorly on a query about one of them) and waste context-window budget on irrelevant text. There's no universal right size — it depends on the source content's own structure, and it's worth testing a few sizes against real queries before committing.

Embeddings and Vector Store Choices

ComponentOptionsConsideration
Embedding modelHosted (OpenAI, Azure OpenAI, Cohere embeddings) or self-hosted open models (sentence-transformers[4] and similar)Hosted is simpler to operate; self-hosted keeps document content from ever leaving your environment, which matters for sensitive corpora
Vector store — "you already have Postgres"pgvector[2] as a Postgres extensionLowest operational overhead if Postgres is already in your stack; solid for small-to-mid scale before a dedicated store is justified
Dedicated vector databasesPinecone, Weaviate, Qdrant[3], MilvusPurpose-built for large-scale similarity search, with richer indexing and filtering features than a general-purpose database bolted on
Cloud-native search with vector supportAzure AI Search[5], Amazon OpenSearch, ElasticsearchUseful when you already need hybrid keyword-plus-vector search, or already run the platform for other search workloads

One rule that isn't optional: the same embedding model must be used to embed both the documents at ingest time and the queries at retrieval time — vectors from two different models don't share a meaningful distance metric, and mixing them silently degrades every search result without an obvious error to point at.

Retrieval Patterns: Beyond Naive Top-K

The default "embed the query, return the K nearest chunks" works, but three refinements consistently improve real-world retrieval quality:

  • Hybrid search. Combine vector similarity with traditional keyword search (BM25), because pure semantic search sometimes misses an exact term match — a product code, an error message — that a keyword search finds trivially. Most dedicated vector stores and search platforms support this natively.
  • Re-ranking. Retrieve a larger initial candidate set with a fast, cheap method, then re-rank the top candidates with a slower, more accurate model before choosing the final set to inject into context. This catches cases where the fast retrieval's top-K missed the truly best match by a small margin.
  • Metadata filtering. Scope retrieval by document type, date, department, or — critically, as covered in the companion article on securing LLM applications — the requesting user's access permissions. Retrieval-time access control isn't a nice-to-have; it's the mechanism that keeps a RAG system from surfacing content the asking user was never authorized to see.
  • Query rewriting. A user's literal question is sometimes a poor search query — expanding it, rephrasing it, or breaking a multi-part question into sub-queries before retrieval often finds better matches than searching the raw question text.

A Worked Example: A Minimal RAG Pipeline

A small, complete pipeline — load a document, chunk it, embed it, store it, and answer a question grounded in it. Library names and APIs shift fast in this space; treat this as the shape, and confirm current syntax against whichever framework you land on.

# Ingest + chunk: split on paragraphs, cap chunk size, keep overlap
def chunk_document(text, max_chars=800, overlap=100):
    paragraphs = text.split("\n\n")
    chunks, current = [], ""
    for p in paragraphs:
        if len(current) + len(p) > max_chars:
            chunks.append(current)
            current = current[-overlap:] + p
        else:
            current += "\n\n" + p
    if current:
        chunks.append(current)
    return chunks

# Embed + store (pgvector-backed table, conceptually)
for chunk in chunk_document(doc_text):
    vector = embedding_model.embed(chunk)
    db.execute(
        "INSERT INTO chunks (text, embedding, source_doc, acl_group) "
        "VALUES (%s, %s, %s, %s)",
        (chunk, vector, doc_id, doc_acl_group),
    )

# Retrieve + generate, scoped to the requesting user's access
def answer(question, requesting_user):
    q_vector = embedding_model.embed(question)
    results = db.execute(
        "SELECT text, source_doc FROM chunks "
        "WHERE acl_group = ANY(%s) "
        "ORDER BY embedding <-> %s LIMIT 5",
        (acl.groups_for(requesting_user), q_vector),
    )
    context = "\n\n".join(r.text for r in results)
    prompt = f"Answer using only this context:\n{context}\n\nQuestion: {question}"
    return llm.generate(prompt), [r.source_doc for r in results]

Notice the access-control filter is inside the retrieval query itself — the same principle from the companion security article, applied here as the actual implementation rather than a policy statement. And the function returns the source documents alongside the answer, which is what makes the result citable and, in practice, what lets a user judge whether to trust it.

The tooling landscape here moves quickly. Embedding model pricing and quality, vector database features, and the frameworks that wrap this pipeline (LangChain, LlamaIndex, and others) all change fast enough that a specific library version from even a few months ago may already differ from current. Treat the pipeline shape above as durable and the specific library calls as something to verify against current documentation before you build on them.

Evaluating a RAG System

"It gave a reasonable-looking answer in my quick test" is not evaluation, and it's how RAG systems ship with retrieval quality nobody actually measured. Two dimensions matter, and they fail independently:

  • Retrieval quality. Precision and recall at K — of the chunks retrieved, how many are actually relevant, and of the relevant chunks that exist, how many were found? This is measurable with a golden test set: a curated list of questions with known correct source passages, checked automatically against what retrieval actually returns.
  • Answer quality — specifically, groundedness. Does the generated answer actually stick to what the retrieved context says, or does the model quietly fill gaps with its own (unverified, uncited) knowledge? A model can produce a fluent, confident answer that's only loosely tethered to the retrieved passages — the "looks right but isn't grounded" failure mode that's hardest to catch by spot-checking, because it reads exactly like a correct answer.

Build the golden test set before you ship, not after a user reports a wrong answer — a small set of twenty to fifty real questions with known-correct sources, re-run every time the chunking strategy, embedding model, or retrieval logic changes, is the difference between "we think it's better" and "we can show it's better."

When RAG Is the Wrong Tool

RAG solves a specific problem, and reaching for it by default has real costs:

  1. Small, static content that fits in context. Long-context models can hold tens or hundreds of thousands of tokens directly. If the entire knowledge base is small and changes rarely, "just paste it all into the prompt" is simpler, has no retrieval-quality failure mode to debug, and is a legitimate architecture at small scale — don't build a vector pipeline to solve a problem that fits in a prompt.
  2. The task needs computation, not retrieval. "What's the sum of these numbers" or "look up this customer's current account balance" is better served by a tool/function call to a real system than by semantic search over documents — RAG retrieves text, it doesn't compute or query live state.
  3. The corpus is small enough that a good search engine already solves it. If users are well served by a traditional keyword search over a modest document set, the added complexity of embeddings and a vector store may not earn its keep over the answer-quality improvement it produces — measure the actual gap before building the more complex system.

Rule of Thumb: Build RAG when the corpus is large or changes often enough that "paste it all in the prompt" stops being practical, and when the answer needs to cite a real, verifiable source. Below that threshold, the simpler alternative — a long context window, a traditional search engine, or a direct tool call — usually gets you most of the value without the retrieval pipeline's own failure modes to build, tune, and evaluate.


References

  1. Lewis, P. et al. — "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks" (2020): the original RAG paper and architecture. NeurIPS, current.
  2. pgvector — "pgvector" documentation: the Postgres extension for vector similarity search. pgvector Project, current.
  3. Qdrant — "Qdrant Documentation": vector database architecture, filtering, and hybrid search. Qdrant Documentation, current.
  4. Hugging Face — "Sentence Transformers" documentation: open embedding models for semantic search. Hugging Face Documentation, current.
  5. Microsoft — "Retrieval Augmented Generation (RAG) in Azure AI Search" documentation: chunking, indexing, and hybrid retrieval patterns. Microsoft Learn, current.
← Back to Articles ← Previous: Securing LLM Applications Next: Moving from Active Directory and ConfigMgr to Entra ID and Intune →