
What is a RAG system?
A RAG (retrieval-augmented generation) system connects large language models (LLMs) to knowledge sources outside the model’s weights — in an enterprise, usually the organisation’s own documents. It retrieves relevant passages at query time and supplies them as context for an answer. The architecture below has two pipelines: one prepares the documents; the other retrieves evidence and generates an answer for each question.
The term comes from Lewis et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks” (arXiv 2005.11401, May 2020).
Enterprise AI systems need reliable sources as well as a capable language model. RAG can supply evidence from an organisation’s own data, but it does not guarantee a correct answer. Document quality, retrieval and answer evaluation all need attention.
What does a RAG architecture look like?
Two pipelines share one vector store. The indexing pipeline runs when documents change; the query pipeline runs for every question.
In plain text: parse source documents, split them into passages and store their embeddings with source references. For each user query, retrieve candidate passages and rerank them. Supply the selected passages to the language model, then check its answer against that retrieved information and the cited sources.
The table maps each component to the options covered in this post and the failure to design against.
| Component | What it does | Options covered here | Common failure |
|---|---|---|---|
| Document parsing | Extracts text and structure from source files | Carry section headers, document title and document type as metadata | Headings lost at parse time, so chunks arrive without context |
| Chunking | Splits documents into retrievable passages | Structure-aware chunking; hierarchical chunking with parent-section context | Fixed-size splits that cut paragraphs in half |
| Embedding model | Turns each chunk, and each question, into a vector | text-embedding-3-large, Gemini embedding models, Cohere Embed, BGE-M3, Qwen3-Embedding, Nomic Embed | Domain jargon the model handles badly, missed by choosing on benchmarks alone |
| Vector store | Stores vectors with their metadata for similarity search | pgvector, Pinecone, Weaviate, Qdrant | A new database added before corpus size or filtering needs justify it |
| Retrieval | Finds candidate chunks for the question | Dense plus BM25 hybrid search; query decomposition | Naive top-k similarity missing multi-part or terminology-shifted questions |
| Reranking | Rescores candidates and keeps the passages that answer the question | Cross-encoder models; contextual compression | Loosely related chunks crowding the context |
| Prompt assembly | Combines the question with the top passages and their source references | Enforced citation of retrieved sources | Answers that cannot be traced back to a source |
| Generation | The language model writes the answer from the supplied context | OpenAI or Claude models; LangChain chains or LangGraph state machines | The model guessing when the context is insufficient |
| Evaluation and guardrails | Measures and enforces answer quality | Context precision and recall; faithfulness and relevancy; hallucination detection | Quality decay from embedding drift and corpus changes that nobody measures |
| Security and access control | Limits retrieval to the sources the asking user is allowed to see | Source permissions as chunk metadata, filtered in the retrieval query; tenant partitions; retrieval logs | Answers quoting documents the user cannot open, or following instructions planted in a document |
The sections below cover the main decisions at each layer.
1. Chunking: How You Split Documents Determines Answer Quality
Fixed-size chunking can separate a statement from the context needed to understand it. Use document headings, sections and paragraphs to choose useful boundaries. Keep the document title, section heading and document type with each chunk.
For long research documents, retrieve a specific paragraph and include its parent section when more context is needed. Test whether the resulting passages contain enough evidence to answer representative questions.
2. Embedding Models: Match Capability to Use Case
For general-purpose English, OpenAI’s text-embedding-3-large is strong out of the box, and Google’s Gemini embedding models are a managed alternative. For multilingual corpora, Cohere’s Embed models perform well without separate translation (Embed v4 and later also embed images and mixed documents). For on-prem needs, open models such as BGE-M3, Qwen3-Embedding or Nomic Embed avoid API dependency. Leaderboard rankings change every few months, so always validate on a representative eval set rather than relying on benchmarks alone, because domain-specific jargon can break otherwise strong models.
3. Vector Store Selection
pgvector is the pragmatic default up to a few million vectors — no new infrastructure and transactional consistency with application data. For higher scale or advanced filtering, move to a dedicated store: Pinecone (managed and fast), Weaviate (hybrid search), or Qdrant (strong metadata filtering). Choose based on corpus size, latency needs, and operational maturity; don’t add a new database unless the retrieval or ops benefits are real.
4. Retrieval Strategy: Beyond Basic Similarity Search
Semantic search uses vector similarity to find passages with related meaning, even when their wording differs from the question. A similar passage can still lack the evidence needed for an answer. Evaluate these techniques against your users’ questions:
- Hybrid search: combine dense vectors with BM25 keyword match for exact terms and identifiers.
- Query decomposition: split complex questions into sub-queries and merge results.
- Re-ranking: cross-encoder models rescore retrieved chunks for true relevance.
- Contextual compression: trim retrieved chunks to only the passages that answer the question.
5. Orchestration with LangChain and LangGraph
Simple Q&A can use a linear chain. Multi-step workflows (compliance reviews, research synthesis) benefit from LangGraph state machines that can retrieve, assess sufficiency, reformulate queries, branch to different data sources, and loop until adequate context is gathered before synthesis.
6. Evaluation and Guardrails
Build an evaluation set with a question, expected answer and supporting sources for each case. Measure whether retrieval finds the needed evidence and excludes irrelevant passages. Check generated responses for claims the sources support, correct citations and relevance to the question.
When evidence is missing, return a clear limitation or request more information. Test these cases as well as successful answers. Repeat evaluation after changes to documents, embeddings, retrieval settings or the language model.
7. Security and Access Control
Retrieval decides what the model can quote. If the vector store returns every chunk that matches a question, an answer can include text from a document the asking user is not allowed to open. The OWASP Top 10 for LLM Applications covers this risk as Vector and Embedding Weaknesses (LLM09 in the 2026 edition, LLM08 in 2025), and instructions hidden in retrieved documents as Prompt Injection (LLM01). Build these controls into the retrieval layer:
- Permission-aware retrieval: copy each source document’s access list (users, groups or sensitivity label) onto its chunks as metadata, and filter on the asking user’s entitlements inside the vector query, not after the results come back.
- Tenant partitioning: keep each tenant’s vectors in a separate index, namespace or partition, and set the tenant scope on the server, never from a value the client sends.
- Retrieved text as untrusted input: a document can carry instructions aimed at the model (indirect prompt injection). Mark retrieved passages as data in the prompt, keep instructions in the system prompt, and require a separate check before retrieved text can trigger a tool call or other action. These measures reduce the risk; OWASP notes it is unclear whether any method prevents prompt injection completely.
- Retrieval logs: record who asked, the tenant scope, the query and the IDs of the chunks returned, in logs the application cannot alter. The logs give you an audit trail of what was retrieved for each request and help you spot attempts to reach another tenant’s data. They do not show which chunks the model used in its answer or what the user read.
RAG, fine-tuning or long-context prompting: which should you use?
| Factor | RAG | Fine-tuning | Long-context prompting |
|---|---|---|---|
| How knowledge gets in | Relevant passages retrieved from an indexed knowledge base at query time and passed to the model as context | Training data is used to adapt model weights | The whole document set goes into the prompt on every call |
| Data freshness | Current once a changed document is re-indexed | Fixed at the last training run until you retrain | Current, because the documents are sent each time |
| Source attribution | Each answer can cite the retrieved passages | No direct link from an answer back to a source | Possible when the model is told to quote the documents it was given |
| Main cost driver | Indexing pipeline, vector store and retrieval tuning | Training runs and preparing example data | Input tokens on every request |
| When it fits | Large or frequently changing corpora where answers must cite sources | A consistent format, tone or task behaviour that rarely changes | Small corpora that fit in a single prompt |
When RAG Makes Sense — and When It Doesn’t
Use RAG when data changes frequently, source attribution matters, or fine-tuning would go stale. Avoid RAG for real-time data (use APIs), primarily structured data (use SQL/analytics), or very small corpora that fit in a single prompt for long-context models. If you do use RAG, set guardrails that force the model to admit when context is insufficient rather than guessing.
At Brainstack, we build RAG systems with LangChain/LangGraph orchestration, OpenAI or Claude generation, pgvector or Pinecone storage, and bespoke eval suites to keep retrieval quality high. Treat RAG as an engineering project with iteration and measurement — that’s how it becomes a daily-use tool instead of a one-off demo. See our AI and machine learning services and FAQ for delivery timelines.
Frequently Asked Questions
What are the main components of a RAG system?
An indexing pipeline that parses documents, splits them into chunks, embeds each chunk and stores the vectors, and a query pipeline that retrieves candidate chunks, reranks them, assembles a prompt with source references, generates the answer and checks it. The vector store connects the two.
What is the difference between RAG and fine-tuning?
RAG retrieves knowledge from your documents at query time, so answers stay current and can cite their sources. Fine-tuning trains knowledge or behaviour into the model’s weights, which fixes it at the last training run. Use RAG when data changes often or source attribution matters.
Which vector database should a RAG system use?
pgvector is the pragmatic default up to a few million vectors: it adds no new infrastructure and keeps transactional consistency with application data. At higher scale or with advanced filtering needs, a dedicated store such as Pinecone, Weaviate or Qdrant can justify the extra database.
How do you evaluate a RAG system?
Build a set of question–answer–source triples and measure context precision and recall for retrieval, then answer faithfulness and relevancy for generation. Keep running the evaluation, because embedding drift and corpus changes degrade quality over time.
When should you not use RAG?
Skip RAG for real-time data (call the source API), for mainly structured data (query it with SQL or analytics tools) and for small corpora that fit in a single prompt for a long-context model.
How long does it take to build a production RAG system?
The schedule depends on data readiness, the number of integrations, evaluation requirements and deployment approvals. Scope a proof of concept separately from production integration and operational testing, then agree milestones and acceptance criteria for the engagement.
Considering RAG for Your Organisation?
We help enterprises design and build RAG systems that deliver accurate, trustworthy answers from proprietary knowledge bases. Start with a focused pilot to see what RAG can do for your specific content.







