What this is
What breaks when embeddings go live?
Running embeddings in production means keeping an AI search system working after it goes live, when the AI model behind it gets upgraded or meets words it does not know. The system stores every document as an embedding, a list of numbers that stands for its meaning, placed by one AI model on its own map. A different AI model draws a different map, so its numbers mean nothing on the old one. Mix the two and the share of questions whose right page lands in the top three falls from 92% to 25% in a small test, and nothing crashes. The lesson covers changing the AI model safely and checking that it knows your company's words. It ends with the first question to ask about a wrong answer: was the right page ever found?
Why it matters: From the day an embedding index serves real traffic. The tell is a report that search "got weird" after an upgrade, or weeks spent tuning prompts for answers whose right page was never retrieved.
At a glance
Key takeaways
- Every embedding model has its own space. Documents and questions embedded by different models do not match, and if the two models have the same number of dimensions, nothing crashes: recall just falls.
- A blue/green migration changes the model without downtime: build a new index beside the old one, write new documents to both, re-embed the old ones, compare the two on a golden set, switch only if the new one is at least as good, and keep the old index for rollback.
- Re-embedding time and cost grow with total tokens (documents × tokens per document), so estimate the hours and dollars before starting.
- General models miss company jargon. A golden set built from resolved search or support logs measures the gap; keyword search and fine-tuning close it.
- When a RAG system answers wrongly, first ask whether the right document was retrieved. If not, fix retrieval; if it was, fix generation.
How it works, from scratch
Two mapmakers each draw a map of the same city on their own grid. On one map, square (3, 7) is the train station; on the other, (3, 7) is a park. Both maps are fine, but a position read off one means nothing on the other.
An embedding model is a mapmaker. It places every document and every question at a point on its own map, and search returns the documents whose points lie nearest the question's. That works only while the documents and the questions were placed by the same model.
Chapter 1
Every model has its own space
Embed the word "vpn" with two versions of the same toy model, both with 64 dimensions, and the two vectors have a cosine similarity of about 0.05, as if they were unrelated words.
To see what that does to search, take a golden set: questions whose right answers are known, here 12 questions over 20 documents. Embed the documents and the questions with the v1 model, and the right document is in the top 3 for 11 of the 12 questions (0.92). Keep the v1 documents but embed the questions with v2, and it is there for 3 of the 12 (0.25). Random ranking would score 0.15, since 3 of the 20 documents are shown. Nothing crashes and nothing reports an error.
A model with a different number of dimensions would at least fail loudly: a 128-number vector cannot be compared with a 64-number one. A model of the same size gives no such warning. The share of golden questions that have a right document in the top k is called hit@k:
The formula and its symbols
Symbols
| Symbol | Meaning here | Example |
|---|---|---|
| Q | the golden set of questions | 12 questions |
| |Q| | how many questions | 12 |
| q ∈ Q | each question in turn | |
| rel(q) | the documents that truly answer q | {it-004} |
| top_k(q) | the k documents search returned | 3 documents |
| ∩, ≠ ∅ | "they share at least one document" | |
| [ … ] | 1 if true, 0 if false | |
| hit@k | the share of questions with a right answer in the top k | 0 to 1 |
In words: the share of golden questions for which at least one right document appears among the top k results. (With one relevant document per question, as here, this equals recall@k.)
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
On the example: 11 hits out of 12 = 0.92 with matching models; 3 out of 12 = 0.25 with mixed models.
In Python:
def hit(rel_q, top_q):
# [rel(q) ∩ top_k(q) ≠ ∅]
return 1 if rel_q & top_q else 0
hit({"it-004"}, {"it-002", "it-004", "fin-001"}) # → 1
# matching models: 11 of the 12 questions
hits = [1] * 11 + [0]
# (1/|Q|) Σ over q in Q
round(sum(hits) / len(hits), 2) # → 0.92
# mixed models: 3 of the 12
hits = [1] * 3 + [0] * 9
round(sum(hits) / len(hits), 2) # → 0.25
Figure 1 · Chart
Recall@3 is 0.92 when documents and queries share a model, and falls to 0.25, near the 0.15 of random ranking, when v2 queries search v1 documents
This mix is the usual cause behind the report "we upgraded the embedding model and search got weird": a pipeline embedded new documents with the new model and left the old ones as they were. The defence is to tie every index to one model version and have it refuse vectors from any other.
In code: golden_recall embeds the documents with one model and the
questions with another and returns hit@k. VectorIndex is a flat index tied
to one model version. View source
Chapter 2
Changing the model: a blue/green migration
A new model therefore means re-embedding every document. So does a fine-tune, a change to how documents are split into chunks, or a bug fix in the text pipeline, because each one moves the points. The task is to re-embed a live index without taking search down and without ever serving documents and questions from different models.
A blue/green migration builds the new index beside the old one, while search keeps using the old one. From the first minute, every new document is written to both indexes (the dual write), so the new index never falls behind. A backfill then re-embeds the existing documents into the new index in batches that can restart where they stopped.
Before anything switches, a shadow comparison scores both indexes on the golden set, and the new one goes live only if it is at least as good. The switch is a pointer: the search service asks for "the live index", an alias that names the real one, and cutover repoints it. Elasticsearch and Qdrant both offer aliases that switch in one atomic step. The old index stays for a soak period, while the new one runs under real traffic, so rolling back means repointing the alias rather than rebuilding for hours.
Figure 2 · Diagram
stateDiagram-v2 [*] --> Live_v1 Live_v1 --> DualWrite: start v2 (empty index, new docs go to both) DualWrite --> Backfilled: backfill (re-embed old docs in batches) Backfilled --> Compared: shadow compare (recall on golden set) Compared --> Live_v2: cutover, only if v2 at least as good Compared --> Live_v1: refused, v2 is worse Live_v2 --> Live_v1: rollback (v1 index kept) Live_v2 --> [*]: retire v1 after a soak period
In code: each arrow of the diagram is one method: BlueGreenMigration.start,
BlueGreenMigration.add (the dual write), BlueGreenMigration.backfill,
BlueGreenMigration.shadow_compare, BlueGreenMigration.cutover and
BlueGreenMigration.rollback. View source
The backfill is the slow step, and its size is simple arithmetic. Say 50 million documents of about 500 tokens each, an embedding throughput of 1 million tokens per second across your workers, and a price of $0.02 per million tokens (replace all three with your own numbers):
The formula and its symbols
Symbols
| Symbol | Meaning here | Example |
|---|---|---|
| n | number of documents (or chunks) | 50,000,000 |
| t | average tokens per document | 500 |
| n · t | total tokens to embed | 25,000,000,000 |
| r | throughput, tokens per second | 1,000,000 |
| 3600 | seconds per hour | |
| p | price per million tokens | $0.02 |
In words: total tokens divided by throughput gives the time; total tokens in millions times the price gives the cost.
On the example: 25 × 10⁹ / (10⁶ × 3600) = 6.94 hours; 25,000 × $0.02 = $500.
In Python:
# documents, tokens per document
n, t = 50_000_000, 500
# tokens per second, dollars per million tokens
r, p = 1_000_000, 0.02
# total tokens
n * t # → 25000000000
# hours
round(n * t / (r * 3600), 2) # → 6.94
# dollars
round(n * t / 10**6 * p, 2) # → 500.0
Figure 3 · Chart
Re-embedding time and cost both grow in step with corpus size: ten times the documents, ten times the hours and the dollars
In code: reembed_estimate computes the tokens, hours and dollars for
your own n, t, r and p. View source
Chapter 3
Domain jargon: test on your own questions
The shadow comparison is only as good as the golden set behind it, and the questions in that set should be your users' own. Public leaderboards rank embedding models on public data. General models are trained mostly on web text, so a company's acronyms and product names are new words to them: "AP" for accounts payable, "T&E" for travel and expenses.
Four employee questions in company jargon show the gap: "ap aging report", "hotspot from a client site", "sso lockout" and "t-and-e submission deadline". The general toy model puts the right document first for 1 of 4. A version that has learned the four jargon words, standing in for a model fine-tuned on company pairs, puts it first for 4 of 4.
Figure 4 · Chart
On company jargon the general model buries three of the four right answers, while the tuned model ranks every one first
In code: rank_of_first_relevant finds where the right document lands
for one question under one model: the height of each bar.
DomainTunedEmbedder stands in for the fine-tuned model. View source
A golden set of your own questions is cheap, because search and support logs already hold one. A session in which someone clicked a document and the issue was resolved is a question paired with its answer. Keep the resolved sessions, merge questions that repeat, and a few hundred pairs make a golden set. Test candidate models on it. If none is good enough, add keyword search, which matches jargon by its spelling (Retrieval), and fine-tune on your own pairs (Training embedding models). A fine-tuned model draws a new map, so shipping it is another migration.
Figure 5 · Diagram
flowchart LR
L["Search & support logs"] --> F["Keep resolved sessions<br/>(the clicked doc answered it)"]
F --> N["Normalize and merge<br/>repeated questions"]
N --> G["Golden set: question → relevant docs<br/>(a few hundred is plenty)"]
G --> T["Test several models on your set"]
T --> D{Good enough?}
D -->|no| FT["Fine-tune on domain pairs,<br/>add hybrid search"]
D -->|yes| S[Ship, and keep the set for regressions]
FT --> T
In code: build_eval_set keeps only resolved sessions and merges
repeated questions. View source
Chapter 4
Measure retrieval separately from generation
A golden set measures search on its own. Most embedding indexes, though, feed a retrieval-augmented generation (RAG) system: search retrieves the top k documents, and a language model writes an answer from them. When the answer is wrong, one of the two halves failed. Think of an open-book exam: either the right page was not in the book you brought (a retrieval failure), or it was there and you misread it (a generation failure). Studying harder fixes the second, not the first.
Three answered questions, checked by hand, show both:
| Retrieved (top 3) | Truly relevant | Answer used | Verdict |
|---|---|---|---|
| it-002, fin-006, fin-001 | it-004 | it-002 | retrieval failure: it-004 was never found |
| hr-002, hr-001, hr-005 | hr-001 | hr-002 | generation failure: found but not used |
| it-001, it-002 | it-001 | it-001 | correct |
One question sorts every failure: was a right document in the retrieved top k? If not, no change to the prompt can help, and the fix is in retrieval: chunking, hybrid search, reranking or the embedding model. If it was there and the answer ignored it, the fix is in generation: the prompt, the order of the context, or fewer distracting chunks.
Figure 6 · Diagram
flowchart TD
A[Wrong answer] --> R{Was a relevant document<br/>in the retrieved top k?}
R -->|no| RF[Retrieval failure:<br/>fix chunking, hybrid search,<br/>reranking, the embedding model]
R -->|yes| G{Did the answer use it?}
G -->|no| GF[Generation failure:<br/>fix the prompt, context order,<br/>fewer distracting chunks]
G -->|yes| OK[Check the grader:<br/>the answer may be fine]
Only the retrieval half can be measured without a language model, which is why recall@k on the golden set is the first number to track. Retrieving more documents looks like a fix for retrieval failures, and the chart below shows what it does instead.
Figure 7 · Chart
Retrieving more documents turns some retrieval failures into generation failures, and the error-code question stays wrong at every k
In code: triage gives the verdict for one answered question, following
the flowchart above; triage_golden_set runs every golden question through
retrieval and the toy generator. View source
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1Q: You need to switch embedding models on a 50-million-document index. Plan the migration.Think it through, then reveal
Create a versioned index for the new model and dual-write new documents to both. Backfill by re-embedding existing documents in restartable batches (estimate: 50M × 500 tokens = 25B tokens; at 1M tokens/s that's about 7 hours). Compare recall on a golden set in shadow; cut over the live alias only if the new model is at least as good; keep the old index for fast rollback, then retire it.
Question 2Q: Why can't you compare vectors from two different embedding models?Think it through, then reveal
Each model defines its own coordinate system. Even with the same number of dimensions, the same text lands in unrelated places, so similarity between the two spaces is meaningless.
Question 3Q: A general embedding model performs poorly on a company's internal documents. What helps?Think it through, then reveal
Build a small eval set from real queries and the documents that resolved them, test several models on it, add hybrid (keyword + dense) search for exact terms, and fine-tune an embedding model on domain pairs with hard negatives if needed.
Question 4Q: Your RAG system gives confident wrong answers. What's your first diagnostic step?Think it through, then reveal
Split retrieval from generation: for failing questions, check whether a relevant document was in the retrieved top k. If not, it's retrieval (fix search); if yes, it's generation (fix prompt and context). Track recall@k on a labeled set continuously.
Primary sources
The papers behind this lesson
Showed that retrieval models trained on one domain often lose badly on others, which is why you evaluate on your own data.
The paperCompared embedding models across many tasks and found no single model wins everywhere.
The paperResearcher's shelf
Further reading
- Es et al., RAGAS: Automated Evaluation of Retrieval Augmented Generation (2023): https://arxiv.org/abs/2309.15217
- Martin Fowler, BlueGreenDeployment: https://martinfowler.com/bliki/BlueGreenDeployment.html
- MTEB leaderboard: https://huggingface.co/spaces/mteb/leaderboard
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.