HomeBlogRAG Architecture Explained: Build AI Apps...

Engineering Guide · 9 min read · June 18, 2026

RAG Architecture Explained: Build AI Apps That Understand Your Documents

Connecting an LLM to a vector database takes an afternoon, but shipping Retrieval-Augmented Generation that respects tenant permissions, handles tables and PDFs cleanly, and refuses to hallucinate requires real systems engineering. Here is the production RAG architecture we deploy for startups.

Author
Smit Desai
Published
June 18, 2026
Read time
9 min read
Topic
AI & Agents
Services
Custom Web · Mobile Apps · All Services

A founder uploads four hundred product PDFs, support runbooks, and customer contracts into a vector database, wires up a chat endpoint, and tests three sample questions. Everything looks sharp in the demo. Two weeks after launch, a paying customer asks about an obscure API error code and gets an invented parameter, or worse, sees pricing from a deprecated 2022 brochure instead of last month's SLA.

Retrieval-Augmented Generation fails in production rarely because the language model is weak. It fails because the retrieval pipeline treats messy enterprise files like clean paragraphs and treats vector cosine similarity like an access-control layer.

If you are building document intelligence into a product—or extending an existing backend like the setup covered in integrating AI and LLM APIs into Laravel—the gap between a weekend prototype and a trustworthy system comes down to ingestion discipline, hybrid retrieval, security boundaries, and evaluation.


Why Naive Vector Search Fails on Real Company Data

The tutorial version of RAG extracts raw text, slices it every 500 characters, embeds each slice, and passes the top five cosine matches into a prompt. That approach breaks down quickly on real business documents.

The Chunk Boundary Problem

PDFs, Notion exports, and spreadsheets carry meaning in structure: headings, nested bullet lists, financial tables, and footnotes. Fixed-character slicing routinely cuts a Markdown or PDF table in half, separating column headers from the numbers underneath. When a chunk contains "$499/month" without "Enterprise Tier" three lines above it, the embedding loses the subject.

Tenant Isolation Before Similarity Scoring

In multi-tenant SaaS apps, filtering permissions after vector lookup is both an accuracy bug and a security hazard. If you fetch the top 10 nearest vectors across all customers and then drop unauthorized rows in application code, a tenant with smaller documents may receive zero valid chunks—or a prompt injection could probe neighboring records if any filtering step is skipped. Access control predicates must run inside the index scan itself, following the data-protection principles highlighted in the OWASP Top 10 for LLM Applications.


Designing an Ingestion Pipeline That Preserves Structure

Good retrieval starts before an embedding API is ever called. Treat document ingestion as an idempotent background pipeline with versioned artifacts.

Document Parsing and Metadata Normalization

Convert PDFs, DOCX files, and HTML into structured Markdown or section trees first so headings, tables, and lists remain intact. Store a deterministic content_hash and source_version per document. When a policy updates, you delete or tombstone stale chunks atomically rather than letting old and new versions compete in search results.

Choosing Chunk Sizes and Overlap Pragmatically

Structure-aware chunking splits along headings and paragraph boundaries first, falling back to token caps only when a single section runs long. Prepending the parent heading breadcrumb to every chunk preserves context even when a paragraph sits three levels deep:

from dataclasses import dataclass
from typing import Iterable


@dataclass(frozen=True)
class DocumentChunk:
    tenant_id: str
    document_id: str
    section_path: str
    acl_roles: tuple[str, ...]
    content: str


def build_contextual_chunks(
    sections: Iterable[tuple[str, str]],
    tenant_id: str,
    document_id: str,
    acl_roles: tuple[str, ...],
    max_words: int = 280,
) -> list[DocumentChunk]:
    """Attach section headings to bounded text slices for higher recall."""
    chunks: list[DocumentChunk] = []

    for section_path, body in sections:
        words = body.split()
        step = max_words - 40  # 40-word overlap preserves cross-sentence references

        for start in range(0, max(1, len(words)), step):
            slice_text = " ".join(words[start : start + max_words]).strip()
            if not slice_text:
                continue

            enriched = f"Section: {section_path}\n\n{slice_text}"
            chunks.append(
                DocumentChunk(
                    tenant_id=tenant_id,
                    document_id=document_id,
                    section_path=section_path,
                    acl_roles=acl_roles,
                    content=enriched,
                )
            )

    return chunks

Keep tables whole whenever possible, or store a concise natural-language summary alongside the raw Markdown table so semantic search can match the topic while the LLM reads exact cell values.


Dense embeddings excel at paraphrasing ("how do I cancel my plan?" matching "subscription termination policy"). They struggle with exact strings: invoice numbers, part IDs, ERR_TIMEOUT_408, or proper nouns.

Instead of spinning up a separate vector database that drifts out of sync with your primary database, PostgreSQL with pgvector and native tsvector lets you run transactional hybrid search using Reciprocal Rank Fusion (RRF):

WITH filtered_chunks AS (
    SELECT id, document_id, content, embedding, search_tsv
    FROM document_chunks
    WHERE tenant_id = $1
      AND is_active = TRUE
      AND acl_roles && $2::text[]
),
vector_hits AS (
    SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $3::vector) AS rank_v
    FROM filtered_chunks
    ORDER BY embedding <=> $3::vector
    LIMIT 40
),
keyword_hits AS (
    SELECT id, ROW_NUMBER() OVER (
        ORDER BY ts_rank_cd(search_tsv, websearch_to_tsquery('english', $4)) DESC
    ) AS rank_k
    FROM filtered_chunks
    WHERE search_tsv @@ websearch_to_tsquery('english', $4)
    LIMIT 40
)
SELECT
    c.id,
    c.document_id,
    c.content,
    COALESCE(1.0 / (60 + v.rank_v), 0.0) + COALESCE(1.0 / (60 + k.rank_k), 0.0) AS rrf_score
