RAG Production Architecture: Demo vs. Real System

RAG Production Architecture: Demo vs. Real System

What happens when the chatbot that wowed everyone in the pilot starts returning stale answers, leaking a document from another department, or confidently inventing a policy that never existed? That moment, more than any model upgrade, is where retrieval-augmented generation (RAG) stops being a prototype and becomes an architecture problem. The demo worked because someone pasted three clean PDFs into a prompt. Production is different: thousands of documents, dozens of users with different permissions, content that changes hourly, and an audit trail someone will eventually demand.

This article walks through the architecture decisions that actually matter when RAG goes live, from ingestion and chunking to hybrid retrieval, reranking, evaluation, and security.

Why the original RAG paper is not a production plan

Retrieval-augmented generation was introduced in a 2020 paper by Lewis and colleagues, which paired a dense retriever with a sequence-to-sequence generator so the model could ground its output in retrieved passages rather than rely on parameters alone. Readers who want the formal definition can read the original RAG paper by Lewis et al., but the important point for builders is this: the paper describes a research setup, not an operational system. It says nothing about incremental re-indexing, multi-tenant permission filters, cost controls, or what to do when the embedding model is deprecated.

Production RAG is best understood as a pipeline with five stages, each of which can fail independently:

  • Ingestion — pulling content from source systems and normalizing it.

  • Indexing — chunking, embedding, and storing vectors alongside metadata.

  • Retrieval — finding candidate passages for a query.

  • Generation — composing an answer grounded in those passages.

  • Evaluation and monitoring — proving the whole thing still works next month.

Most failed RAG projects fail at stage two or stage five, not stage four. The model is rarely the weak link.

Ingestion and chunking: where quiet failures begin

Ingestion and chunking: where quiet failures begin

Chunking is the decision that gets the least attention and causes the most damage. Splitting a document into fixed-size chunks with overlap is the common default, but the right size depends on the embedding model and the kinds of questions users ask. There is no consensus standard, so treat any specific number you read online as a heuristic to test, not a rule to copy.

What works in practice is chunking on structure first. A support article, a contract clause, and a code file have different natural boundaries, and splitting mid-table or mid-clause produces fragments that retrieve badly and read worse. Practical habits that pay off:

  • Preserve headings and section titles in the chunk text or metadata, because they carry meaning the body loses.

  • Keep tables intact where possible; a table split across three chunks is usually useless.

  • Store source, document ID, version, and access-control metadata with every chunk. Retrofitting permissions later means re-indexing everything.

  • Version your embeddings. Vectors from different embedding models are not comparable, so changing the model requires re-embedding the entire corpus. Plan for that migration before you need it.

Freshness is the other ingestion trap. Users notice staleness before they notice almost anything else. Incremental re-indexing, driven by change events from source systems rather than nightly full rebuilds, keeps answers current without rebuilding the world each night.

The infrastructure underneath all this deserves its own design pass. Vector stores, embedding services, and orchestration layers have very different scaling behavior from ordinary web services, a theme covered in this overview of cloud infrastructure and architecture.

Retrieval: hybrid search and the reranking stage

Pure vector search sounds elegant and disappoints in practice. Dense embeddings capture meaning but stumble on exact identifiers, product codes, and rare names. Lexical search like BM25 nails those and misses paraphrases. That is why most mature systems run hybrid retrieval: both methods in parallel, then fuse the ranked lists, often with reciprocal rank fusion, which was formalized by Cormack and colleagues at SIGIR in 2009.

The second standard stage is reranking. A cross-encoder model scores the top candidates against the query directly, which is slower per pair but far more accurate than comparing vectors. The BEIR benchmark from Thakur and colleagues showed that cross-encoder reranking improves zero-shot retrieval across datasets, which is why the pattern of retrieve-wide-then-rerank-narrow is so common.

Context ordering matters too. The 2023 study known as Lost in the Middle by Liu et al. found that language models use information at the beginning and end of a long context more reliably than material buried in the middle. In practice, that means the highest-ranked passages should sit at the edges of the prompt, and stuffing twenty chunks into the context usually hurts more than it helps.

How the retrieval and generation stages are wired together, including batching, caching, and latency budgets, is really a question of AI inference architecture, and it deserves the same rigor as the model choice.

Generation: grounding, abstention, and honest answers

The generation stage has one job: answer from the retrieved context, and say so when the context does not contain the answer. Systems typically instruct the model to use only the provided passages and to abstain otherwise. That is a prompt-level control, not a guarantee. Its effectiveness varies by model and domain, so it must be tested rather than assumed.

Three habits separate serious implementations from hopeful ones:

  • Cite sources inline. Requiring the model to attach a document reference to each claim makes hallucination visible and gives users a way to verify.

  • Design the abstention path. A clear “I could not find this in the knowledge base” with a link to human support beats a confident wrong answer every time.

  • Keep prompts versioned. When answer quality shifts, you need to know which prompt, model, and index version produced the change.

Teams often blur product and platform responsibilities here, debating whether prompt templates belong to the application or the retrieval service. A useful framing for that split appears in this piece on distinguishing AI product and platform roles, which helps avoid the classic outcome where nobody owns the prompt layer.

