Production RAG Architecture: Retrieval, Evals, Security and Cost

A production RAG guide to retrieval, chunking, permissions, evaluation, observability, latency and cost, based on recent hands-on engineering work.

Ijaz KhanSeptember 24, 2026 6 min read
On this page

A useful RAG demo can be assembled quickly. A production assistant needs much more: permission-aware retrieval, measurable quality, failure handling, observability and an owner who can improve it after launch.

My recent and ongoing work includes RAG and AI integrations within full-stack products. In my role at Zigron Pakistan, that includes AI integration responsibilities for DentaSmart as part of a wider team. This guide explains the engineering decisions without claiming sole ownership, private product metrics or a fixed delivery timeline.

The production pipeline in one view

A practical RAG system has two connected paths.

Ingestion path:

  1. Accept an approved source.
  2. Extract and clean its content.
  3. Attach ownership, tenant and access metadata.
  4. Split the content along meaningful boundaries.
  5. Create embeddings and a searchable text representation.
  6. Store the chunks, source references and version information.

Answer path:

  1. Authenticate the user.
  2. Apply tenant and permission filters.
  3. Rewrite or classify the question only when useful.
  4. Retrieve candidate passages with vector and keyword search.
  5. Rerank or filter the candidates.
  6. Build a grounded prompt.
  7. Generate an answer with source references.
  8. Log the question, retrieved evidence, response, latency and outcome safely.

The application, not the language model, must own authentication, authorization and tool permissions.

1. Measure retrieval before changing the model

When an answer is weak, inspect what the model received. Log the query, selected passages, source identifiers, retrieval scores and filters applied. This separates a retrieval failure from a generation failure.

Common retrieval failures include:

  • a relevant section split across chunks
  • outdated content ranking above the current policy
  • a tenant or permission filter removing the correct source
  • an exact identifier missed by semantic search
  • too many marginal passages diluting the prompt

Before changing models or prompts, review a representative set of retrieved passages. The model cannot reliably answer from evidence it never received.

2. Treat chunking as a content decision

A universal token count is a weak default. Chunk boundaries should follow the structure of the source: headings, sections, tables, list items or complete procedures.

Store enough metadata to interpret each passage, including the document title, section path, owner, tenant, version and update date. A sentence about a price, limit or policy is unsafe when separated from the product, plan or date it describes.

Keep the searchable passage focused, but preserve surrounding context for the final prompt. Test several strategies against real questions instead of assuming one chunk size fits every source.

3. Use hybrid retrieval when exact terms matter

Vector search is useful for meaning and paraphrases. Keyword search is useful for exact identifiers such as invoice numbers, product codes, names and error codes. Many production systems need both.

A common pattern is to retrieve candidates from semantic and lexical indexes, merge the results, and rerank them. Microsoft documents the same tradeoff in its RAG retrieval guidance: broad retrieval can improve recall, while reranking can improve precision at the cost of additional latency.

Do not add reranking automatically. Compare retrieval quality, latency and cost on your own evaluation set.

4. Enforce permissions before retrieval reaches the model

RAG does not make private data safe by itself. Every chunk should carry the metadata needed to enforce access rules. Filter by tenant, user role, source ownership and document state before material is added to a prompt.

Test negative cases deliberately:

  • a user asks for another organization's document
  • a source was deleted but remains in the index
  • an employee loses access after a role change
  • a document contains instructions aimed at the model
  • a tool request exceeds the user's application permissions

Treat retrieved documents and uploads as untrusted input. OWASP notes that prompt injection can arrive through external content. Keep secrets and authorization logic outside the prompt, restrict available tools, validate model-generated arguments and require confirmation for consequential actions.

5. Build an evaluation set from the intended workflow

A demo proves that selected examples can work. A release decision needs representative questions, missing information, ambiguous requests, permission failures and adversarial inputs.

For each test case, record:

  • Retrieval: Did the correct source appear in the candidate set?
  • Grounding: Is the answer supported by the retrieved evidence?
  • Citation: Does the reference point to the supporting passage?
  • Refusal: Does the assistant stop when evidence is missing?
  • Permission: Was restricted content excluded before generation?
  • Recovery: Does the user get a useful path after timeout or provider failure?
  • Action safety: Are generated arguments validated before execution?

Start with a small reviewed set and expand it when real failures appear. Run it again after changing the index, chunking, model, prompt or retrieval settings. OpenAI's eval tooling supports repeatable test datasets and graders, but the acceptance criteria still need to match the product risk.

6. Design for latency and partial failure

A production request crosses several components. Authentication, query processing, retrieval, reranking, prompt construction and generation all consume time and can fail independently.

Set a budget for each stage. Stream output when the interface benefits from it, but do not use streaming to hide broken retrieval. Add timeouts, bounded retries and cancellation. Preserve the user's input when a provider fails. If the assistant cannot answer safely, show a fallback instead of an endless spinner.

Cache only where permissions and freshness allow it. A cached answer can become a data leak when the cache key ignores tenant, role or document version.

7. Track cost as part of the workflow

Token prices are only one cost driver. A useful estimate also includes embedding, storage, retrieval, reranking, background ingestion, evaluation, monitoring and engineering support.

Track input and output tokens, retrieved context size, model choice, retries and tool calls per request. Then review the expensive cases. Common optimizations include removing duplicate passages, shortening repeated instructions, limiting unnecessary history and routing simple work to a smaller model.

Do not promise a universal build price or delivery time before the sources, permissions, actions, integrations and acceptance criteria are known.

A production readiness checklist

Before launch, confirm that:

  • every source has an owner and update process
  • deleted or revoked content leaves the searchable index
  • tenant and role filters are tested with negative cases
  • answers expose useful source references where appropriate
  • missing evidence produces a safe refusal or fallback
  • prompt injection and unsafe output cases are included in testing
  • latency, provider errors and retrieval failures are observable
  • request limits and cost alerts are configured
  • a feature switch or rollback path exists
  • someone owns feedback, source quality and evaluation after launch

When RAG is the wrong choice

Use ordinary search when users mainly need links. Use deterministic application logic when rules must be exact. Use templates when the task is repetitive but does not require retrieval. RAG is justified when the product must answer or synthesize from changing source material and can support the permissions, evaluation and maintenance that this requires.

The practical takeaway

A production RAG assistant is not a model attached to a vector database. It is a permission-aware information system with evaluation, observability and recovery paths.

My DentaSmart case study describes relevant backend, web application, subscription and AI integration responsibilities within Zigron Pakistan. If you are planning a RAG feature for an existing product, review my AI and LLM integration service or share the workflow you want to add. Please do not send private customer data, credentials or confidential documents in an initial message.

Primary references

#rag#llm#vector-databases#ai#production

Need this built?

These services can turn the ideas in this article into production software.

Keep reading

All articles
For Founders6 min read

Adding AI to Your SaaS: Scope, Risks and Launch Checklist

A founder’s guide to adding AI to an existing SaaS: choose one workflow, define permissions and acceptance criteria, then plan a controlled rollout.

Read article
AI Engineering4 min read

Serving a Custom ML Model in Production: The Plumbing Nobody Talks About

The data scientists hand you a model that works in a notebook. Making it survive real traffic, uploads, GPUs, queues and versioning is a different job entirely.

Read article