FROM filtered_chunks c
LEFT JOIN vector_hits v ON v.id = c.id
LEFT JOIN keyword_hits k ON k.id = c.id
WHERE v.id IS NOT NULL OR k.id IS NOT NULL
ORDER BY rrf_score DESC
LIMIT 20;

Notice the order of operations: filtered_chunks enforces tenant_id, is_active, and acl_roles first. Then vector_hits and keyword_hits retrieve up to 40 candidates each, and RRF merges them without needing fragile score normalization between cosine distance and BM25-style keyword ranks.


Retrieval Architecture Trade-Offs

Adding complexity only pays off when it solves a measured failure mode. Compare the three practical tiers before over-building:

Architecture Tier Retrieval Components Latency Impact Best Operational Fit Primary Failure Mode
Baseline Vector Dense embeddings + cosine top-k 40–90 ms Small homogeneous FAQ sets under 5,000 docs Misses exact SKUs, dates, and error codes
Hybrid + ACL Filter pgvector + tsvector + RRF + tenant predicates 70–150 ms Multi-tenant SaaS apps, support portals, contracts Top-20 may still include noisy partial matches
Hybrid + Reranker Hybrid top-25 passed through cross-encoder reranker to top-6 220–450 ms High-stakes legal, compliance, and technical docs Higher per-query compute; needs caching for repeats

For most startups shipping an initial version through custom web application development, starting at Hybrid + ACL Filter gives you clean security and exact-match coverage without extra microservices. Add a cross-encoder reranker once your evaluation set shows relevant chunks landing at rank 12 instead of rank 3.


Grounding Prompts, Citations, and Evaluation Harnesses

Retrieval is only half the contract. The generation layer must respect what was retrieved—and admit when nothing relevant came back.

Enforcing Source Citations and Abstention

Structure your prompt and output schema (following patterns in the OpenAI platform documentation) so every factual claim cites a chunk ID returned in that request. Give the model an explicit escape hatch: if the retrieved chunks do not contain the answer, instruct it to return an abstention state rather than guessing from pretraining weights. Pair each response with clickable document links in the UI so users verify critical numbers in one click.

Regression Testing Retrieval Separately from Generation

Never debug RAG by staring at final chat answers alone. Maintain a golden dataset of 40 to 100 real user questions mapped to expected document_id or section_path targets:

  1. Retrieval Recall@K: Did the right chunk appear in the top 5 or top 10 before the LLM ran? If not, fix parsing, chunking, or query expansion.
  2. Faithfulness / Groundedness: Given the exact retrieved chunks, did the model introduce claims absent from the context? If yes, tighten prompt instructions or lower temperature.
  3. Abstention Accuracy: On out-of-scope questions, did the system refuse cleanly instead of fabricating policy?

Run this suite automatically in CI whenever someone changes chunk sizes, embedding models, or system prompts.


How SmitDev Scopes and Ships Production RAG Systems

Building AI features that earn customer trust requires full-stack ownership across ingestion workers, database indexing, access control, and frontend streaming—not just prompt tweaks. Across 170+ shipped case studies since 2017, we treat RAG as core backend engineering first and model integration second.

Through our AI agents and architecture consulting, we scope and ship production document pipelines cleanly: starting with a technical blueprint and fixed milestone build, or via $55/day dedicated senior engineering (8–9 hours/day) and $1,999/month ongoing delivery for startups scaling fast.

If you have documents sitting in S3, Google Drive, or PostgreSQL and want a grounded AI interface that actually passes security review, contact SmitDev to walk through your schema and retrieval requirements.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Agentic Engineering

AI Agents & Automation Consulting

Deploy schema-validated AI agents, RAG pipelines, and CRM/support automation with predictable token and latency budgets.

Interactive Tool · Scope & Budget

SaaS & AI Cost Calculator

Estimate development timeline, MVP phases, and build costs across $55/day sprints or $1,999/month dedicated delivery.

01 — Frequently asked questions

ai & agents

When should a startup choose RAG instead of fine-tuning a language model?

Choose RAG whenever answers depend on changing business documents, customer-specific records, or verifiable citations. Fine-tuning teaches a model tone or output format, not live factual recall, and cannot enforce per-user document permissions at query time.

Why does pure vector similarity search miss exact product codes or legal terms?

Dense embeddings compress meaning into a semantic vector, which blurs exact tokens such as SKU numbers, error codes, or clause IDs. Pairing vector similarity with keyword search (BM25 or PostgreSQL tsvector) via Reciprocal Rank Fusion fixes exact-match recall.

Can we build production RAG inside PostgreSQL without adding a dedicated vector database?

Yes. For most startups under a few million document chunks, PostgreSQL with pgvector keeps embeddings, full-text indexes, and row-level tenant permissions inside a single transactional database—eliminating sync drift between separate stores.

How do you stop a RAG assistant from leaking another customer's documents?

Enforce tenant and role filters inside the retrieval query itself before ranking results, never after the LLM receives the context. Pair database-level predicates with short-lived document ingestion ACLs.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.