Let's talk.

Whether it's a project, a role, or you just want to say hi, my inbox is open.

kadhar.mfn@gmail.com
AboutExperienceProjectsWritingResearchFree guidesFree ebookToolsGames

© 2026 Kadharmoideen Fadurudeen. Made with care.

kadhar.
AboutExperienceProjectsWritingResearchFree guides
Tools
Say hello
Back to Blog
AI Engineering
December 3, 2026
13 min read

RAG from Scratch: Chunking, Embeddings, Retrieval and Why It Fails

When you actually need RAG, how to chunk documents so answers stay whole, embeddings without the maths, hybrid search and reranking, prompt assembly, and the usual reasons RAG gives wrong answers. With an interactive retrieval demo.

A language model knows a lot about the world and nothing about your company.

It hasn't read your help centre, your internal wiki or last week's policy change. Ask it about any of those and it will either say it doesn't know or, worse, give a confident answer that sounds right and isn't.

Retrieval-augmented generation, RAG for short, is the standard fix. The idea is simple: before the model answers, look up the few pieces of your documents that are relevant to the question and put them in the prompt. The model answers from those, not from memory. The idea really is that simple. Getting good answers out of it is where the work is, and almost all of that work is in the retrieval part.

First, do you even need RAG?

Context windows are big now. Current frontier models take hundreds of thousands of tokens or more in one prompt, which is a lot of documentation. If everything the model needs fits comfortably, you can just send all of it, and use prompt caching so you aren't paying full price for the same text on every request. No chunking, no search, nothing to get wrong.

RAG earns its complexity when one of these is true:

  • The content is too big. Thousands of documents, a whole wiki, years of tickets.
  • It changes often. Re-indexing one changed document is cheaper than rebuilding a giant prompt.
  • Different users can see different things. RAG lets you filter by permission before anything reaches the model. Sending everything to everyone can't.
  • Cost or speed matters at volume. Even cached, a huge prompt on every request adds up. A few relevant paragraphs are cheaper and faster.

The whole pipeline in two halves

RAG has two parts that run at different times.

Ahead of time: indexing

  1. Load your documents and clean them up.
  2. Split them into chunks.
  3. Turn each chunk into an embedding.
  4. Store chunk, embedding and metadata together.

On every question: answering

  1. Turn the question into an embedding.
  2. Find the most similar chunks.
  3. Put the best few into the prompt.
  4. Let the model answer from them, with sources.

If the right chunk doesn't make it into the prompt, nothing after that can save the answer. So most of this article is about getting step 2 of indexing and step 2 of answering right.

Chunking: the decision that matters most

You can't search a whole document and paste it in, so you cut it into pieces. How you cut decides what the model can ever see together. Cut too small and an answer gets split across two chunks. Cut too big and each chunk is about several things, so it matches lots of questions loosely and none of them well.

Try it. The first question needs two facts from the same paragraph: deleted files are kept for 30 days, and after that not even support can get them back. Switch the chunking and see when the model gets both.

Question

How the docs are chunked

12 chunks from a four-section help centre. The top 3 go to the model.

  1. #1 · chunk 6 · score 3.2

    be recovered by anyone, even by support. Changing your plan. You can change your plan

  2. #2 · chunk 1 · score 1.9

    Plans. The Basic plan stores 100 GB and keeps old versions of each file for

  3. #3 · chunk 3 · score 1.9

    Both plans include unlimited devices. Deleted files. Deleted files go to the Trash and stay

No single retrieved chunk holds the whole answer. The model gets half the facts, and may guess the rest.

Word-overlap scoring stands in for embeddings so this runs in your browser. The chunking lesson is the same.

With tiny fixed chunks, the “30 days” and the “even by support” land in different pieces, and the model is left to fill the gap. Splitting on the document's own sections keeps each idea whole. Overlap helps fixed-size chunking too, because a sentence cut at the end of one chunk appears again at the start of the next.

