SysDesignAtlas

Embeddings

What a vector actually encodes, why cosine similarity is the metric, how dimensionality trades quality against cost, and the operational problem nobody plans for — re-embedding.

CoreMedium11 min readaiembeddingsvectorsretrieval
Confidence

#The idea

An embedding maps a piece of content — text, an image, a product — to a fixed-length vector of floats, arranged so that geometric closeness corresponds to semantic similarity.

   "how do I reset my password"     → [0.021, -0.14, 0.87, ...]
   "forgot my login credentials"    → [0.019, -0.13, 0.85, ...]   ← close
   "what is the capital of Peru"    → [-0.61, 0.44, -0.02, ...]   ← far

   No shared words between the first two. The vectors are
   close anyway, because they mean the same thing.

That last line is the entire value proposition. Keyword search cannot connect "reset password" to "forgot credentials"; embeddings can, because they were trained to.

#How they're trained

Nearly all modern text embeddings come from contrastive learning, which trains by comparison rather than by correct answers: show the model pairs that ought to end up close together and pairs that ought to end up far apart, and push the geometry until they do.

   For each anchor a with a known positive p and negatives n₁..nₖ:

     maximise    sim(a, p)
     minimise    sim(a, nᵢ)  for all i

   InfoNCE loss:

     L = −log [  exp(sim(a,p)/τ)                       ]
              [ ─────────────────────────────────────  ]
              [ exp(sim(a,p)/τ) + Σ exp(sim(a,nᵢ)/τ)   ]

   Positive pairs come from: question/answer, title/body,
   translation pairs, or two crops of the same image.

In words: the loss is small when the anchor scores much higher against its positive than against any negative, and large otherwise. τ is a temperature, as in sampling — smaller τ punishes near-misses more sharply.

#Similarity metrics

"Close together" needs a definition, and there are three in common use. The key distinction: cosine measures only the direction two vectors point, ignoring how long they are, while dot product and Euclidean distance both take length into account.

MetricFormulaBehaviour
Cosinea·b / (‖a‖‖b‖)Angle only; magnitude-invariant. The default
Dot producta·bAngle and magnitude; magnitude can encode importance or popularity
Euclidean (L2)‖a − b‖Distance in space

For normalised vectors — rescaled so every vector has length 1 (‖v‖ = 1) — all three are equivalent for ranking: sorting results by one gives exactly the same order as sorting by the others, since ‖a−b‖² = 2 − 2(a·b). Most embedding models emit normalised vectors precisely so that this holds and any index works.

Cosine is the default because embedding magnitude usually reflects nothing you care about — text length, token frequency — rather than semantic strength. Dot product is preferred in recommendation systems, where you want magnitude to encode popularity so that popular items rank higher for equally-relevant matches.

#Dimensionality

Typical text embeddings are 384 to 4,096 dimensions. The choice is a direct cost decision.

Matryoshka embeddings are the elegant answer. Train so that the first k dimensions are independently useful — truncating a 3,072-dim vector to its first 256 gives a valid, if slightly weaker, embedding. This enables a two-stage retrieval that gets most of the quality at a fraction of the cost:

   Stage 1:  search the 256-dim index over 100M docs → top 1,000
             (cheap: 12× less memory, 12× faster distance calcs)
   Stage 2:  re-rank those 1,000 with the full 3,072-dim vectors
             (exact, and only 1,000 comparisons)

   → near-full quality at a small fraction of the index cost

Quantizing the vectors themselves stacks on top: float32 → int8 is 4× smaller with small recall loss; binary embeddings (1 bit per dimension, compared by Hamming distance — the count of bits that differ) are 32× smaller and fast enough to compare against every stored vector directly, with no index. They're typically used as a first-stage filter.

#What embeddings are bad at

Understanding the failure modes matters more than understanding the successes, because the failures are what break production retrieval.

Negation. "Documents about cats" and "documents not about cats" embed close together. The word "not" barely moves the vector. This breaks a surprising number of real queries.

Exact identifiers. Order number SKU-99381, an error code, a person's name, a version string. These need lexical matching — matching the exact characters. Embeddings treat them as approximately-similar-looking strings, so SKU-99381 and SKU-99318 can land almost on top of each other. This is the single strongest argument for hybrid search — combining BM25 (classic keyword scoring) with dense retrieval (embedding search) — covered in retrieval architecture.

