Urvil Patel
urvil@portfolio:~$
0%
Urvil PatelUrvil Patel
•14 min read•Urvil Patel

Understanding RAG: From Embeddings to Production-Ready AI Systems

A deep architectural breakdown of Retrieval-Augmented Generation: embedding geometry, chunking math, hybrid retrieval, cross-encoder reranking, and production evaluation.

Retrieval-Augmented Generation (RAG) is frequently pitched as a straightforward pattern: turn text into vectors, store them in a database, query by similarity, and stuff the top results into a prompt. In practice, building a RAG system that functions reliably in enterprise production is an exercise in applied distributed systems, information retrieval mathematics, and defensive software engineering.

When deployed naively, RAG systems suffer from high latency, context pollution, hallucinated synthesis, and silent retrieval failures. In this guide, we decompose RAG from foundational vector geometry to production-grade TypeScript implementations in modern Next.js environments.


What Problem Are We Solving?

Large Language Models (LLMs) possess vast parametric memory formed during pre-training. However, relying solely on parametric memory introduces three critical engineering constraints:

  1. Knowledge Cutoffs: A model trained through early 2024 has zero knowledge of changes deployed yesterday, updated API schemas, or recent news.
  2. Private & Proprietary Silos: Foundation models have never seen your company's internal Jira tickets, SOC2 compliance reports, private codebases, or customer CRM records.
  3. Parametric Hallucination: When an LLM lacks verifiable grounding for a niche domain question, its probabilistic sampling defaults to plausible-sounding fabrication.

RAG resolves these limitations by decoupling the knowledge base from the reasoning engine. The LLM ceases to act as an unreliable encyclopedia; instead, it acts as a reasoning processor operating over verifiable, just-in-time documents retrieved from an external data store.


RAG vs. Fine-Tuning: The Decision Matrix

A frequent architectural question is whether to fine-tune a model on internal documents or build a RAG pipeline. The table below illustrates the core engineering tradeoffs:

Architectural VectorRetrieval-Augmented Generation (RAG)Supervised Fine-Tuning (SFT)
Primary PurposeInject dynamic, verifiable factual knowledgeAdapt syntax, style, tone, and deterministic structure
Knowledge Update LatencyMilliseconds (insert new vector into index)Days/Weeks (dataset curation, GPU training run, eval)
Auditability & CitationsExplicit: provides exact source document chunksBlack-box: impossible to cite a specific neural weight
Access Control (RBAC)Dynamic: filter retrieval by tenant/user ACLsStatic: all users access the same baked weights
Hallucination RateLow (strictly grounded by context prompt)Moderate/High (model generates from probability weights)
Compute / Training CostLow infrastructure cost; vector DB query feesHigh GPU cluster costs and continuous retraining

The Complete RAG Architecture

A production-grade RAG pipeline consists of two decoupled sub-systems: the Ingestion Pipeline (offline/asynchronous) and the Retrieval & Inference Pipeline (online/real-time).

architecture/rag-pipeline.txt
TXT
INGESTION PIPELINE (Offline / Asynchronous)
Raw Documents (PDF, MDX, Docs)
↓
Document Parser & Cleaner
↓
Semantic / Recursive Chunker
↓
Dense Embedding Model (e.g. text-embedding-3-small)
↓
Vector Database (HNSW Index + Sparse Inverted Index)
──────────────────────────────────────────────────────────
QUERY & INFERENCE PIPELINE (Online / Real-time)
User Query: "How do we rotate production KMS keys?"
↓
Query Expander / Sub-Query Decomposition
↓
Hybrid Retriever (Dense Vector Search + BM25 Lexical Search)
↓
Reciprocal Rank Fusion (RRF) -> Candidate Chunks (Top 50)
↓
Neural Cross-Encoder Reranker -> Precision Chunks (Top 5)
↓
Context Assembly & Citation Guardrails Prompt
↓
Frontier LLM (e.g., Claude 3.5 Sonnet / GPT-4o)
↓
Verified Streaming Response with Inline Citations

Embeddings and Vector Geometry Explained

At the heart of dense semantic retrieval is the embedding model. An embedding model transforms arbitrary-length text strings into fixed-dimensional vectors in high-dimensional space (typically 1,536 or 3,072 dimensions).

Mathematically, text chunks with similar semantic meaning are mapped to coordinates that sit close together in this high-dimensional hypersphere.

Measuring Proximity: Cosine Similarity vs. Inner Product

Given two vectors u and v:

math/cosine-similarity.txt
TXT
Cosine Similarity(u, v) = (u · v) / (||u||₂ * ||v||₂)

