Labs › ai-foundations

Build Your Own Embedding Pipeline

Build an embedding pipeline from single-model serving to dynamic batching with LRU cache to model versioning with drift detection — measuring what batching really buys (6x on CPU, 12x on an Apple GPU for short texts) and making the zero-downtime upgrade path concrete.

python 3.12 advanced ~8h build · ~2h read ~740 LoC (v3)
v0: Single-Model Embedding Serverv1: Dynamic Batching + LRU Cachev2: Model Versioning + Drift Detection
☕ Java/Spring integration included service client

Why this lab exists

Every RAG system, every semantic search, every recommendation engine begins with the same operation: convert text to a vector. That operation is embedding. Understanding embedding at the implementation level — not just calling openai.embeddings.create() — means understanding why batching multiplies throughput (and by how much on your hardware), why L2 normalization matters for ANN indexes, and why swapping embedding models without re-indexing is a silent correctness bug.

You’ve read that embeddings are dense representations. You’ve used them through an API. But until you’ve implemented the batching queue and timed the forward pass at batch=1 vs batch=32, until you’ve built the LRU cache and seen its hit rate swing from 10% to 90% with nothing but the popularity of the requests, until you’ve measured cosine drift between model versions and understood what it means for your vector index — you don’t know it.

This lab builds an embedding pipeline from the ground up: a single-model HTTP server, then dynamic batching with an LRU cache, then model versioning with drift detection. Each stage addresses a concrete limitation of the previous one, measured in numbers.

What we’re building

A Python embedding pipeline implemented across three stages. Each stage is a targeted fix for a measured limitation.

We build:

  • SingleModelServer (v0): load all-MiniLM-L6-v2, L2-normalize embeddings, serve over FastAPI
  • BatchingQueue + EmbeddingWorker (v1): dynamic batching — collect for 5ms or 32 texts, whichever fires first
  • EmbeddingCache (v1): SHA-256-keyed LRU cache with configurable max size
  • ModelRegistry (v2): hold multiple model versions simultaneously with alias routing
  • EmbeddingDrift (v2): compare model versions — matched-pair cosine for same-model checks, neighbour overlap across models, and a gate on which versions can share an index
  • PinningPolicy (v2): pin callers to a version during gradual migrations

We explicitly skip:

  • ANN indexes (FAISS, Weaviate) — covered in the Vector Index lab; our pipeline produces the vectors that go into those indexes
  • Document chunking — covered in the RAG lab; this lab focuses on the embedding step itself
  • GPU inference — CUDA support falls out of using PyTorch via sentence-transformers; covered in What the Toy Misses
  • Persistent model registry — our registry is in-memory; production would use a model registry like MLflow or Hugging Face Hub

Mental model

An embedding pipeline has three concerns that scale at different rates:

Throughput — how many texts can you embed per second? The bottleneck is the transformer forward pass, and a single-text call wastes most of it: fixed per-call overhead (tokenizer, Python, kernel launches) dominates when the matrices are tiny. On an M1 Ultra CPU, all-MiniLM-L6-v2 takes 8.3 ms for one short text and 46 ms for 32 — the batch is 5.5x slower per call but carries 32x the texts, so throughput rises 6x. The longer the texts, the less there is to amortize: for 256-token chunks the gain is about 4x.

Freshness — when do cached embeddings go stale? Embeddings are deterministic: the same text always produces the same vector from the same model. Cache invalidation is by model version, not by time. When you upgrade the model, all cached embeddings from the old model become stale.