Numeric and temporal comparison. "Orders over $500" or "articles from last week" are filter predicates — yes/no conditions on a field like price > 500 — not similarity questions. An embedding has no reliable notion of "greater than", so these belong in metadata filters stored alongside the vectors.

Long documents. A single vector for a 50-page document averages everything into mush: a query matching one paragraph is drowned out by the other 49 pages. This is why chunking exists — splitting documents into passages of a few hundred tokens, each embedded separately — and why chunk size is one of the most consequential parameters in a retrieval system.

Domain shift. A model trained on web text will underperform on legal contracts, medical notes, or your internal jargon. Fine-tuning on in-domain pairs is usually the single largest available quality improvement.

#The operational problem: re-embedding

The part nobody plans for.

Embeddings from different models are not comparable. Not "slightly different" — completely incomparable, different spaces with no meaningful relationship. So upgrading your embedding model means re-embedding your entire corpus.

   100M documents, 500 tokens each = 50B tokens to re-embed

     compute cost:    substantial, though embedding models
                      are far cheaper than generative ones
     wall-clock:      hours to days on a GPU fleet
     index rebuild:   HNSW construction on 100M vectors is
                      itself hours
     storage:         you need BOTH indexes live during the
                      migration → double the memory

   And you cannot mix: a query embedded with the new model
   cannot search vectors embedded with the old one.

Design for this from the start:

  • Version every vector with the model that produced it.
  • Build the new index alongside the old, dual-write new documents to both.
  • Shadow-evaluate the new index on real traffic before switching: run real queries against it in the background and compare its results with the old index's, without showing them to users.
  • Cut over atomically per index, never per document. A half-migrated index would hold vectors from two incomparable models, and every search over it would be partly meaningless.
  • Keep the source text, always. If you only stored vectors, you cannot re-embed at all — a genuinely unrecoverable position that people do get into.

#Beyond text

The same machinery, different encoders:

  • Multimodal (CLIP-style) — image and text encoders trained into a shared space, so you can search images with a text query. The joint space is the whole trick.
  • Code — trained on code/docstring pairs; substantially better than text models on code search.
  • Two-tower recommendation — user and item encoders trained so that a user's vector is close to items they engaged with. Retrieval becomes nearest-neighbour search, which is what makes candidate generation over 100M items feasible. See ranking and recsys.

#Check yourself

What does an embedding do?Show answer
Maps content to a fixed-length vector so geometric closeness means semantic similarity — connecting "reset password" to "forgot credentials" with no shared words.
How are embedding models trained, and why do batch sizes matter?Show answer
Contrastive learning (InfoNCE): pull positives close, push negatives apart. Every other example in a batch is a free negative, so bigger batches — and mined hard negatives — sharpen quality.
Cosine, dot product or Euclidean?Show answer
Cosine (angle only) is the default; dot product lets magnitude encode popularity in recommenders. For normalised vectors all three rank identically.
Why can't you compare similarity scores across models?Show answer
Each model occupies a different region of its space, so thresholds like "above 0.8" break on upgrade. Calibrate per model on your data, or use rank instead of score.
What does dimensionality cost, and how do you cut it?Show answer
100M docs at 3,072 dims is ~1.2 TB before index overhead versus ~154 GB at 384. Matryoshka embeddings let you search a truncated index then re-rank with full vectors; int8 is 4× smaller, binary 32×.
Name four things embeddings are bad at.Show answer
Negation, exact identifiers (codes, SKUs, names), numeric and date filters, long documents averaged into mush — plus domain shift, often fixed by in-domain fine-tuning.
Why is re-embedding the hard operational problem?Show answer
Vectors from different models are incomparable, so an upgrade means re-embedding the whole corpus, rebuilding the index and running two indexes at once.
What must you design in from day one for re-embedding?Show answer
Keep the source text, store the model version per vector, build the new index alongside the old with dual writes, shadow-evaluate, then cut over atomically per index.

#What to carry forward

  • Embeddings put semantic similarity into geometry; contrastive training with in-batch negatives is how.
  • Cosine is the default; scores are not comparable across models, so calibrate thresholds per model.
  • Dimensionality is a direct infrastructure cost. Matryoshka truncation plus quantization is how you cut it.
  • They fail on negation, exact identifiers, numeric filters, and long documents — which is why hybrid search exists.
  • Re-embedding is the hard operational problem. Keep the source text, version every vector, plan for dual indexes.
00:00
/ 11m