rumblr Work in progressWIP

● The AI Primer · Lesson 31 · Part 4: embeddings and search

Embeddings in production

Operating embeddings: model changes, jargon, and finding what broke

This lesson covers What breaks when an embedding index serves real traffic, and how to measure retrieval on its own

Members · open during launch 21 min7 figures and diagrams

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

  1. 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.
  2. 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.
  3. Re-embedding time and cost grow with total tokens (documents × tokens per document), so estimate the hours and dollars before starting.
  4. 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.
  5. 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

v1 docs, v1 queries v2 docs, v2 queries v1 docs, v2 queries 0.0 0.2 0.4 0.6 0.8 1.0 recall@3 on the golden set Mixing two models' vectors fails silently 0.92 0.92 0.25 random ranking (3 of 20)

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

Reading it: each bar is recall@3 on the golden set. The first two bars use one model for both documents and questions, v1 then v2, and both find 11 of the 12 answers. The third bar searches v1 documents with v2 questions and falls to 0.25, just above the dashed line at 0.15 that random ranking would score.

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

Reading it: follow the states from the top. Users are served by v1 until the cutover arrow. Two arrows leave the comparison: cutover, and a refusal that keeps v1 live. A smaller candidate model that scores 0.58 on the golden set, against the live index's 0.92, takes the refusal arrow. After cutover, the arrow back to v1 is the rollback, and v1 is retired only when the soak period ends.

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

1 0 5 1 0 6 1 0 7 1 0 8 1 0 9 documents (500 tokens each, log scale) 1 0 − 3 1 0 − 2 1 0 − 1 1 0 0 1 0 1 1 0 2 1 0 3 hours (log scale) Time to re-embed 100,000 tokens/s 1,000,000 tokens/s 10,000,000 tokens/s 1 0 5 1 0 6 1 0 7 1 0 8 1 0 9 documents (500 tokens each, log scale) 1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 dollars (log scale) Cost to re-embed $0.01 per million tokens $0.02 per million tokens $0.13 per million tokens

Re-embedding time and cost both grow in step with corpus size: ten times the documents, ten times the hours and the dollars

Reading it: corpus size runs along the bottom on a log scale. The left panel shows hours at three throughputs, the right panel dollars at three prices. Every line is straight: ten times the documents takes ten times the hours and the dollars. At these prices the money is small. The hours, the provider's rate limits and paying to store two indexes during the migration are what need planning.

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

ap aging report hotspot from a client site sso lockout t-and-e submission deadline 0 2 4 6 8 10 12 14 rank of the right document (1 is best) Company jargon: general vs. tuned model general model tuned on the jargon

On company jargon the general model buries three of the four right answers, while the tuned model ranks every one first

Reading it: each pair of bars is one jargon question, and a bar's height is the rank of the right document, so shorter is better and 1 is best. The general model ranks three of the four answers far down; the tuned model ranks every one first. The general model gets "sso lockout" right only because it knows one of its words, "lockout".

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

Reading it: the set comes from real usage, not invention. The loop at the bottom repeats until a model is good enough, and whatever ships, the set stays: every later change is checked against it.

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

Reading it: start at the wrong answer and take the first question. The last branch matters too: if the answer did use the right document, check the grader before changing anything, because 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

1 3 5 documents retrieved (k) 0 2 4 6 8 10 12 golden questions Which half failed? (generator uses the top document) correct generation failure retrieval failure

Retrieving more documents turns some retrieval failures into generation failures, and the error-code question stays wrong at every k

Reading it: each bar is the 12 golden questions at one k (1, 3 and 5 documents retrieved), answered by a toy generator that always uses the top document. Green is correct, red a retrieval failure, orange a generation failure. As k grows, red turns orange and green stays at 10: the right page is now in the book, but the reader still opens the wrong one. The error-code question ("what does ERR-4012 mean") is one of them. Its answer ranks fourth, so it is a retrieval failure until k = 5 and a generation failure after, because the top document is still the wrong one. Dense vectors blur exact identifiers like ERR-4012; keyword search puts that page first.

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

Thakur et al., BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models (2021)

Showed that retrieval models trained on one domain often lose badly on others, which is why you evaluate on your own data.

The paper
Muennighoff et al., MTEB: Massive Text Embedding Benchmark (2022)

Compared embedding models across many tasks and found no single model wins everywhere.

The paper

Researcher'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.