When vectors are L2-normalized prior to storage (||u||₂ = 1), the denominator equals 1, and Cosine Similarity simplifies directly to the Dot Product (u · v). This reduces query-time distance calculations from expensive square roots to vectorized SIMD multiply-accumulate operations.

Vector Databases and HNSW Indexing

Brute-force exact nearest neighbor search over millions of vectors requires an O(N · d) scan, which introduces hundreds of milliseconds of query latency.

Production vector databases (such as pgvector, Pinecone, or Qdrant) use Hierarchical Navigable Small World (HNSW) graphs. HNSW constructs multi-layered skip-list style graphs where top layers allow rapid long-distance routing through vector space, and lower layers perform fine-grained localized clustering. This brings query complexity down to O(log N) while maintaining over 97% recall.


Chunking Strategies: The Foundation of Retrieval

Chunking is the single most common failure point in RAG pipelines. If chunk boundaries split a paragraph mid-sentence or detach a table from its explanatory heading, the embedding model will produce an inaccurate vector representation.

1. Fixed-Size Chunking (Anti-Pattern)

Splitting text strictly every 500 characters breaks words, code blocks, and lists arbitrarily. Never use fixed-character chunking in production.

2. Recursive Character Chunking

Splits sequentially on semantic boundaries: double line breaks \n\n (paragraphs), then single line breaks \n (lines), then spaces (words).

3. Markdown / Document AST Chunking (Gold Standard)

