Key takeaways

  • RAG lets an LLM answer from your own documents, with sources, without retraining the model.
  • Most accuracy problems are retrieval problems: chunking, hybrid search and re-ranking matter more than the prompt.
  • Enforce permissions during retrieval, not in the prompt.
  • Measure with a golden question set and faithfulness scores before and after every change.
  • Use RAG for knowledge, fine-tuning for behaviour, and long context for occasional deep analysis.

Every company we talk to has the same problem. The knowledge that answers most questions already exists somewhere: in a policy PDF, a Confluence page, last year’s support tickets or a product spec nobody can find. Large language models are excellent at writing answers, but out of the box they know nothing about your business. Ask them anyway and they will happily make something up.

Retrieval-augmented generation, or RAG, fixes that by giving the model the right information at the moment it needs it. The idea is simple. The engineering is not. This guide walks through how a production RAG architecture actually works, the design decisions that decide whether it is accurate, and the failure points we see most often when teams move from a demo to real users.

What is retrieval-augmented generation?

RAG is an architecture that combines two steps. First, a retriever searches your own content for passages relevant to a question. Second, a generator, usually a large language model, writes an answer using only those passages and cites where each fact came from.

Think of it as an open-book exam. Instead of relying on what the model memorised during training, you hand it the right pages and ask it to answer from them. That gives you three things a plain chatbot can’t: answers specific to your business, sources people can check, and knowledge you can update by changing documents rather than retraining a model.

How a RAG system works, end to end

A working RAG system is really two pipelines that meet in the middle. The ingestion pipeline runs in the background, turning raw documents into something searchable. The query pipeline runs every time someone asks a question, usually in one to three seconds.

Figure 1. The two halves of a RAG system. Documents are processed offline into a hybrid index (top); each question is rewritten, matched against that index, re-ranked and answered with citations (bottom).
  1. Data sourcesAnything with text: PDFs, Word files, SharePoint, Confluence, ticket systems, CRMs and databases.
  2. Parse and OCRExtract clean text, tables and headings. Scanned files need OCR, and this step quietly decides a lot of your final accuracy.
  3. ChunkSplit documents into passages that keep one idea together, ideally following headings rather than a fixed character count.
  4. EmbedConvert each chunk into a vector that captures its meaning, and attach metadata such as source, date and access level.
  5. Hybrid indexStore vectors for semantic search alongside a keyword index (BM25) and permission metadata.
  6. User questionThe question arrives from a chat window, an API, a help desk or a voice agent.
  7. Query rewriteClarify vague questions, expand acronyms, or split a complex question into several simpler searches.
  8. Hybrid retrievalRun semantic and keyword search together and merge the results, filtering out anything the user isn’t allowed to see.
  9. Re-rankA more precise model scores the candidates and keeps only the handful that actually answer the question.
  10. Grounded answerThe LLM writes an answer from those passages only, cites them, and is checked before the response is sent.

The production RAG architecture, layer by layer

The diagram above shows the flow. In production, it helps to think in layers instead, because each layer has different owners, costs and failure modes. This is the reference architecture we use as a starting point for client projects.

Figure 2. A six-layer production RAG architecture. Data moves up from sources to applications; evaluation and observability sit underneath everything, because you can’t improve what you don’t measure.
  1. Channels and applicationsWhere people ask questions. One RAG back end can serve a website assistant, an internal Slack bot and a voice agent at the same time.
  2. Orchestration and guardrailsDecides which knowledge base and prompt to use, removes sensitive data, and blocks answers that don’t cite a source.
  3. Retrieval layerHybrid search, re-ranking and a semantic cache that returns instant answers to questions it has already seen.
  4. Knowledge storesA vector database such as Pinecone, Weaviate, pgvector or Chroma, plus a keyword index and the permission metadata attached to every chunk.
  5. Ingestion pipelineConnectors, OCR, chunking and embedding jobs that keep the index in sync as documents change.
  6. Evaluation and observabilityTest sets, accuracy and faithfulness scores, logging and drift alerts. This is the layer most demos skip and most production systems regret skipping.

The design decisions that matter most

Most RAG accuracy problems are retrieval problems. If the right passage never reaches the model, no amount of prompt engineering will save the answer. These are the decisions we spend the most time on.

1. Chunking strategy

Chunks that are too small lose context; chunks that are too large bury the relevant sentence in noise and waste tokens. In our experience, passages of roughly 300 to 800 tokens with a small overlap work well for most business documents, but the bigger win is structure-aware chunking: splitting on headings, sections and table boundaries so each chunk holds one complete idea. For long manuals, a parent-child approach helps: search small chunks for precision, then pass the larger parent section to the model for context.

2. Embedding model

The embedding model decides what “similar” means. Choose one that handles your languages and domain vocabulary, and remember that changing it later means re-embedding everything. For data that must stay private, strong open-source embedding models run comfortably on your own infrastructure.

3. Hybrid search and re-ranking

Pure vector search is great at meaning and surprisingly bad at exact terms such as product codes, error numbers and names. Keyword search (BM25) is the opposite. Running both and merging the results with reciprocal rank fusion consistently beats either alone. A cross-encoder re-ranker then reads the top 30 to 50 candidates properly and keeps the best five to eight. This single step often produces the largest accuracy jump in a RAG system.

4. Query transformation

Real users ask vague, multi-part questions. Rewriting the query, expanding it with a hypothetical answer (a technique called HyDE), or decomposing it into sub-questions gives the retriever a much better chance.

5. Access control at retrieval time