Evaluation: measuring retrieval and generation separately

A RAG system has two failure surfaces, and a single end-to-end score hides which one broke. Retrieval metrics include recall@k (did the right passage appear in the top k?), mean reciprocal rank, and nDCG. Generation metrics include faithfulness or groundedness (is every claim supported by the retrieved context?) and answer relevance (does the answer address the question?).

The RAGAS framework, proposed by Es and colleagues in 2023, offers reference-free metrics for exactly this purpose, which matters because writing gold-standard answers for every question does not scale. A workable evaluation routine looks like this: (NIST AI Risk Management Framework)

  • Build a fixed evaluation set of real user questions with known correct source documents.

  • Score retrieval separately from generation on every run.

  • Add regression cases for every production incident.

  • Re-run the suite whenever the embedding model, chunker, prompt, or generator changes.

In production, monitor user behavior as well as model output. Thumbs-down rates, rephrased follow-up questions, and sessions that end in a support ticket are retrieval signals in disguise.

Security: retrieved documents are untrusted input

Here is the uncomfortable truth about RAG security: every retrieved document is input the model will follow. Indirect prompt injection, where malicious instructions are hidden inside a document that later gets retrieved, is listed as LLM01 in the OWASP Top 10 for LLM Applications entry on prompt injection, and RAG pipelines are a natural delivery route.

The second risk is simpler and more common: access control. If retrieval does not filter documents by the requesting user’s permissions at query time, RAG will happily summarize a salary spreadsheet for someone who should never see it. Document-level ACL filtering belongs in the retrieval query itself, not in a post-filter applied to the generated answer. Multi-tenant systems need tenant isolation at the index level, and audit logs should record which documents were retrieved for which answer.

A short checklist that prevents most incidents:

Risk Control
Cross-tenant leakage Tenant-scoped indexes or mandatory metadata filters
Permission bypass ACL filtering at query time, tested with negative cases
Indirect prompt injection Treat retrieved text as data, strip instructions, constrain tool use
Data exfiltration via output Output filtering and no raw document dumps

Operating RAG over time

The unglamorous truth is that RAG systems decay. Source documents change, embedding models get deprecated, user questions drift, and the evaluation set goes stale. Teams that keep RAG healthy treat it as a product with an owner, a roadmap, and a dashboard, not a one-time integration.

Cost and latency deserve explicit budgets too. Reranking every candidate is expensive; retrieving fifty chunks and reranking all of them on every query will show up on the bill. Caching frequent queries, tuning top-k per use case, and routing simple questions to cheaper paths are standard levers. The broader discipline of running these systems, from model serving to observability, is what enterprise AI systems and architecture covers in depth, and it is worth reading before scaling a pilot.

Finally, decide early how the system will be governed. Who approves a new document source? Who reviews flagged answers? What is the rollback plan when a bad index version ships? These are organizational questions, but they determine whether the architecture survives contact with real users.

Conclusion

RAG production architecture is less about picking a model and more about the plumbing around it: structured chunking, hybrid retrieval with reranking, grounded generation with honest abstention, separate evaluation of retrieval and generation, and security that treats every retrieved document as untrusted. The 2020 paper gave builders a powerful idea; the work of turning that idea into a dependable system is entirely architectural. Teams that plan for re-indexing, permissions, and evaluation from day one spend their time improving answers. Teams that skip those steps spend their time explaining incidents.

What is the difference between RAG and fine-tuning?

RAG retrieves external documents at query time and grounds the answer in them, so knowledge can change without retraining the model. Fine-tuning adjusts the model’s weights to change behavior or style. RAG is usually the better fit for factual, frequently changing content, while fine-tuning suits tone, format, and task-specific behavior.

How large should chunks be in a RAG system?

There is no universal answer. Chunk size depends on the embedding model, the document structure, and the kinds of questions users ask. Splitting on natural boundaries such as headings and clauses, then testing retrieval quality on a real question set, works better than copying a fixed number from a blog post.

Why does RAG need reranking if vector search already works?

Vector search is fast but approximate, and it struggles with exact identifiers and rare terms. A cross-encoder reranker scores the top candidates against the query directly, which is slower per pair but more accurate. Retrieving a wider candidate set and reranking it down to a handful is a reliable way to improve answer quality.

How do you evaluate a RAG system?

Measure retrieval and generation separately. Retrieval uses recall@k, mean reciprocal rank, and nDCG against known correct documents. Generation uses faithfulness and answer relevance, which reference-free frameworks such as RAGAS can score. Re-run the suite whenever the index, embedding model, prompt, or generator changes. (Retrieval-augmented generation (Wikipedia))

Can RAG leak documents users are not allowed to see?

Yes, if retrieval does not enforce permissions. Access-control filtering must happen at query time, inside the retrieval step, so unauthorized documents never enter the context. Post-filtering the generated answer is not sufficient, because the model has already seen the content.

Is prompt injection a real risk in RAG systems?

It is one of the most cited risks. Retrieved documents are untrusted input, and instructions hidden inside them can influence the model. Treat retrieved text as data rather than instructions, constrain what tools the model can call, and keep the retrieval corpus curated and monitored.

Latest articles

Scroll to Top