What works in practice:

  • Split on structure first. Headings, sections, list items, FAQ entries. Authors already grouped related ideas for you.
  • Then cap the size. If a section is very long, split it further on paragraphs, with a little overlap.
  • Give each chunk its context. Prepend the document title and section heading. “30 days” means nothing alone. “Help centre › Deleted files: 30 days” does.
  • Keep metadata. Source URL, last updated date, product, and who's allowed to see it. You'll need all of it later.

Embeddings, without the maths

An embedding model turns a piece of text into a long list of numbers. Texts that mean similar things get similar numbers. “How do I cancel my subscription?” and “Stop my plan from renewing” share almost no words, but their embeddings sit close together. That's the whole point: search by meaning instead of by exact wording.

A few practical rules:

  • Use the same embedding model for documents and questions. Numbers from two different models aren't comparable.
  • Changing the model means re-embedding everything. Store which model and version made each embedding, so you can migrate cleanly.
  • Pick on your own data. Benchmark scores are a starting point. Twenty real questions from your users tell you more.

Where to store the vectors

Start with the database you already have. If that's Postgres, the pgvector extension adds a vector column type and similarity search, and keeps chunks, metadata and permissions next to the rest of your data, where you can filter them with normal SQL. Hosted Postgres platforms like Supabase support it out of the box.

Dedicated vector databases such as Pinecone, Qdrant, Weaviate or Chroma make sense at very large scale, or when you want their built-in extras. Moving later is mostly a re-index, so it's not a decision you need to get perfect on day one.

Retrieval that actually finds the answer

Plain vector search is a good start. These three upgrades fix most of what it misses.

1. Hybrid search

Embeddings are great with meaning and weak with exact strings: error codes, product SKUs, names, version numbers. Classic keyword search (BM25) is the opposite. Run both and merge the results. Most search engines and vector stores support this, and it's often the single biggest improvement.

2. Reranking

Fetch more candidates than you need, say the top 30, then use a reranker model to score each one against the question more carefully and keep the best five. Search is fast but rough. Reranking is slower but sharper, and you only run it on a handful.

3. Filters before similarity

Use the metadata. Only this customer's documents, only the current product version, only pages this user is allowed to read. Permission filtering has to happen here, in the query. Telling the model to ignore documents it shouldn't see is not a security control.

Putting it in the prompt

Once you have the chunks, the prompt does three jobs: give the model the sources, tell it to stick to them, and make it show where each claim came from.

const chunks = await search(question, { userId, limit: 5 })

const sources = chunks
  .map((c, i) => `<source id="${i + 1}" url="${c.url}">\n${c.text}\n</source>`)
  .join("\n")

const prompt = `Answer the question using only the sources below.
Cite sources like [1]. If the sources don't contain the answer,
say you don't know. Don't guess.

${sources}

Question: ${question}`

The “say you don't know” line matters more than it looks. Without it, a model handed five loosely related chunks will usually stitch together something plausible. With it, a retrieval miss becomes an honest “I couldn't find that”, which users forgive far more easily than a wrong answer. Citations also let you and your users check the answer against the source.

Why RAG gives wrong answers

When an answer is wrong, find which of these it is before you touch the prompt or model.

Confident answer that's half right

Likely cause: The answer was split across chunks and only one was retrieved.

Fix: Chunk by section, add overlap, attach headings.

Misses questions with codes, names or versions

Likely cause: Embeddings blur exact strings.

Fix: Add keyword search (hybrid).

Right document, wrong part of it

Likely cause: Chunks are too big and cover several topics.

Fix: Smaller, single-topic chunks, plus reranking.

Outdated answer

Likely cause: Old and new versions of a page are both indexed.

Fix: Re-index on change, delete old chunks, filter by date or version.

Makes something up

Likely cause: Nothing relevant was retrieved and the prompt didn't allow “I don't know”.

Fix: Require citations and an explicit don't-know answer.

Shows a user something they shouldn't see