Permissions must be enforced before passages reach the model, by filtering on metadata during search. Asking the model to “ignore documents the user can’t see” is not a security control.

Here is how a quick demo compares with a production build:

AreaDemo RAGProduction RAG
ChunkingFixed size, e.g. every 1,000 charactersStructure-aware, with parent-child context
SearchVector search onlyHybrid vector and keyword search, merged and re-ranked
QueriesPassed through as typedRewritten, expanded or decomposed
SecurityEveryone sees everythingPermission filters applied during retrieval
AnswersNo sourcesCitations on every claim, refusal when unsupported
QualityChecked by eyeEvaluation set, faithfulness scores, drift monitoring
FreshnessIndexed onceIncremental sync and re-indexing

Why RAG systems fail, and how to fix them

When a RAG assistant gives a bad answer, the cause is usually one of a short list. Knowing the list makes debugging much faster.

  • The right passage was never retrieved. Fix chunking, add keyword search, add query rewriting.
  • It was retrieved but ranked too low. Add or tune a re-ranker.
  • The document was parsed badly. Tables and scanned pages are common culprits; improve parsing and OCR.
  • The index is stale. Schedule incremental syncs and track when each source was last updated.
  • The model ignored the context. Tighten the prompt, reduce irrelevant passages and require citations.
  • The model invented a fact. Add hallucination checks before the answer is shown.

That last point deserves more attention than it usually gets. In our multi-tenant RAG platform we run five separate hallucination checks, from verifying that every cited passage exists to scoring whether each sentence is supported by the retrieved text, and we log every failure for review. We also track embedding drift, so the system re-indexes automatically when retrieval quality starts to slip.

Rule of thumb: when accuracy is poor, look at what was retrieved before you touch the prompt. Nine times out of ten, the model gave a reasonable answer to the wrong context.

How to evaluate a RAG system

You can’t improve what you don’t measure, and “it looked right in the demo” is not a measurement. A practical evaluation setup has three parts.

  1. A golden question set. Collect 100 to 300 real questions with known correct answers and the source passages that support them. Include the awkward ones.
  2. Retrieval and answer metrics. Measure context recall (did we retrieve the passages that contain the answer?), context precision (how much of what we retrieved was relevant?), faithfulness (is every claim supported by the context?) and answer relevance (did we actually answer the question?).
  3. Production feedback. Thumbs up and down, “no answer found” rates and escalations to humans tell you where the knowledge base has gaps.

Run the golden set on every change to chunking, models or prompts. It turns tuning from guesswork into engineering.

RAG vs fine-tuning vs long context

Teams often ask whether they should fine-tune a model instead. The honest answer is that they solve different problems, and many strong systems use more than one.

ApproachBest forLimitations
RAGAnswering from large, changing knowledge with sources and permissionsQuality depends on retrieval; needs an ingestion pipeline
Fine-tuningTeaching a consistent style, format or narrow skillExpensive to update; doesn’t cite sources; can still hallucinate facts
Long contextA few large documents per question, analysed in depthCost and latency grow with every token; accuracy drops in very long inputs

Our default recommendation: start with RAG for knowledge, add fine-tuning only when you need a behaviour the base model can’t learn from examples in the prompt, and use long context for one-off deep analysis rather than everyday questions.

Where RAG is heading: agentic RAG and knowledge graphs

The next step is agentic RAG, where an AI agent decides when to search, which source to query, and whether the results are good enough or it should search again. It handles multi-step questions far better than a single retrieve-then-answer pass. You can read more about how these agents are designed in our guide to agentic AI architecture.

Graph-based approaches, often called GraphRAG, add a knowledge graph of entities and relationships on top of the text. They shine when questions are about connections, such as “which suppliers affect these three products?”, rather than finding a single passage.

A practical path from idea to production

We usually run RAG projects in three stages. In the first two weeks, we build a proof of concept on a representative slice of your real documents and measure it against a golden question set. Next comes the production build: connectors, permissions, monitoring and the user interface your team will actually use. Finally, we keep tuning based on feedback and evaluation results as more content and users arrive. You can see how that works in practice on our how we work page, or explore our RAG development services.

Frequently asked questions

What is RAG architecture?

RAG architecture is a design that combines a retriever, which searches your own documents for relevant passages, with a large language model that writes an answer from those passages and cites them. It usually includes an offline ingestion pipeline and an online query pipeline.

What is the best chunk size for RAG?

There is no universal best size. Passages of roughly 300 to 800 tokens with a small overlap work well for most business documents, but splitting on headings and sections so each chunk holds one complete idea usually matters more than the exact size.

Which vector database should I use for RAG?

Pinecone, Weaviate, pgvector and Chroma are all solid choices. The right one depends on scale, hosting requirements and whether you already run PostgreSQL. Hybrid search support and metadata filtering matter more than raw speed for most business use cases.

Does RAG eliminate hallucinations?

No, but it reduces them significantly when combined with good retrieval, citation requirements and automated faithfulness checks. A production system should also be able to say it doesn’t know when the answer isn’t in the source material.

Is RAG cheaper than fine-tuning?

Usually, yes, for knowledge-heavy use cases. RAG avoids repeated training runs, and updating knowledge is as simple as updating documents. Fine-tuning is better suited to teaching a style or narrow skill than to keeping facts current.

NPMCODE Engineering TeamWe design, build and run AI agents, RAG systems and machine-learning models for SMBs and enterprises. About us

Keep reading

All articles

Planning a RAG system?

We can build a proof of concept on your own documents in two weeks and measure its accuracy against real questions.