Parses the Abstract Syntax Tree (AST) of the document. Keeps Markdown headings (#, ##, ###) prepended to each sub-chunk as a breadcrumb trail:

taxonomy/breadcrumb-chunk.txt
TXT
[Document: Security Policy > Section: AWS Infrastructure > KMS Key Rotation]
KMS customer managed keys must be rotated every 90 days using the automated
scheduler. Manual rotations require approval from the SecOps lead.

By prepending hierarchical breadcrumbs to each chunk, the vector captures domain context even when the chunk text itself is brief.


Hybrid Search: Combining Dense Semantic & Sparse Lexical Retrieval

Dense vector embeddings excel at semantic matching (e.g., matching "automobile malfunction" with "car engine breakdown"). However, they frequently fail at exact lexical matching:

  • Part numbers (SKU-9921-X)
  • Function names (getVerifiedUserById)
  • Acronyms or unique employee handles

Production systems implement Hybrid Search, executing two parallel queries:

  1. Dense Retrieval: Embedding vector cosine similarity against HNSW indices.
  2. Sparse Lexical Retrieval: BM25 (Best Matching 25) algorithm scoring term frequency and inverse document frequency over an inverted token index.

Reciprocal Rank Fusion (RRF)

To merge results from dense and sparse search without manual score normalization, we apply Reciprocal Rank Fusion (RRF):

math/rrf-scoring.txt
TXT
RRF Score(d) = Σ [ 1 / (60 + rank_m(d)) ] for m in [dense, sparse]

Where rank_m(d) is the 1-indexed rank of document d in system m, and the constant 60 prevents top ranks from overwhelmingly dominating the blended score.


Cross-Encoder Neural Reranking

A bi-encoder (your standard embedding model) processes queries and documents independently: $\mathbf = f(\text)$, $\mathbf = f(\text)$. Because it cannot model cross-attention between individual query tokens and document tokens, its relevance scoring is relatively coarse.

A Cross-Encoder Reranker (such as Cohere Rerank or BGE-Reranker-Large) takes the query and document concatenated together: $(\text, \text) \to \text \in [0, 1]$. Full multi-head self-attention inspects every token relationship directly.

comparison/encoders.txt
TXT
Bi-Encoder (Retriever) Cross-Encoder (Reranker)
Query -> [Encoder] -> Vector \ (Query + Document)
[Cosine] ↓
Document-> [Encoder] -> Vector / [Full Cross-Attention]
↓
Latency: ~5ms per 10k items Relevance Score: [0.0 - 1.0]
Precision: Moderate Latency: ~25ms per 50 items
Precision: State-of-the-Art

The production pattern: Retrieve high-recall Top-50 candidates via Hybrid Search, then rerank down to Top-5 high-precision chunks using a Cross-Encoder.


Practical Next.js Implementation

Let's build a modular, type-safe RAG engine in TypeScript using the Next.js App Router and the Vercel AI SDK.

1. Document Chunking with Breadcrumbs

lib/rag/chunker.ts
TS
export interface Chunk {
id: string;
content: string;
metadata: {
source: string;
section: string;
tokenCount: number;
};
}
export function chunkMarkdownWithHeadings(content: string, source: string): Chunk[] {
const sections = content.split(/(?=^#{1,3}\s)/m);
const chunks: Chunk[] = [];
for (const [index, section] of sections.entries()) {
const trimmed = section.trim();
if (!trimmed) continue;
const firstLine = trimmed.split("\n")[0] || "";
const sectionTitle = firstLine.replace(/^#{1,3}\s*/, "").trim() || "Overview";
// Simple token estimation: ~4 chars per token
const estimatedTokens = Math.ceil(trimmed.length / 4);
chunks.push({
id: `${source}#section-${index}`,
content: trimmed,
metadata: {
source,
section: sectionTitle,
tokenCount: estimatedTokens,
},
});
}
return chunks;
}

2. Dense Embeddings Client

lib/rag/embeddings.ts
TS
import { embed, embedMany } from "ai";
import { openai } from "@ai-sdk/openai";
const embeddingModel = openai.embedding("text-embedding-3-small");
export async function generateEmbedding(text: string): Promise<number[]> {
const { embedding } = await embed({
model: embeddingModel,
value: text.replace(/\n/g, " "),
});
return embedding;
}
export async function generateBatchEmbeddings(texts: string[]): Promise<number[][]> {
const { embeddings } = await embedMany({
model: embeddingModel,
values: texts.map((t) => t.replace(/\n/g, " ")),
});
return embeddings;
}

3. Hybrid Retriever with Reciprocal Rank Fusion

lib/rag/retriever.ts
TS
export interface RetrievedDoc {
id: string;
content: string;
source: string;
score: number;
}
export function reciprocalRankFusion(
denseResults: { id: string; content: string; source: string }[],
sparseResults: { id: string; content: string; source: string }[],
k: number = 60
): RetrievedDoc[] {
const scoreMap = new Map<string, { doc: { id: string; content: string; source: string }; score: number }>();
// Process dense rankings
denseResults.forEach((doc, rank) => {
const current = scoreMap.get(doc.id) || { doc, score: 0 };
current.score += 1 / (k + rank + 1);
scoreMap.set(doc.id, current);
});
// Process sparse rankings
sparseResults.forEach((doc, rank) => {
const current = scoreMap.get(doc.id) || { doc, score: 0 };
current.score += 1 / (k + rank + 1);
scoreMap.set(doc.id, current);
});
return Array.from(scoreMap.values())
.map(({ doc, score }) => ({ ...doc, score }))
.sort((a, b) => b.score - a.score);
}

4. Streaming Route Handler with Grounding Guardrails

app/api/rag/query/route.ts
TS
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";
import { generateEmbedding } from "@/lib/rag/embeddings";
export const maxDuration = 30;
export async function POST(req: Request) {
const { query } = await req.json();
if (!query || typeof query !== "string") {
return new Response(JSON.stringify({ error: "Invalid query parameter" }), { status: 400 });
}
// 1. Generate query embedding
const queryVector = await generateEmbedding(query);
// 2. Fetch context chunks from vector DB (mocked for brevity)
const contextChunks = [
{
id: "doc-1",
section: "Authentication",
content: "All session tokens expire after 7 days of inactivity. Tokens use Ed25519 signatures.",
},
{
id: "doc-2",
section: "Rate Limits",
content: "Default rate limit is 100 requests per minute per tenant IP address.",
},
];
// 3. Assemble prompt with strict boundary isolation
const formattedContext = contextChunks
.map((chunk, i) => `[Source ${i + 1}: ${chunk.section}]\n${chunk.content}`)
.join("\n\n");
const systemPrompt = `You are a technical knowledge assistant.
Use ONLY the provided context blocks to answer the user query.
If the answer cannot be determined strictly from the context, respond:
"I do not have sufficient information in the knowledge base to answer this question."
Always cite the source number using brackets like [Source 1].`;
const result = streamText({
model: openai("gpt-4o"),
system: systemPrompt,
messages: [
{ role: "user", content: `Context:\n${formattedContext}\n\nQuestion: ${query}` },
],
});
return result.toDataStreamResponse();
}

Context Construction & Prompt Design

Even with accurate retrieval, a poor prompt can cause the model to ignore context or hallucinate. Use these strict prompt design principles:

  1. Context Envelope Isolation: Delimit context using markdown code fences or clear XML tags (<context>...</context>). This reduces susceptibility to indirect prompt injection embedded within ingested documents.
  2. Defensive Fallback Directives: Explicitly instruct the model to state its inability to answer rather than speculating when context is sparse.
  3. Citation Synthesizer: Force inline bracket citations (e.g. [1], [Doc A]).
prompts/rag-grounding.txt
TXT
<system_instruction>
You are an enterprise technical support specialist.
Answer the user's inquiry based exclusively on the facts contained within the <context> tags below.
Do NOT extrapolate, infer unstated assumptions, or apply outside parametric knowledge.
For every claim you assert, append the corresponding reference tag [doc_X].
</system_instruction>
<context>
[doc_1]: The internal VPN requires client certificates provisioned through Vault.
[doc_2]: Staging environments are teardown-automated daily at 02:00 UTC.
</context>

Evaluating RAG Systems: The RAG Triad

Traditional software testing relies on deterministic unit assertions (expect(result).toBe(true)). RAG applications require continuous automated probabilistic evaluations across the RAG Triad:

diagrams/rag-triad.txt
TXT
┌──────────────────┐
│ User Query │
└────────┬─────────┘
│
Context Relevance (Recall & Precision)
│
↓
┌────────────────────────────────────────────────────────┐
│ Retrieved Context │
└─────────────────────────────┬──────────────────────────┘
│
Faithfulness (Groundedness / No Lies)
│
↓
┌────────────────────────────────────────────────────────┐
│ Generated Response │
└─────────────────────────────┬──────────────────────────┘
│
Answer Relevance (Did we answer the query?)
│
↓
┌──────────────────┐
│ Verified User │
└──────────────────┘
  1. Context Relevance: Are the retrieved passages pertinent to the user question, or is $80%$ of the context window filled with irrelevant noise?
  2. Faithfulness (Groundedness): Can every factual assertion in the generated answer be directly inferred from the retrieved chunks? (Score: $1.0$ = zero hallucinations).
  3. Answer Relevance: Did the model actually answer what the user asked, rather than deflecting or generating tangential facts?

In CI/CD, run automated benchmarks with frameworks like Ragas or TruLens over a synthetic golden test suite on every deployment.


Common RAG Failure Modes

  1. Lost in the Middle: LLM transformer attention exhibits a U-shaped accuracy curve. Context placed in the middle of a $64\text$ token window is recalled with significantly lower fidelity than context placed at the very beginning or end.
    • Fix: Limit retrieved context to the Top-5 most relevant chunks using cross-encoder reranking.
  2. Outdated Index Drift: Data changes in PostgreSQL, but vector embeddings in your vector store are hours behind.
    • Fix: Implement real-time Change Data Capture (CDC) via Postgres WAL triggers or webhook invalidation.
  3. Chunk Boundary Truncation: A crucial explanation is split across chunk 4 and chunk 5, causing neither chunk alone to have sufficient semantic similarity.
    • Fix: Use semantic windowing where small chunks are retrieved, but the parent document section is injected into the LLM context.

Production Security, Latency, and Costs

  • Tenant Isolation (RBAC): In SaaS environments, vector queries must include strict metadata filtering (WHERE organization_id = 'org_123'). Never query vectors without tenant scope predicates.
  • Semantic Caching: Store prior user queries and their synthesized answers in Redis. When an incoming query has a cosine similarity exceeding 0.96 to a cached query vector, return the cached answer in under 20ms with zero LLM inference cost.
  • Observability: Trace each stage using OpenTelemetry. Log:
    1. Dense search latency (ms)
    2. Sparse search latency (ms)
    3. Rerank score delta
    4. Prompt token count vs. completion token count

When to Use RAG vs. When NOT to Use It

Use RAG When:

  • Knowledge updates frequently (documentation, policies, knowledge bases).
  • Auditable citations and provenance are non-negotiable requirements.
  • Different tenants have strict data access permissions.
  • You need high factual reliability without multi-thousand-dollar training runs.

Do NOT Use RAG When:

  • You need deep mathematical calculation or deterministic logic (use code or SQL engines).
  • The total document size is small enough to fit statically within a 128k prompt context window without retrieval overhead.
  • You need to alter the model's fundamental tone, voice, or linguistic register (use Fine-Tuning or System Prompt Engineering).

Related Reading

To see how RAG integrates into full-stack SaaS and multi-step streaming agent applications, check out our companion guides:


Summary Checklist for Production RAG

  • Ingestion pipeline uses Markdown AST / hierarchical breadcrumb chunking.
  • Vectors are $L_2$-normalized for fast dot-product similarity.
  • Hybrid search combines dense vector retrieval (HNSW) with BM25 lexical search.
  • Reciprocal Rank Fusion merges candidate lists without manual score weighting.
  • Cross-Encoder neural reranker filters Top-50 candidates down to Top-5 chunks.
  • Strict citation and grounding rules are enforced in the system prompt.
  • Tenant-level RBAC metadata filtering protects every vector search query.
  • Continuous RAG Triad evaluations guard CI/CD deployment pipelines.
Topics:#AI#RAG#Vector Databases#Embeddings#LLM#System Design