Compatibility — can you swap models without re-indexing? No. Each model embeds into its own vector space, so query vectors from model-v2 can’t be searched against an index built with model-v1. Even two models from the same family disagree a lot: on this lab’s 434 probe texts, MiniLM-L6 and MiniLM-L12 embeddings of the same text have an average cosine distance of 0.49, and a third of each text’s 10 nearest neighbours change between them. What you can measure is how much retrieval will change, which tells you how carefully to evaluate the new model before switching.

                v0: Request → embed() → L2-normalize → return
                ─────────────────────────────────────────────
  text(s) ──► SingleModelServer.embed()
                │
                ▼
              model.encode(texts)   ← forward pass (CPU: 8 ms for 1 short text, 46 ms for 32)
                │
                ▼
              L2-normalize          ← cosine sim = dot product after this
                │
                ▼
              float32 (N, 384)

                v1: Batching queue + LRU cache
                ──────────────────────────────
  text ──► EmbeddingCache.get()
             │
             ├─[hit]──► return cached embedding
             │
             └─[miss]─► BatchingQueue.put() → Future
                              │
                         EmbeddingWorker (background thread)
                              │
                         drain() — waits 5ms or 32 items
                              │
                         model.encode(batch)
                              │
                         resolve each Future, update cache

                v2: Model registry + drift gate
                ────────────────────────────────
  request ──► PinningRegistry.resolve(caller_id)
                │
                ▼
              ModelRegistry.embed(texts, version="stable")
                              │
                         (or "canary" once its shadow index is built)

Prerequisites

  • Python 3.12
  • Familiarity with NumPy array operations (@ matmul, linalg.norm, einsum)
  • Basic understanding of transformers — what a forward pass is, what an embedding is
  • Python threading basics — threading.Thread, concurrent.futures.Future

Stage-by-stage build

Stage 0 Single-Model Embedding Server ~180 LoC ›
  • Load all-MiniLM-L6-v2 with SentenceTransformer(name)
  • Implement encode(model, texts) — returns L2-normalized float32 (N, 384)
  • Verify: norms = np.linalg.norm(embeddings, axis=1) are all 1.0
  • Verify: cosine_similarity(text, text) == 1.0 for identical inputs
  • Wire into FastAPI: POST /embed, GET /health, GET /model-info

The key insight of v0 is L2 normalization. After normalization, every embedding has unit length: np.linalg.norm(embedding) == 1.0. This single property collapses cosine similarity to a dot product:

cosine_similarity(a, b) = (a · b) / (|a| * |b|) = a · b

Because |a| = |b| = 1 after normalization, the denominator disappears. This matters enormously for ANN indexes: FAISS’s IndexFlatIP (inner product) gives exact cosine similarity for unit vectors. Any index configured for inner-product / dot-product distance has the same requirement and fails silently if vectors aren’t normalized: it ranks by inner product, so longer vectors win and you get wrong nearest neighbours.

The normalization itself is three lines:

def _l2_normalize(embeddings: np.ndarray) -> np.ndarray:
    norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
    norms = np.where(norms == 0, 1.0, norms)  # guard against zero vectors
    return (embeddings / norms).astype(np.float32)

The zero-vector guard is important: if sentence-transformers ever returns an all-zeros embedding (it can for empty strings in some configurations), dividing by zero produces NaN. NaN embeddings silently corrupt ANN indexes.

Why sentence-transformers?

SentenceTransformer("all-MiniLM-L6-v2") downloads the model on first call and caches it in ~/.cache/huggingface/. It wraps HuggingFace Transformers and handles tokenization, batching, pooling, and (optionally) normalization. We do normalization explicitly to make it visible.

FastAPI wiring:

The server exposes three endpoints:

  • POST /embed — body: {"texts": ["...", "..."]} → returns {"embeddings": [[...]], "dimension": 384}
  • GET /health — returns model name and loaded status
  • GET /model-info — returns name and dimension

The v0 limitation is throughput: single-item requests call model.encode() once per text. Measured on the M1 Ultra CPU with short texts (~46 tokens), that’s 120 texts/sec; the same code with 32 texts per call does 695 texts/sec. On the Apple GPU (MPS, which sentence-transformers picks by default on a Mac) it’s 160 vs 1,930 texts/sec. V1 gets there without asking clients to batch.

Stage 1 Dynamic Batching + LRU Cache ~280 LoC ›
  • Implement BatchingQueue: put(text) returns a Future; drain() waits 5ms or 32 items
  • Implement EmbeddingWorker: background thread calls model.encode(batch), resolves futures
  • Implement EmbeddingCache: SHA-256(text) key, OrderedDict for LRU, max 10,000 entries
  • Wrap in BatchedEmbeddingServer.embed(): check cache, enqueue misses, await futures
  • Verify: batch=32 throughput measurably higher than single-item

