I'm Gopi Gugan, a software engineer who builds AI features with FastAPI, Postgres/pgvector, and React/TypeScript. I write about what I actually do at work — the parts that work, the parts that break, and the parts where a human still has to stay in the loop. You can find more of my writing at gopigugan.ca.

When a RAG app gives a bad answer, my first instinct used to be to blame the model. Most of the time, that was wrong. The model can only work with what retrieval hands it, and if retrieval hands it the wrong chunks, no amount of prompt engineering saves the answer. Here's how I tune vector search so my RAG app retrieves the right chunks in the first place.

Start by measuring retrieval, not answers

Before I tune anything, I build a small test set: 20 or 30 real questions, each with the chunks I expect retrieval to return. I score retrieval separately from the final answer, because they fail in different ways.

  • Missed the right chunk entirely — the information is in the database, but search never surfaced it. That's a chunking or embedding problem.
  • Found it, but buried it — the right chunk ranked 8th and only the top 3 made it into the prompt. That's a ranking or cutoff problem.
  • Found lookalike chunks — chunks that share words with the question but don't answer it. That's a relevance problem.

This split matters because each failure has a different fix. If I only look at final answers, I end up tweaking prompts to compensate for retrieval — and that never really works.

Chunk size is a tradeoff, not a setting to guess

My first RAG app chopped documents into fixed 500-token chunks. It worked okay for short docs and terribly for everything else — a chunk would split a paragraph in half, and the model would get the second half of an idea with no beginning.

What I do now:

  • Chunk by structure first. Split on headings, paragraphs, and list boundaries before falling back to a size limit. A chunk that respects the document's own structure almost always retrieves better than one that cuts mid-sentence.
  • Overlap a little. A 10–15% overlap between neighbouring chunks catches ideas that straddle a boundary. More than that just bloats the index with near-duplicates.
  • Store the metadata. Every chunk keeps its source document, section heading, and position. When the model answers, I show the user where the answer came from — and when retrieval goes wrong, that metadata tells me exactly which chunk failed and why.

There is no universal best chunk size. A chunk that works for API docs is too small for a legal contract. I pick a size, run my test set, and change it only when the failures point at chunking.

Tune the index, then tune the query

In Postgres with pgvector, the HNSW index is where most of the performance and recall lives. The defaults are fine for a demo; for real data I set them deliberately:

-- An HNSW index tuned for recall over raw speed CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64); -- At query time, a higher ef_search trades a little latency for better recall SET hnsw.ef_search = 100; SELECT id, title, section, 1 - (embedding <=> $1) AS similarity FROM documents WHERE 1 - (embedding <=> $1) > 0.6 ORDER BY embedding <=> $1 LIMIT 5; 

A few things I learned the hard way:

  • Pick the right distance. Cosine similarity is my default for text embeddings. Inner product and L2 distance give different rankings on the same data, so I test with the metric my embedding model was actually trained for.
  • Use a similarity floor. A LIMIT 5 with no threshold returns five chunks even when none of them are relevant. A floor like 0.6 means the model sometimes gets fewer chunks — and that's better than getting five confident-sounding wrong ones.
  • Check recall at the index level. HNSW is approximate by design. If ef_search is too low, the index skips good neighbours to save time. When my test set shows the right chunk exists but wasn't returned, I raise ef_search before I touch anything else.

Add keyword search when embeddings go blind

Pure vector search has a blind spot: exact terms. Ask "What is the REFUND_WINDOW_DAYS constant?" and embeddings may return chunks about refunds in general while missing the one chunk that literally contains the constant name.

That's why I run hybrid search — vector similarity plus Postgres full-text search — and combine the scores. The keyword side catches names, codes, and IDs; the vector side catches meaning. Neither is enough on its own for a real codebase or docs set.

My rule is simple: if the question contains a proper noun, a code identifier, or a number, keyword search earns its place in the pipeline. If it's a conceptual question ("how do I handle expired tokens?"), embeddings do the heavy lifting.

Know when retrieval isn't the problem

This is the honest part. Not every bad RAG answer is a search problem:

  • If the right chunk is retrieved and the answer is still wrong, that's a generation problem — prompt, model, or context length.
  • If the information simply isn't in the documents, that's a content problem. No retrieval trick finds knowledge that was never written down, and a good system says "I don't know" instead of stitching together a plausible answer from unrelated chunks.
  • If the test questions are vague, that's a product problem. "Tell me about the API" will retrieve a bit of everything and answer none of it well. A clarifying question beats a longer context window.

Tuning vector search is worth doing precisely because it narrows the problem down. Once retrieval is solid, the remaining failures are honest failures — and those are the ones I can actually fix.

What I'd do this week

Pick one RAG feature you own and build the test set: 20 questions, the chunks each one should retrieve, and a note on which ones fail today. Don't change the model, the prompt, or the chunk size yet. Just look at what retrieval is actually returning. In my experience, that one afternoon of measurement tells you more about your system than a month of tweaking settings blind.