🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Embedding System Design

AI System DesignEmbedding System ArchitectuređŸŸĸ Free Lesson

Embedding System Design

Module 15 - Building Production Embedding Pipelines

What You'll Learn

  • 1Compare embedding models on dimensions, token limit, storage cost, and retrieval quality rather than leaderboard rank alone
  • 2Write the InfoNCE objective and explain where hard negative mining changes the gradient
  • 3Size the vector payload for a corpus and pick the dimensionality from a memory budget
  • 4Estimate embedding throughput and cost per million vectors for batch and streaming paths

Why This Matters

Embeddings are the foundation of semantic search, recommendations, RAG, and anomaly detection. Choosing the right model, training strategy, and infrastructure directly impacts downstream task performance. A well-designed embedding system handles scale, latency, and continuous improvement.

The choices are quantifiable. Moving from a 384 dimension MiniLM to a 3,072 dimension API model multiplies storage, index size, and distance cost by exactly 8, and on 10 million documents that is 15.4 GB versus 122.9 GB of float32 vectors. Quality gains rarely scale that fast, so the design question is always how many dimensions you can afford for how much recall.


System Architecture Overview

Embedding System ArchitectureData SourcesText, Images, Audio, CodePreprocessingClean, Tokenize, AugmentEmbedding ModelEncode -> VectorVector StoreIndex, Search, ServeEmbedding Models+- OpenAI text-embedding-3-large| 3072 dims, best quality+- Cohere embed-v3| 1024 dims, multi-lingual+- BGE-large-en-v1.5| 1024 dims, open-source+- E5-large-v2| 1024 dims, instruction-tuned+- Jina embeddings v2| 768 dims, Matryoshka+- Sentence-Transformers 384-1024 dims, customizableTraining Strategies+- Contrastive Learning| InfoNCE, Triplet loss+- Hard Negative Mining| Mine difficult negatives+- Knowledge Distillation| Teacher -> Student models+- Domain Adaptation| Fine-tune on domain data+- Multi-task Training Combine retrieval, clusteringLoss: InfoNCE, Triplet, MarginMulti-Modal Embeddings+- CLIP (OpenAI)| Image and Text alignment+- SigLIP| Sigmoid loss, scalable+- ImageBind (Meta)| 6 modalities unified+- Cohere Embed v3| Text + Images+- Custom multi-modal Fusion, early vs. lateUse: cross-modal search, QAEmbedding Pipeline+- Ingestion: Batch process, streaming updates, incremental sync+- Embedding: Model serving, batching, caching, rate limiting+- Storage: Vector DB upsert, metadata sync, versioning+- Serving: Query embedding, search, re-ranking, filteringEvaluation MetricsMTEB Benchmark - Recall@K - NDCG - Clustering quality - Classification accuracyPerformance TuningBatch encoding - GPU inference - ONNX optimization - Quantization - Caching

Embedding Model Selection

Embedding models vary by dimensions, max tokens, cost, and performance tier. OpenAI's text-embedding-3-large produces 3072-dim vectors with best quality, while open-source models like BGE-large (1024 dims) and E5-large (1024 dims) offer zero-cost alternatives. The embedding service handles both local models (SentenceTransformers) and API-based models, with batch encoding for throughput and instruction-prefixed queries for retrieval-specific embedding.

ModelDimsMax tokensStorage per 10M docsQuality tier
text-embedding-3-large3,0728,191122.9 GBHighest
text-embedding-3-small1,5368,19161.4 GBHigh
BGE-large-en-v1.51,02451240.9 GBHigh, self-hosted
E5-large-v21,02451240.9 GBHigh, instruction-tuned
all-MiniLM-L6-v238425615.4 GBAdequate, cheapest

Storage is dimensions x 4 bytes x documents, so every doubling of dimension is a doubling of index RAM, distance work, and network egress for the same 10 million documents.


Similarity Metrics

Nearly every text retriever ranks by cosine similarity between the query vector and the document vector :

Cosine ranges from -1 to 1 but for normalized embeddings it collapses to the dot product, which is why most services L2-normalize at export time and let the index use an inner-product metric. Forcing a dot-product model through an unnormalized cosine index is a common recall leak: the magnitude information the model trained with gets discarded at query time.

Training uses the InfoNCE contrastive objective over a batch of pairs, where is cosine similarity scaled by temperature :

A temperature of 0.02 sharpens the softmax so the hardest negative dominates the gradient, and a batch of 64 therefore supplies 63 negatives per anchor. Hard negative mining matters more than batch size: drawing negatives from the top 50 results of a pretrained retriever raises MTEB retrieval by 3 to 6 points over random in-batch negatives at the same compute.


Training Embeddings

Domain-specific embeddings are trained using contrastive learning with SentenceTransformers. Training pairs (query, positive document) are fed through a DataLoader with InfoNCE or Contrastive loss. Hard negative mining improves quality by selecting difficult negatives from the top-k results of a pretrained model - randomly sampling from the top-50 to avoid false negatives. Knowledge distillation transfers quality from a large teacher model to a smaller student.


