Embeddings and Retrieval in RAG, what breaks in production and how to fix it
Embeddings and retrieval look simple in tutorials. Learn what changes in production: chunking, hybrid search, reranking, evaluation and hidden operational costs.
Most tutorials describe embeddings and retrieval in one line: an embedding model turns text into vectors, and a retriever finds the vectors closest to the question. That is true, and it is also the reason many first RAG systems disappoint. Retrieval-augmented generation (RAG), the approach introduced in the 2020 paper by Lewis and colleagues, lets a language model answer using passages fetched from an external document store instead of relying only on what it memorised during training. The generation step can only be as good as the passages it receives.
This article is for readers who already know what a transformer and a vector are. It covers what changes when you move from a notebook demo to a production system, and what to do when retrieval is not good enough.
Why the textbook definition of embeddings and retrieval is incomplete
An embedding model maps a piece of text to a fixed-length vector so that texts with similar meaning land close together. Retrieval then means finding the stored vectors nearest to the query vector, usually by cosine similarity (the cosine of the angle between two vectors, which ignores their length).
The catch is the word similar. The model decides what similar means during training, and that definition may not match what your users need. Two texts can be about the same topic without one answering the other. Take the query 'What is the refund window for annual plans?'. A chunk describing refunds for monthly plans may score higher than the correct chunk, because both talk about subscription refunds in nearly the same words. The vector says the topics match. It does not say the answer is there.
Discipline is not willpower or robot-like routine. Learn how the brain builds habits, why boredom appears, and how to keep a routine that keeps working.
·10 min read
Keep this gap in mind through the rest of the article. Almost every production fix is a way of closing the distance between topically similar and actually useful.
Chunking: the decision that quietly limits everything
You cannot embed a whole manual as one vector, so you split documents into chunks, the pieces that are embedded and retrieved individually. Chunking looks like a preprocessing detail, but it sets a ceiling on retrieval quality.
Chunks that are too large produce a vector that averages many topics. It matches everything weakly and nothing strongly.
Chunks that are too small lose context. A chunk reading 'It must be filed within 30 days' is useless if you cannot tell what 'it' refers to.
A practical starting point is 200 to 500 tokens with 10 to 15 percent overlap, then tune using your own evaluation results. A few habits help more than any fixed number:
Split on document structure (headings, paragraphs, list items) rather than a raw character count.
Prepend the document title and section heading to each chunk before embedding, so the vector carries its own context.
Consider small-to-big retrieval: embed small chunks for precise matching, but pass the larger parent section to the model.
Check how tables, code blocks and PDFs were extracted. Broken extraction produces broken chunks, and no embedding model can repair that.
Before tuning anything else, read 20 random chunks yourself. This takes ten minutes and often finds the biggest problem in the system.
Queries and documents are different kinds of text
A user query is short, often incomplete and written as a question. A document passage is long, formal and written as a statement. This query-document asymmetry means the best match for a question is not always the passage that looks most like it.
Some embedding models handle this with separate prefixes. The E5 family, for example, expects query: before questions and passage: before documents. Forgetting the prefix does not raise an error. It only lowers quality, which is why this bug survives so long. Always read the model card and use the similarity metric and normalisation it was trained with.
You can also change the query itself:
Query rewriting turns a chat message like 'what about the second one?' into a standalone question using the conversation history. Without this, multi-turn RAG fails badly.
HyDE (Hypothetical Document Embeddings) asks a language model to write a fake answer first, then embeds that answer instead of the question, because an answer looks more like a stored passage.
Multilingual and code-mixed queries matter a lot for Indian users. A student typing in Hinglish may not match English documents unless you use a multilingual embedding model and test with real queries.
Why pure vector search is not enough
Embeddings compress meaning, and compression loses detail. Exact strings such as error codes, product IDs, section numbers, names and abbreviations are often blurred. A query for 'Section 420' or 'ERR_5012' may return vaguely related text instead of the exact match.
BM25, a classic keyword ranking function that scores documents by how often query words appear in them and how rare those words are overall, handles this well. The BEIR benchmark, which tests retrieval models across many domains they were not trained on, showed that BM25 remains a strong baseline and that dense models do not always beat it on new domains.
That is why most production systems use hybrid search: run keyword and vector search together and merge the results. A common merging method is Reciprocal Rank Fusion (RRF), which gives each document a score of 1 divided by (k + its rank) in each list, then adds the scores. A value of k around 60 is a common default. RRF only uses ranks, so you do not need to compare a BM25 score with a cosine score, which live on different scales.
Two-stage retrieval: recall first, precision second
A bi-encoder, the usual embedding setup, encodes the query and each document separately. This is fast because document vectors are computed once and stored. The cost is that the model never sees the query and the passage together.
A cross-encoder reads the query and one passage together in a single pass and outputs a relevance score. It is far more accurate but too slow to run over a whole corpus. So the standard pattern is:
Retrieve a wide set, for example the top 50 to 100 chunks, with hybrid search. The goal here is recall.
Rerank those candidates with a cross-encoder and keep the top 5 to 10. The goal here is precision.
Reranking adds latency, so measure it. Also resist the urge to send more chunks to the model. The paper Lost in the Middle found that language models use information near the start and end of a long context better than information in the middle. More context can make answers worse.
Approximate search has a price
Exact nearest-neighbour search compares the query with every stored vector, which gets expensive as the corpus grows. Production systems use approximate nearest neighbour (ANN) indexes that trade a little accuracy for a lot of speed. Two common types are HNSW, a layered graph that you walk toward the query (original paper), and IVF, which groups vectors into clusters and searches only the nearest few. Libraries such as FAISS, an open-source similarity search library from Meta, implement both.
Three practical points:
Index parameters (for HNSW, the search-time breadth setting called efSearch) trade recall against latency and memory. Do not leave them at defaults without measuring.
Measure ANN recall by comparing its results with exact brute-force search on a sample of queries. If ANN misses 10 percent of the true neighbours, no amount of prompt work will recover them.
Metadata filters, such as 'only documents from 2024', can interact badly with ANN. Depending on whether the filter is applied before or after the vector search, you may get fewer than k results or lower recall. Test filtered queries separately.
When retrieval is bad: debug in this order
Saying 'the RAG is bad' is not a diagnosis. Work through these steps.
Separate retrieval from generation. For a failing question, check whether the chunk containing the answer appears in the retrieved top k. If it does not, you have a retrieval problem. If it does, the problem is in the prompt, the context order or the model.
Build a golden set. Collect 50 to 200 real user questions and mark which chunks answer each one. Track recall@k (how often a correct chunk is in the top k), MRR (mean reciprocal rank, which rewards putting the correct chunk higher) and nDCG (which scores the whole ranking, giving more credit to relevant results near the top).
Sort failures into categories. Typical ones are: the answer was split across two chunks, the user's wording differs from the document's, the query was ambiguous, the answer is not in the corpus at all, or outdated and duplicate documents crowded out the right one.
Fix the cheapest thing first. A sensible order is chunking and metadata, then hybrid search, then a reranker, then query rewriting, and fine-tuning the embedding model last.
Fine-tuning needs pairs of queries and matching passages. If you lack real ones, you can generate synthetic questions from your chunks with a language model, but review a sample by hand. Remember that changing the embedding model means re-embedding the whole corpus.
Challenges that books rarely mention
Embedding model versioning. Vectors from different models, or even different versions of one model, are not comparable. Store the model name and version with every vector, and plan to build a new index alongside the old one and switch over, rather than editing in place.
Stale and duplicate content. Near-duplicate chunks can fill the entire top k with the same information. Deduplicate at ingestion, and have a process to remove or update documents when the source changes.
Access control. If different users may see different documents, enforce permissions inside the retrieval step. Telling the model in the prompt to ignore restricted text is not a security measure.
Cost and latency. Every query may involve an embedding call, two searches, a reranker and a generation call, and the index must sit in memory. Higher-dimensional vectors cost more to store and search. Some models are trained with Matryoshka representation learning (paper), which lets you shorten the vector with limited quality loss.
Leaderboards are not your data. The MTEB leaderboard compares embedding models across many tasks, which makes it a good place to shortlist candidates. Your documents, language and queries are different, so only your own golden set can tell you which model works.
Questions with no answer. Vector search always returns something, even when nothing relevant exists. Use a score threshold or a reranker score cut-off, and let the system say it does not know.
Monitoring. Log each query, the retrieved chunk IDs and user feedback. Real queries will look different from the ones you imagined, and they are the best source for improving your golden set.
Treat retrieval as a search system, not a plugin
The main lesson is that embeddings are one component in a search system, not the whole system. Production quality comes from careful chunking, hybrid retrieval, reranking, honest evaluation and operational discipline around versions, permissions and cost.
If you are building a RAG application, create your golden set before you tune anything. Then change one thing at a time and watch recall@k. That habit will teach you more about retrieval than any tutorial, and it is the same habit that separates a demo from a system people can trust.