The core idea of dynamic batching: don’t call model.encode() per request. Collect requests until either 32 are waiting or 5ms has elapsed, then encode the whole batch at once.

Why a thread, not asyncio?

sentence-transformers releases the Python GIL during the forward pass (PyTorch’s C extension does this). A real OS thread running the forward pass is truly parallel with the asyncio event loop handling new HTTP requests. With asyncio.to_thread(), you’d lose the batching window — each call would immediately dispatch to a thread pool instead of waiting to be grouped.

class EmbeddingWorker:
    def _run(self):
        while not self._stop_event.is_set():
            batch = self._queue.drain()   # blocks up to 100ms for first item
            if not batch:
                continue
            texts = [req.text for req in batch]
            embeddings = encode(self._server.model, texts)
            for i, req in enumerate(batch):
                req.future.set_result(embeddings[i])

The drain() logic:

drain() blocks until at least one item arrives (up to 100ms), then collects additional items non-blocking until max_batch_size or max_wait_ms expires:

def drain(self) -> list[_PendingRequest]:
    batch = []
    deadline = None
    try:
        first = self._queue.get(timeout=0.1)  # block for first item
        batch.append(first)
        deadline = time.monotonic() + (self.max_wait_ms / 1000.0)
    except queue.Empty:
        return batch
    while len(batch) < self.max_batch_size:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            break
        try:
            item = self._queue.get(timeout=remaining)
            batch.append(item)
        except queue.Empty:
            break
    return batch

SHA-256 cache key:

A production RAG system embeds document chunks of ~2,000 characters. As raw dict keys, 10,000 cached chunks would hold ~20 MB of key text next to ~15 MB of vectors (10,000 × 384 × 4 bytes); at a million entries that’s ~2 GB of keys. A SHA-256 hex digest is 64 characters regardless of text length. Collision probability for 10M cached texts: about n²/2^257 ≈ 4 × 10^-64 (birthday bound on 2^256 outputs). Not a concern in practice.

