AppZyra AppZyra
AI Systems • Published: 2026-02-15 • 13 min read

Building Resilient Retrieval-Augmented Generation (RAG) Pipelines with Vector Search

An architectural blueprint for enterprise RAG systems. Hybrid BM25 keyword + dense vector embeddings, late chunking, Cohere reranking, and semantic caching to slash latency.

Vaibhave — Principal Engineer & Founder

Architectural Key Takeaways

  • Naive vector RAG fails in real-world scenarios due to chunk context fragmentation, semantic drift, and hallucinated source citations.
  • Hybrid retrieval combining sparse lexical search (BM25) and dense embeddings (OpenAI text-embedding-3) prevents catastrophic keyword omissions.
  • Two-stage retrieval—fetching 50 candidates and reranking top 5 with a Cross-Encoder—improves context precision by over 38%.
  • Semantic caching with embedding distance thresholds drops recurring LLM API query costs by up to 72%.
Table of Contents
  1. Why Naive RAG Fails in Production
  2. Context-Aware Semantic Chunking & Late Chunking
  3. Hybrid Retrieval: Sparse BM25 + Dense pgvector
  4. Cross-Encoder Reranking with Cohere Rerank 3
  5. Semantic Caching for Sub-50ms Responses

Why Naive RAG Fails in Production

Retrieval-Augmented Generation (RAG) is the dominant architecture for grounding Large Language Models (LLMs) on private enterprise datasets. However, prototype implementations—such as those built with basic LangChain scripts—frequently degrade in production.

Naive RAG chops documents into fixed 500-token chunks with arbitrary character overlaps, converts them to vector embeddings, performs top-k cosine similarity search, and pipes the result directly into an LLM prompt. In practice, this causes context loss (tables split mid-row), keyword blindness (part numbers and acronyms missed by dense embeddings), and irrelevant hallucinated responses.

Context-Aware Semantic Chunking & Late Chunking

Fixed-token windowing is destructive to semantic meaning. A table of specifications or a multi-step code snippet cannot be split arbitrarily across two vectors. In advanced RAG architectures, document ingestion parses Markdown AST trees, preserving structural sections, headers, and bulleted lists as coherent units.

Furthermore, 'Late Chunking' computes token embeddings across the entire document context first, and then averages token vectors into chunk boundaries. This embeds global document context into individual chunk representations.

Listing 1: AST-Aware Markdown Chunking Pipeline in Node.js typescript
import { remark } from 'remark';
import { visit } from 'unist-util-visit';

interface DocumentChunk {
  content: string;
  metadata: {
    headingLevel: number;
    parentSection: string;
    tokenEstimate: number;
  };
}

export async function parseMarkdownAST(rawMarkdown: string): Promise<DocumentChunk[]> {
  const tree = remark.parse(rawMarkdown);
  const chunks: DocumentChunk[] = [];
  let currentSection = 'Introduction';

  visit(tree, (node: any) => {
    if (node.type === 'heading') {
      currentSection = node.children.map((c: any) => c.value).join('');
    } else if (node.type === 'paragraph' || node.type === 'table') {
      const text = rawMarkdown.slice(node.position.start.offset, node.position.end.offset);
      if (text.length > 50) {
        chunks.push({
          content: text,
          metadata: {
            headingLevel: node.depth || 2,
            parentSection: currentSection,
            tokenEstimate: Math.ceil(text.length / 4)
          }
        });
      }
    }
  });

  return chunks;
}

Hybrid Retrieval: Sparse BM25 + Dense pgvector

Dense vector embeddings excel at semantic concept matching (e.g. associating 'cardiac incident' with 'heart attack'). However, they struggle with exact lexical matches: serial numbers, customer account IDs, error codes, and niche technical jargon.

A production retrieval engine must employ Hybrid Search: querying PostgreSQL full-text search (BM25 or tsvector) alongside pgvector (HNSW cosine similarity), normalized via Reciprocal Rank Fusion (RRF).

Table 1: Retrieval Accuracy Comparison (Lexical vs Dense vs Hybrid RRF)
Query CategoryPure BM25 (Lexical)Dense Vector (Cosine)Hybrid RRF (AppZyra Stack)
Conceptual Inquiries ('how do I sync data?')58.2% Recall91.4% Recall94.8% Recall
Specific Identifiers ('error code 0x80040154')96.1% Recall34.2% Recall (Severe drop)98.5% Recall
Multi-hop Technical Documentation62.0% Recall78.5% Recall89.2% Recall
Average Context Precision @ 564.1%76.8%91.3%

Cross-Encoder Reranking with Cohere Rerank 3

Bi-encoders (embedding models) compute vector representations independently for query and document. While extremely fast to search over millions of records via HNSW indexes, bi-encoders miss subtle relational nuances.

Cross-encoders take both the query and the candidate document simultaneously, allowing full cross-attention across all tokens. By retrieving 50 coarse candidates via hybrid search and passing them through a Cross-Encoder reranker, context precision jumps dramatically.

Listing 2: Two-Stage Hybrid Retrieval & Cross-Encoder Rerank Workflow typescript
import { CohereClient } from 'cohere-ai';

const cohere = new CohereClient({ token: process.env.COHERE_API_KEY });

export async function rerankCandidates(
  query: string,
  candidates: Array<{ text: string; id: string }>
): Promise<Array<{ id: string; relevanceScore: number }>> {
  const reranked = await cohere.rerank({
    model: 'rerank-english-v3.0',
    query: query,
    documents: candidates.map(c => c.text),
    topN: 5,
    returnDocuments: false
  });

  return reranked.results.map(r => ({
    id: candidates[r.index].id,
    relevanceScore: r.relevanceScore
  }));
}

Semantic Caching for Sub-50ms Responses

In enterprise applications, 30% to 50% of user queries represent semantic permutations of the same core questions. By calculating embedding cosine similarity against an in-memory Redis vector store of historical queries, previously validated answers can be returned in under 40ms without invoking expensive downstream LLM generation passes.

This dual-tier retrieval and caching architecture slashes LLM operational token budgets while dramatically elevating real-world response times.

V
Authored by
Vaibhave
Principal Engineer & Founder
Principal Systems Architect at AppZyra. Specializing in high-throughput React Native, local-first SQLite runtimes, and distributed state synchronization.