Likely cause: Permissions were left to the prompt.

Fix: Filter by permission in the search query itself.

What you seeLikely causeFix
Confident answer that's half rightThe answer was split across chunks and only one was retrieved.Chunk by section, add overlap, attach headings.
Misses questions with codes, names or versionsEmbeddings blur exact strings.Add keyword search (hybrid).
Right document, wrong part of itChunks are too big and cover several topics.Smaller, single-topic chunks, plus reranking.
Outdated answerOld and new versions of a page are both indexed.Re-index on change, delete old chunks, filter by date or version.
Makes something upNothing relevant was retrieved and the prompt didn't allow “I don't know”.Require citations and an explicit don't-know answer.
Shows a user something they shouldn't seePermissions were left to the prompt.Filter by permission in the search query itself.

Test retrieval on its own

The most useful habit in RAG is measuring retrieval separately from the final answer. Write down 30 to 50 real questions, and for each one note which chunk or document holds the answer. Then run only the search and check: is the right chunk in the top five? The share of questions where it is, called recall at 5, is your retrieval score.

It's fast, cheap, involves no model calls, and turns arguments like “should we use bigger chunks?” into a number you can compare. Run it again every time you change chunking, embeddings or search settings. Only once retrieval is good is it worth tuning the prompt.

Frequently Asked Questions

What is RAG in simple terms?

Retrieval-augmented generation means looking up the parts of your own documents that are relevant to a question, and pasting them into the prompt so the model answers from them instead of from memory.

Do I still need RAG with large context windows?

Not always. If all your knowledge fits comfortably in the context window and doesn't change much, sending it all with prompt caching is often simpler and just as good. RAG is still the right tool when the content is too large, changes often, or different users may only see different documents.

What chunk size should I use for RAG?

There's no universal number. Start by splitting on the document's own structure, like headings and sections, and keep each chunk to one idea. Then test with real questions and check whether the chunk holding each answer is retrieved.

Do I need a vector database for RAG?

Not to start. If you already run Postgres, the pgvector extension handles vector search well for most apps. A dedicated vector database becomes worth it at very large scale or when you need features your current database doesn't have.

Why does my RAG system give wrong answers?

Most often the right text was never retrieved: chunks split the answer in half, the search missed exact terms like product codes, or the answer wasn't in the documents at all. Check retrieval on its own before changing the prompt or the model.

The short version

If it all fits in the context window, skip RAG and use caching. If it doesn't, chunk along the document's own structure with titles attached, start with pgvector in the database you have, add keyword search and a reranker, filter by permission in the query, and tell the model to cite its sources and admit when it doesn't know. Then measure retrieval on its own with real questions, because that's where RAG usually goes wrong. Choosing the model that writes the final answer is covered in how to choose the right AI model.

PreviousPrompt Caching Explained: Cut Your LLM Bill by Reordering Your PromptNextEvals for LLM Features: How to Know Your Prompt Change Didn't Break Anything

Continue Reading

Explore more articles on software engineering and technology

AI Engineering

Making AI Features Feel Fast: Streaming, Latency and UX

Time to first token vs output speed, streaming from the model to the browser in Next.js, the UX details that make streaming feel polished, and the changes that genuinely cut latency. With an interactive race between waiting and streaming.

11 min read
Read
AI Engineering

Prompt Injection and AI Security: A Practical Guide for App Developers

Why LLMs can't reliably tell instructions from data, how indirect injection hides in emails and web pages, the lethal trifecta, and the layered defences that hold: fewer capabilities, real confirmation, output control, quarantine and testing. With an interactive attack demo.

13 min read
Read
AI Engineering

Structured Output and Tool Calling: Getting Reliable JSON from LLMs

Prompt-only vs JSON mode vs structured outputs, how Claude, OpenAI and Gemini do it, schema design that helps the model, the validation you still need, and how tool calling works under the hood. With an interactive demo of what each layer catches.

12 min read
Read