@staticmethod
def _key(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

LRU eviction:

collections.OrderedDict maintains insertion order. Moving an accessed key to the end (.move_to_end(key)) and always evicting from the front (popitem(last=False)) implements LRU in O(1) per operation — no sorted data structure required.

Throughput comparison (measured, short texts, scripts/bench.py):

CPU (16 threads)MPS (Apple GPU)
v0, 1 text per call120 texts/s (8.3 ms)160 texts/s (6.3 ms)
v0, 32 texts per call695 texts/s (46 ms)1,930 texts/s (16.6 ms)
v1, 32 concurrent callers, 1 text each697 texts/s, p50 45 ms1,579 texts/s, p50 19 ms
v1, 1 caller62 texts/s, p50 16 ms56 texts/s, p50 17 ms
v1, cache hit~300,000 texts/s (3.3 µs)same (no model call)

With enough concurrent callers, the queue forms full batches of 32 and v1 matches explicit batching on CPU (82% of it on MPS). With a single caller there is nothing to batch, and v1 is slower than v0: every request waits out the 5 ms window plus a thread hand-off, 7.5 ms (CPU) to 11.7 ms (MPS) on top of the model call. Dynamic batching is a throughput tool for concurrent traffic, not a free win.

For chunk-length texts (~256 tokens, the model’s maximum) the gains shrink: CPU goes from 35 to 112 texts/s at batch 32 (4.3x) and peaks around batch 8; MPS from 112 to 648 texts/s (5.0x).

Stage 2 Model Versioning + Drift Detection ~280 LoC ›
  • Implement ModelRegistry: register_model(version, name), get_model(version), list_versions()
  • Implement EmbeddingDrift.measure_drift(texts, v_a, v_b) -> avg cosine distance (same-model check)
  • Implement EmbeddingDrift.neighbour_overlap(texts, v_a, v_b, k) -> fraction of shared nearest neighbours
  • Implement EmbeddingDrift.is_compatible(v_a, v_b, probe_texts, threshold=0.9) -> can both share one index?
  • Implement PinningRegistry: pin(caller_id, version, until), resolve(caller_id, default)
  • Wire into VersionedEmbeddingServer with caller_id -> version resolution

The failure mode v2 prevents: you upgrade the embedding model, embeddings look correct in isolation, but your ANN index returns wrong results because the query embedding and the stored document embeddings are from different vector spaces.

Why different models produce incompatible vectors:

Each model learns its own embedding space during training. Nothing forces coordinate 17 of one model to mean what coordinate 17 means in another, even when both output 384 dimensions. Models that share training lineage end up partly aligned: on our 434 probe texts, all-MiniLM-L6-v2 and all-MiniLM-L12-v2 embeddings of the same text have an average cosine distance of 0.49, against 0.92 for unrelated text pairs. That’s well short of interchangeable. Models with different dimensions (MiniLM’s 384 vs all-mpnet-base-v2’s 768) can’t be compared vector-to-vector at all.

Measuring drift:

def measure_drift(self, texts, version_a, version_b) -> float:
    emb_a = self._registry.embed(texts, version=version_a)
    emb_b = self._registry.embed(texts, version=version_b)
    # Dot product of unit vectors = cosine similarity (N,)
    similarities = np.einsum("ij,ij->i", emb_a, emb_b)
    distances = np.clip(1.0 - similarities, 0.0, 2.0)  # clip float noise
    return float(np.mean(distances))

np.einsum("ij,ij->i", a, b) is the row-wise dot product of two matrices — equivalent to (a * b).sum(axis=1) but more readable for this pattern. Since both matrices are L2-normalized, this gives cosine similarity per row.

Matched-pair drift answers “are these the same embeddings?” That’s the right check when you redeploy the same model on a new runtime, precision or library version: it should be close to 0. Across different models it measures training lineage, not whether you can swap.

Comparing different models: neighbour overlap

To compare two different models, compare rankings instead of vectors. For each probe text, find its k nearest neighbours among the other probe texts under each model, and count how many they share:

def neighbour_overlap(self, texts, version_a, version_b, k=10) -> float:
    def top_k(emb):
        sims = emb @ emb.T
        np.fill_diagonal(sims, -np.inf)   # a text is not its own neighbour
        return np.argsort(-sims, axis=1)[:, :k]
    nbrs_a = top_k(self._registry.embed(texts, version=version_a))
    nbrs_b = top_k(self._registry.embed(texts, version=version_b))
    return float(np.mean([len(set(a) & set(b)) / k for a, b in zip(nbrs_a, nbrs_b)]))

Each model is only ever compared with itself, so this works across spaces and even across dimensions. MiniLM-L6 vs L12 score 0.65 at k=10. Overlap tells you how much retrieval will change, not whether the new model is better: for that you still need labelled queries.

The compatibility gate:

is_compatible(v_a, v_b, probe_texts, threshold=0.9) answers one narrow question: can vectors from both versions live in the same index? For two different models (different names or dimensions) the answer is always False. For two versions of the same model, it requires average cosine similarity of at least threshold between same-text embeddings.

PinningPolicy:

During a gradual migration from “stable” (MiniLM-L6) to “next” (MiniLM-L12), you want:

  • New services: use “next” immediately (you chose them for a reason)
  • Existing services: keep “stable” for 7 days, while the new model’s index is built and tested
policy = PinningRegistry()
policy.pin("svc-legacy", version="stable", until=now + timedelta(days=7))

# svc-legacy gets "stable" regardless of the global default:
resolved_version = policy.resolve("svc-legacy", default_version="next")
# → "stable" (still within 7-day window)

After pinned_until, resolve() returns the default (“next”), so the pin expires automatically. No manual cleanup required.

Zero-downtime upgrade path:

  1. Load new model as “canary”: registry.register_model("canary", "all-MiniLM-L12-v2")
  2. Check whether it can share the index: drift.is_compatible(...) → False (different model)
  3. Measure how much retrieval will change: drift.neighbour_overlap(probe_corpus, "stable", "canary") → 0.65, then evaluate both on labelled queries
  4. Pin existing services to “stable” for 7 days
  5. Shadow-index: re-embed all documents with “canary” into a shadow index
  6. Promote: rename “canary” to “stable”, atomically swap index pointer
  7. Pins expire after 7 days; all callers now use the new stable

Run it yourself

Prereqs: Python 3.12+pip or uv
  1. 1
    Clone and install dependencies
    git clone https://github.com/pushkarkumar-dev/system-design-labs
    cd system-design-labs/labs/embedding-pipeline
    pip install -e '.[test]'
  2. 2
    Run tests (downloads model on first run ~25MB)
    python -m pytest tests/test_embedding.py -v
  3. 3
    Start the embedding server (v0/v1/v2 all served)
    uvicorn src.server:app --port 8000
  4. 4
    Embed a single text (v0 endpoint — no batching)
    curl -s -X POST http://localhost:8000/embed/v0 \
      -H 'Content-Type: application/json' \
      -d '{"texts": ["hello world"]}' | python -m json.tool
  5. 5
    Embed a batch of texts (v1 endpoint — dynamic batching)
    curl -s -X POST http://localhost:8000/embed/v1 \
      -H 'Content-Type: application/json' \
      -d '{"texts": ["hello", "world", "embedding", "pipeline"]}' | python -m json.tool
  6. 6
    Register a second model version (v2 — model registry)
    curl -s -X POST http://localhost:8000/versions/canary \
      -H 'Content-Type: application/json' \
      -d '{"model_name": "all-MiniLM-L6-v2"}' | python -m json.tool
  7. 7
    Measure drift between stable and canary
    curl -s -X POST http://localhost:8000/drift \
      -H 'Content-Type: application/json' \
      -d '{"texts": ["the cat sat on the mat", "distributed systems", "embedding pipeline"], "version_a": "stable", "version_b": "canary"}' | python -m json.tool
  8. 8
    Check cache hit rate
    curl -s http://localhost:8000/cache/stats | python -m json.tool
  9. 9
    Measure batching, the queue and the cache on your machine (stop the server first; several minutes per device)
    python scripts/bench.py --devices cpu
Expected output
=== GET /health ===
{
"v0": {"status": "ok", "model": "all-MiniLM-L6-v2", "loaded": true},
"v1": {"status": "ok", "model": "all-MiniLM-L6-v2", "loaded": true,
       "cache": {"size": 0, "max_size": 10000, "hits": 0, "misses": 0, "hit_rate": 0.0}},
"v2": {"status": "ok",
       "versions": [{"name": "all-MiniLM-L6-v2", "version": "stable", "dimension": 384,
                     "loaded_at": "2026-10-12T02:49:18.751585+00:00"}],
       "default_version": "stable", "active_pins": 0}
}

=== POST /embed/v0 (first 3 of 384 floats shown) ===
{"embeddings": [[-0.034, 0.031, 0.007, ...]], "model": "all-MiniLM-L6-v2", "dimension": 384, "count": 1}

=== POST /versions/canary, then POST /drift (same model under two aliases) ===
{"version_a": "stable", "version_b": "canary", "avg_cosine_distance": 0.0,
"avg_cosine_similarity": 1.0, "compatible": true, "threshold": 0.9}

=== GET /cache/stats (after the 4-text /embed/v1 call: 4 misses, now cached) ===
{"size": 4, "max_size": 10000, "hits": 0, "misses": 4, "hit_rate": 0.0}

Benchmarks

Benchmark results on Apple M1 Ultra, 64 GB RAM, macOS 27, Python 3.13.7, torch 2.14.1, sentence-transformers 6.1.0 — CPU (16 threads) and MPS rows labelled, 2026-10-11
Metric Result Notes
encode(), 1 short text per call (CPU / MPS) 120 / 160 texts/sec measured — 8.3 / 6.3 ms per call; texts average 46 tokens
encode(), 32 short texts per call (CPU / MPS) 695 / 1,930 texts/sec measured — 6.0x / 12.0x the single-text rate
encode(), 1 vs 32 chunk-length texts (CPU) 35 / 112 texts/sec measured — 4.3x; texts truncated to 256 tokens
encode(), 1 vs 32 chunk-length texts (MPS) 112 / 648 texts/sec measured — 5.0x
v1 queue, 32 concurrent callers (CPU / MPS) 697 / 1,579 texts/sec measured — full batches of 32; p50 latency 45 / 19 ms
v1 queue, 1 caller: latency added by the queue 7.5 / 11.7 ms measured — CPU / MPS; 5 ms window + thread hand-off
Cache hit through BatchedEmbeddingServer.embed() 300,000 texts/sec measured — 3.3 µs; SHA-256 + OrderedDict lookup is 1.1 µs of it
LRU hit rate, Zipf s=1.0, 100k distinct texts, cache 10k 72.2 % measured — synthetic stream of 200k requests; uniform: 9.8%
Matched-pair cosine distance (MiniLM-L6 vs L12) 0.49 avg cosine dist measured — 434 probe texts; unrelated pairs 0.92
Neighbour overlap@10 (MiniLM-L6 vs L12) 0.65 fraction measured — scripts/compare_models.py

Every throughput row is the median of 7 rounds in which the alternatives being compared were interleaved, after a warm-up (scripts/bench.py; raw numbers in bench-runs/mac/2026-10-11/). Other workloads were running on the machine at the same time. Treat absolute CPU numbers as rough: an earlier, non-interleaved run of the script saw the same single-text measurement differ by 2x, and the chunk-length CPU rows here varied up to 3x between rounds. Ratios measured within one round are steadier (CPU short-text batching gain: 5.4x–6.5x across rounds).

Batching helps because a single-text call is mostly fixed overhead, not because the forward pass is free. The per-call time does grow with the batch: on CPU, 8.3 ms for one short text and 46 ms for 32. It grows more slowly than the batch, so throughput rises, until the hardware is busy: CPU throughput flattens past batch 32 for short texts and past batch 8 for 256-token texts; MPS flattens past 64. The size of the win depends on hardware and text length: 12x on the Apple GPU for short texts, 4–5x for chunk-sized texts. Measure on your own hardware and your own text lengths before you quote a multiplier.

There is no single “typical” cache hit rate. An LRU cache’s hit rate is set by how often texts repeat, which is a property of your traffic, not of the cache. On 200,000-request streams over 100,000 distinct texts, EmbeddingCache hits 9.8% when every text is equally popular, 46% with mildly skewed popularity (Zipf s=0.8) and 72% with Zipf s=1.0, all at the default 10,000 entries. A bulk ingestion job that embeds each chunk once gets 0%. Log your own request stream and replay it against the cache before sizing it.

Stress tests

Batch accumulation under load: in-process, the queue does what it promises. With 32 or 64 threads each calling BatchedEmbeddingServer.embed() with one text, every batch was full (32 texts) and throughput matched explicit batching on CPU (697 texts/s). Over HTTP it’s a different story. scripts/bench.py --server sends 1,000 single-text requests through 100 connections (asyncio.gather() with httpx) to the FastAPI server on its default device (MPS): /embed/v1 finished in 10.9 s (91 requests/s, p50 5.3 s), /embed/v0 in 13.8 s (72 requests/s), and one /embed/v0 request failed with a connection reset. The model isn’t the bottleneck there: GET /model-info, which does no model work at all, peaked at 600 requests/s under the same load, and a single sequential /embed/v1 request takes 19 ms against 7 ms for /embed/v0 because it waits out the batching window. We didn’t profile the server further; FastAPI runs these sync handlers in a thread pool, and every request pays for JSON-encoding 384 floats. The practical lesson: if clients can send 32 texts in one request, that beats any server-side batching of one-text requests.

Cache eviction correctness: fill the cache to max_size (10,000 entries), then add 1,000 new entries. The 1,000 oldest entries should be evicted. Access pattern: check that the 1,000 most recently accessed entries are all cache hits, and that an entry accessed only at the beginning of the fill is a miss.

Drift with mismatched dimensions: register a model with a different output dimension (e.g. all-mpnet-base-v2 has 768-dim vs MiniLM’s 384-dim). measure_drift() should raise immediately when trying to compute np.einsum("ij,ij->i", emb_a, emb_b) on mismatched shapes — a fast failure rather than silently wrong results. neighbour_overlap() still works, because it never compares vectors across models; run python scripts/compare_models.py all-MiniLM-L6-v2 all-mpnet-base-v2 to see it.

Pin expiry race condition: create a pin that expires in 100ms. Send requests at 50ms intervals. The first two requests should get the pinned version; requests after 100ms should get the default. Verify with the GET /pin endpoint’s active field.

Worker thread crash recovery: inject an exception in model.encode() via monkeypatching. The worker’s _run() loop catches all exceptions and calls future.set_exception() on all pending requests. Callers should receive Future.exception() rather than hanging indefinitely on future.result().

What the toy misses

What the toy misses Honest gaps vs. production
  • GPU acceleration sentence-transformers picks CUDA or Apple's MPS automatically when PyTorch finds one; on the Mac we measured on, it chose MPS without being asked, so 'the default' already means different hardware on different machines. A datacenter GPU needs much larger batches than 32 to stay busy, so max_batch_size and the wait window have to be retuned per device, and GPU memory, not the 5 ms window, becomes the limit on batch size.
  • Embedding quantization Float32 embeddings use 4 bytes per dimension. INT8 quantization cuts storage 4x (1,536 to 384 bytes per 384-dim vector) and speeds up ANN search, at a recall cost you have to measure on your own queries. Matryoshka representation learning trains models so you can truncate dimensions (384 → 256 → 128) with little quality loss — useful for tiered storage.
  • Late chunking for long documents all-MiniLM-L6-v2 reads at most 256 word pieces per text and silently drops the rest; every chunk-length text in our benchmark (~1,200 characters, ~270 tokens) was truncated. Late chunking (JinaAI) embeds the full document with a long-context model first, then pools token embeddings per chunk — preserving cross-chunk context that naive chunking loses.
  • Streaming ingestion At the 110–180 chunk-length texts/sec we measured for one CPU process, a 1M-chunk corpus takes 1.5–2.5 hours to embed. Production pipelines use parallel workers (Ray, Spark), with each worker embedding a shard. Coordination requires a distributed job queue and idempotent checkpointing — so you can resume after worker failure without re-embedding already-processed shards.
  • Index synchronization When upgrading the embedding model, all vectors in the ANN index must be re-embedded and re-indexed. Re-embedding time is corpus size divided by throughput: 100M chunk-length texts at 110–180 texts/sec is 6–10 days for one process, so real migrations shard the work across many GPUs. Blue-green index switching requires maintaining two indexes simultaneously — doubling memory cost during the migration window.
  • Embedding model fine-tuning General-purpose embeddings (MiniLM) can underperform on domain-specific tasks. Fine-tuning with domain data using contrastive loss (positive/negative pairs) can help on specialized retrieval; measure it on your own labelled queries. The contrastive loss requires mining hard negatives — documents that are lexically similar but semantically different.

Wiring it into a Java/Spring service

☕

Wiring it into a Java/Spring service

service client spring-ai
Maven dependencies
org.springframework.ai:spring-ai-core:1.0.0
org.springframework.ai:spring-ai-openai-spring-boot-starter:1.0.0
org.springframework.boot:spring-boot-starter-web:3.3.0

Part A — EmbeddingClient: the HTTP bridge

EmbeddingClient.java calls our Python FastAPI server using Spring Framework 6.1’s RestClient. Two embed operations:

public class EmbeddingClient {
    private final RestClient http;

    public EmbeddingClient(String baseUrl) {
        this.http = RestClient.builder().baseUrl(baseUrl).build();
    }

    public EmbedResponse embed(List<String> texts) {
        return embed(texts, null);   // uses "stable" version
    }

    public EmbedResponse embed(List<String> texts, String version) {
        var resp = http.post()
                .uri("/embed")
                .contentType(MediaType.APPLICATION_JSON)
                .body(new EmbedRequest(texts, version, null))
                .retrieve()
                .body(EmbedResponse.class);
        if (resp == null) throw new EmbeddingException("null from server");
        return resp;
    }
}

Usage in any Spring service:

@Autowired EmbeddingClient embeddingClient;

EmbeddingClient.EmbedResponse resp = embeddingClient.embed(List.of("hello world"));
float[] vector = resp.floatArray(0);   // 384-dim, L2-normalized

Part B — Spring AI’s EmbeddingClient interface

Spring AI defines org.springframework.ai.embedding.EmbeddingClient as an interface with one method:

float[] embed(String text);

The spring-ai-openai-spring-boot-starter auto-configures an OpenAiEmbeddingClient that calls OpenAI’s text-embedding-3-small (1536-dim) by default. The downstream code is identical for both backends:

// Using Spring AI's auto-configured client (OpenAI by default):
@Autowired
EmbeddingClient springAiClient;

float[] embedding = springAiClient.embed("Hello world");
// → float[1536] from text-embedding-3-small

// Using our custom client (Python server):
@Autowired
dev.pushkar.embedding.EmbeddingClient ourClient;

float[] embedding = ourClient.embed(List.of("Hello world")).floatArray(0);
// → float[384] from all-MiniLM-L6-v2

Both produce float[] embeddings. The cosine similarity calculation downstream is identical.

Part C — Routing Spring AI to our local server

To use Spring AI’s full abstraction stack (VectorStore, DocumentRetriever) with our local embedding model instead of OpenAI:

# application.yml
spring:
  ai:
    openai:
      base-url: http://localhost:8000   # our FastAPI server
      api-key: not-needed               # local server ignores this
      embedding:
        options:
          model: all-MiniLM-L6-v2

With this configuration, springAiClient.embed("...") routes to POST http://localhost:8000/v1/embeddings. Our FastAPI server needs to accept OpenAI’s request format — add a /v1/embeddings endpoint that maps to our /embed handler. This is the standard OpenAI-compatible API contract that local inference servers (Ollama, LM Studio) also implement.

Run it

# Terminal 1: start the Python server
cd labs/embedding-pipeline
uvicorn src.server:app --port 8000

# Terminal 2: run the Spring Boot demo
cd labs/embedding-pipeline/java-integration
mvn spring-boot:run

Expected output. The Java side wasn’t run on the machine that measured this page (no JDK there). The cosine similarities are what the Python server’s embeddings give for the demo’s texts; the Spring AI part depends on whether an OpenAI key is configured.

=== Embedding Pipeline Spring Integration Demo ===

--- Backend 1: Our Python server (all-MiniLM-L6-v2, 384-dim) ---
Health: HealthStatus[v0={status=ok, ...}, v1=..., v2=...]
Embedded 3 texts | model: all-MiniLM-L6-v2 | dim: 384
  Cosine sim (text 0, text 1): 0.1036
  Cosine sim (text 0, text 0): 1.0000

--- Backend 2: Spring AI EmbeddingClient ---
Spring AI embed dim: 1536
  (OpenAI text-embedding-3-small returns 1536-dim by default)
  Set spring.ai.openai.base-url=http://localhost:8000 to
  route Spring AI through our local server instead.

Done. Both clients produce float[] embeddings — downstream code is identical.

What surprised me

Where to go deeper

  • Previous in AI: RAG System (lab rag) — uses an embedding pipeline exactly like this one for chunk retrieval; this lab explains what happens inside the embed_texts() call
  • Next in AI: Vector Index (lab vector-index) — build the ANN index that stores and queries the vectors this pipeline produces
  • System design companion: If your embedding model produces 384-dim vectors and your ANN index is built on them, how do you upgrade to a 768-dim model without downtime? (Hint: blue-green indexes — build the new index in the background, atomically swap the query pointer when ready)
  • System design companion: At what query volume does the 5ms batching window become too expensive? (Hint: below the rate that fills batches, the window is pure cost. We measured a lone caller paying 7.5–11.7 ms extra per request, not 5 ms, because of the thread hand-off; against a 10 ms P99 budget that’s the whole budget. Size the window from measured arrival rates, or let clients batch.)