Embedding Pipeline

Production embedding pipelines handle batch ingestion (embedding documents in chunks of 128 and upserting to a vector store), cached search (checking an embedding cache before computing query embeddings), and parallel batch search across multiple queries. The pipeline supports incremental sync for streaming updates and integrates with vector stores for indexing and metadata management.


Serving Capacity and Cost

Batch encoding is the lever that turns a slow model into a fast service. A model processing batches of documents in seconds runs at:

BGE-large on one A100 takes about 85 ms for a batch of 64 documents at 128 tokens, which is 753 documents per second. Encoding a 10 million document corpus therefore takes 10,000,000 / 753 = 13,280 seconds, or 3.7 hours of one GPU. That is the number you put in the migration plan, and it is why a dimension change is a scheduled re-index rather than a config edit.

Price follows the same rate:

At USD 3.50 per hour and 753 documents per second, one million embeddings costs USD 1.29 in GPU time, and a 10 million document re-embed costs USD 12.90. API pricing at roughly USD 0.13 per million tokens is cheaper for small batches and much more expensive at 10 million documents of 500 tokens each, so cross the two curves before you commit.

Query-side latency is a different regime: a single 8 token query at batch 1 takes about 4 ms on the same GPU, which is small next to the 40 ms search and 1,800 ms generation that follow it in a RAG path. Embedding rarely is the tail; uncached batch ingestion is where the budget actually goes.


Matryoshka Embeddings

Matryoshka embeddings (from Jina, OpenAI) support truncating the first N dimensions while preserving most quality. This enables multi-stage retrieval: use 256 dims for fast screening, then 1024 dims for precise ranking - reducing cost and latency. The model is trained to be self-contained at each dimension level.


Common Mistakes

Picking a model from the MTEB rank alone

Fix: Check dimensions and token limit first: 3,072 dims costs 8x the storage of 384 dims and the 512 token limit truncates most product descriptions.

Indexing unnormalized vectors under a cosine metric

Fix: L2-normalize at export, otherwise the magnitude your model trained with is silently thrown away at query time.

Swapping the embedding model without re-embedding

Fix: Vectors from two models do not share a space; build a shadow index, re-embed everything, then cut over atomically.

Best Practices

  • Use Matryoshka truncation to screen at 256 dimensions and re-rank at 1,024, cutting index reads by 4x for about 1 point of recall
  • Mine hard negatives from the top 50 results of the current retriever and refresh them after every model release
  • Track cache hit rate on query embeddings, since repeated queries should never reach the model

Key Takeaways

  • Storage is dims x 4 bytes x documents: 10M docs cost 15.4 GB at 384 dims and 122.9 GB at 3,072 dims
  • InfoNCE at temperature 0.02 with batch 64 gives 63 negatives per anchor, and hard negatives add 3 to 6 MTEB points
  • One A100 encodes BGE-large at 753 docs/s, so a 10M document re-embed is 3.7 hours and USD 12.90 of GPU time
  • Query embedding is about 4 ms and is rarely the tail; uncached batch ingestion is where the budget goes

Frequently Asked Questions

Should I normalize embeddings before indexing?

Yes, if the model was trained with a cosine objective. Unit length vectors turn cosine into a plain dot product, letting the index skip the two norms at query time and use an inner-product metric with identical results. The one exception is a model trained for magnitude-sensitive similarity, where normalizing discards signal the loss function deliberately used.

Why do queries and documents need different prefixes?

Retrieval training uses asymmetric inputs: the query encoder is taught to place a short question near the passage that answers it, and a shared prefix like "query: " or "passage: " tells the model which role it is encoding. Omitting the prefix at inference on an instruction-tuned model like E5 typically costs 5 to 15 recall points, because the model is asked to do a job it was never shown during training.

How often do I need to re-embed after a model change?

Every time, in full. There is no partial migration, because a new model defines a new vector space and mixing two spaces in one index corrupts every neighbour relationship. The safe path is a shadow index, a full re-embed (10 million documents is about 3.7 hours on one A100), a recall@10 comparison against the old index on a fixed query set, then an atomic pointer swap.

Interview Questions

Q1: How do you choose between embedding models?

Start from the constraint, not the leaderboard. Filter by token limit against your real document length, then by dimensions against your RAM budget, then compare recall@10 on 100 to 200 labeled queries from your own domain. A 1,024 dimension open model fine-tuned on your data usually beats a 3,072 dimension general model at half the storage.

Q2: How do you handle embedding drift over time?

Log a sample of production query vectors and compare them to the training distribution with a KS test or PSI per dimension. Version every index by model id, re-embed stale partitions on a schedule, and always A/B a model upgrade against a shadow index before cutover so a recall regression shows up before users do.

Q3: How do you evaluate embedding quality?

Use retrieval metrics (recall@10, NDCG) on your own labeled set as the primary gate, MTEB as a sanity check, clustering silhouette or NMI if you also cluster, and correlation with human similarity judgments when labels are scarce. Offline metrics must move together; if accuracy rises while recall@10 falls, the label set is wrong.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement