AI Engineering Reference/RAG & Knowledge Bases

RAG Fundamentals & Chunking

Retrieval pipeline, embedding models, chunking strategies, reranking, and the failure modes that make RAG systems useless.

3/5Overview: 30m

What RAG solves

LLMs know public internet text. They don't know your codebase, runbooks, or last week's ADR. Retrieval-Augmented Generation fetches relevant documents at query time and injects them into the prompt — grounding the model in facts you control.

User query → Embed query → Search vector DB → Retrieve top-k chunks → Inject chunks into prompt → LLM generates grounded answer

RAG is the default pattern for "chat with our docs" and "answer questions about our codebase." It's cheaper and faster to iterate than fine-tuning.

The RAG pipeline

StageOptionsKey decision
IngestParse PDF, MD, HTML, codePreserve structure (headings, code blocks)
ChunkFixed-size, semantic, recursiveChunk size vs retrieval precision
EmbedOpenAI, Cohere, open-source (e.g. nomic, bge)Quality vs cost vs latency
StorePinecone, Weaviate, pgvector, ChromaScale, filtering, hybrid search support
RetrieveCosine similarity, BM25, hybridPure semantic misses exact matches (API names)
RerankCohere reranker, cross-encoderImproves top-k at small latency cost
GenerateAny LLM with retrieved contextCite sources; reject if no relevant chunk found

Chunking: the make-or-break step

Bad chunking = bad RAG, regardless of embedding model quality.

StrategyHowBest for
Fixed-sizeSplit every N tokens with overlapSimple baseline; breaks mid-sentence
Paragraph/sectionSplit on \n\n or headingsDocs, wikis, markdown
RecursiveSplit on \n\n\n. → charLangChain default; decent general-purpose
Code-awareSplit on functions/classesSource code (preserve signatures)
Parent-childSmall chunks for search, large for contextBest of both: precise retrieval, rich context

Rules of thumb:

  • Chunks of 256–512 tokens for factual Q&A
  • Chunks of 512–1024 tokens for code (keep function bodies intact)
  • 10–20% overlap between chunks to avoid boundary splits
  • Include metadata (source file, section title, last-modified) for filtering and citation

Embedding model selection

Mid-2026 options:

ModelStrengthTrade-off
OpenAI text-embedding-3-largeStrong general qualityAPI cost, vendor lock-in
OpenAI text-embedding-3-smallGood enough for mostLower cost, slightly less precise
Open-source (bge, nomic)Self-hosted, no API costOps burden, may need fine-tuning for domain

Re-embed when you switch models — embeddings aren't interchangeable across model families.

Failure modes

FailureSymptomFix
Chunk too smallAnswer lacks contextIncrease chunk size or use parent-child
Chunk too largeIrrelevant filler dilutes answerDecrease size; add reranking
Stale indexAnswers reference deleted codeCI-triggered re-index on merge
Missing content"I don't know" for known topicsCheck ingest gaps; expand sources
Wrong chunk retrievedConfident wrong answerHybrid search; reranking; eval suite
No citationCan't verify answerRequire source attribution in prompt

Hybrid search

Pure vector search misses exact matches (function names, error codes, config keys). Combine:

Final score = α × semantic_similarity + (1-α) × BM25_keyword_score

Typical α = 0.7 for docs, 0.5 for code. Most production systems use hybrid.

When RAG beats alternatives

NeedRAGFine-tuningLong context
Q&A over docs✅ BestOverkillExpensive at scale
Code style/conventions⚠️ Partial✅ Better⚠️ Partial
Real-time data✅ Re-index❌ Stale❌ Cutoff
New product knowledge✅ Fast to updateSlow, expensiveManual paste

Interview framing

"RAG retrieves relevant chunks at query time and injects them into the prompt. The critical engineering decisions are chunking strategy, hybrid search, and eval — not embedding model selection. I'd build a 20-query eval set before tuning anything."

Senior signal: Explain parent-child chunking. Mention you'd re-index on every merge to main. Describe a RAG failure you diagnosed (wrong chunk retrieved) and how you'd fix it.

Further Reading

Hands-On Tasks (Optional)

Practical exercises — prompt drills, local MCP servers, or workflow design on paper. The goal is professional fluency, not model training.

  • Compare chunking strategies on one doc

    Take a 10-page internal doc. Chunk it three ways: fixed 512 tokens, paragraph-based, and heading-aware. Query each with 5 real questions. Score retrieval quality (did the right chunk appear in top-3?).

    30m