Enterprise RAG System Design and Implementation
This article explains how to design and ship enterprise retrieval-augmented generation (RAG): when RAG fits, a four-layer architecture, corpus quality, chunking, hybrid search, query rewrite and rerank, grounded generation, workflows and agents, evaluation, security, cost, and a four-step rollout.
Retrieval-augmented generation (RAG) is not about whether a model can talk; it is about what the model is allowed to talk from. Large language models are strong at language and reasoning, but parametric knowledge goes stale and does not cover private documents, policies, API docs, or tickets. Retrieving relevant material first, then asking the model to compose an answer, is the most common and most engineerable path. It does not replace training; it adds an updatable, auditable knowledge layer at inference time.
Problem boundary and fit
Problems that fit RAG usually share three traits: the answer lives mainly in existing text or structured records; knowledge changes faster than retraining; the business needs sources, versions, or owners. Typical cases include policy Q&A, product manuals, ops troubleshooting, contract clause comparison, and support knowledge replies.
Do not send every task through retrieval. Strict numerical computation, strong transactional consistency, or real-time control belong in dedicated systems; retrieval may only supply explanatory context. Creative writing and open brainstorming need not be forced onto a knowledge base, or the model will be boxed into irrelevant snippets. Drawing the boundary first avoids using complex retrieval to paper over a wrong product definition.
Overall architecture
A usable RAG pipeline splits into offline and online stages.
Offline work turns raw sources into searchable assets: ingest, clean, chunk, embed, build keyword and metadata indexes, and record document versions. Online work takes the user question, rewrites the query and detects intent, runs multi-path retrieval, reranks, packs context, calls the generator, then verifies citations and applies safety filters.
Think of four layers: knowledge, retrieval, generation, and governance. Knowledge answers “what exists”; retrieval answers “can we find it”; generation answers “can we say it clearly without overstepping”; governance answers “can we observe, roll back, and assign accountability.” Missing any layer shows up later as occasional hallucination or untraceable failures.
A sketch of responsibilities, not a vendor API:
query = normalize(user_input)queries = rewrite(query) # synonyms, coreferencecandidates = hybrid_search(queries, filters)ranked = rerank(query, candidates)context = pack(ranked, token_budget, citations)answer = generate(system_policy, query, context)return verify_citations(answer, context)
Knowledge prep: quality before algorithms
Retrieval quality is capped by the corpus. Before indexing, normalize encoding, strip headers, footers, and navigation noise, OCR scans, and keep heading hierarchy and table structure. If tables are flattened to plain text, row–column relations are lost and even a strong embedding model cannot restore them.
Each chunk should carry at least: source, update time, effective version, business domain, classification, and language. These are online filters, not decoration. Without classification, retrieval can inject passages the current user must not see. Without version, the model may cite both retired and current clauses.
Incremental updates are more common than full rebuilds. After a document change, locate affected chunks and reindex them instead of wiping the store daily. Keep replayable originals so you can check that cited sentences truly come from the source.
Chunking
Chunking trades semantic completeness against retrieval grain. Chunks that are too large add noise and fill the context window; chunks that are too small split definitions from conditions so a hit cannot stand alone.
In practice, split first by heading, then by fixed length with overlap so sentences are not cut at boundaries. For policies, use a clause as the unit; for API docs, one endpoint plus parameters and error codes; for long narrative, a paragraph plus its heading path. Keeping parent titles in the chunk makes “which chapter this belongs to” much clearer.
Parent–child indexing is a solid pattern: small chunks for recall, then the larger parent block for generation—precise location plus full context.
Representation and indexes
Embeddings handle paraphrased questions; keyword indexes handle proper nouns, error codes, model numbers, and exact phrases. They complement each other; either path alone will miss recalls. Hybrid search typically recalls a vector set and a keyword set, dedupes by document, then reranks.
Choose embedding models for corpus language, text length, and update cost—not public leaderboards alone. Switching embeddings means re-encoding the whole corpus; treat it as a version upgrade, not a daily knob. Indexes must filter on metadata at recall time (or immediately after) so you do not fetch large volumes of unauthorized documents only to drop them.
Similarity is only a candidate signal. The same question can map to different documents by domain. User identity, workspace, time, and product line must be in the filters.
Query understanding and reranking
User questions are often vague, anaphoric, or colloquial. Rewrite can restore subjects, split compound questions, and produce several search formulations. Rewrite is itself a model call: bound latency, length, and safety so stray intents do not leak into retrieval.
After splitting multi-part questions, search separately then merge; otherwise two entities in one query interfere. Rerank with a stronger cross-encoder (or equivalent) scoring query–passage pairs; that tracks relevance better than vector distance alone. Do not feed too many candidates to rerank—latency and cost rise while gains diminish.
Context packing and generation constraints
Before generation, pick passages within the token budget: prefer high relevance, dedupe, cover multiple sources, and attach citation IDs. The prompt should require: answer only from the given material; say you do not know if material is insufficient; do not present speculation as fact; citations must match IDs.
The system prompt should also encode business rules—for example, time is the document effective date; amounts and legal conclusions need human review. Those rules beat vague “be more accurate” instructions. After generation, run a light check: citation IDs exist, quoted sentences appear in the corresponding passage, no numbers invented outside the material. On failure, degrade to returning retrieved passages or asking the user for more constraints—not a fluent but ungrounded paragraph.
Workflows and agents
RAG is a capability, not a full application. Many tasks need multiple steps: decide whether to retrieve, pick a corpus, then call calculators or business systems, then summarize. Fixed steps fit workflows; branching and tool choice fit agents.
Expose retrieval as a reusable tool rather than baking prompts into one chat. Tool input should include query, filters, and a result cap; output should include passages, scores, source, and version. Human-in-the-loop nodes suit high-risk answers—common enterprise cases are contract and finance wording. Agents may decide to retrieve again, but round limits are required to avoid loops.
Model management should be independent of retrieval: smaller models for rewrite, stronger models for final generation, embeddings versioned separately. Routing, timeouts, retries, and fallbacks should be configurable; if generation fails, at least return what was retrieved.
Evaluation, observability, and iteration
Without an eval set you cannot tell whether a change helped. Eval questions should come from real traffic and be labeled with the documents that should support the answer—not only a “gold” paragraph. Metrics should include: whether recall hit the supporting docs, whether they ranked high, whether the answer is supported, whether refusal is correct, and whether citations can be traced.
Online, log query, filters, recall list, passages used, and user feedback, with redaction and access control. Archive failures by type: broken chunks, missing metadata, uncovered synonyms, stale docs, prompt overreach. Each type needs a different fix; do not always raise Top-K.
Version knowledge, embeddings, prompts, and rerankers together so an incident can answer “which policy version and which index.”
Security and cost
Authorization must apply in retrieval, not only by hiding UI entry points. For multi-tenant setups, isolate indexes or enforce filters, and test for privilege escalation regularly. Prompt injection can masquerade as document text telling the model to ignore rules. Defenses include separating documents from instructions, limiting tools documents can trigger, and policy-checking outputs.
Cost is driven by embedding, rerank, and generation. Control it with caches for identical questions, skipping rerank on low-value traffic, and compressing duplicate passages. Allocate latency budgets per stage so generation does not wait on slow retrieval. Object storage holds originals; the search engine holds chunks and vectors; logs and monitors track failure rate, empty recall, and citation failures—generic engineering, not a single product shape.
Rollout order
Ship in four steps rather than all optimizations at once. First, a clean small corpus, hybrid keyword-plus-vector search, and mandatory citations. Second, metadata filters, versions, and permissions. Third, an eval set, then rerank, parent–child indexes, and query rewrite. Fourth, wrap retrieval as a tool, plug into workflows or agents, and add observability and fallbacks.
RAG’s value is answers that are updatable, traceable, and governable. Models and documents both change; keeping knowledge, retrieval, generation, and evaluation separate means you do not rebuild the system every time the model changes. Teams that chase fluent demos and skip chunking, permissions, and citation checks usually pay more in production rework than they would have spent doing those three things well from the start.
