06.2 Embedding Pipelines: Batching, Caching, Scale and Cost

RetrievalLesson 2 of 1010,780 words13 parts
Module 06 · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

06.1 taught you how to call an embedding model correctly: which models exist, what each provider's API accepts, how task types and prefixes work, and how to choose a model with evidence. Module 05 taught you how to turn documents into clean, well-formed chunks. This lesson covers the step in between and around them: the production embedding pipeline that takes those chunks and turns them into stored, searchable vectors — efficiently, cheaply, resumably, and without silently corrupting your index. It owns batching under provider limits, concurrency and rate-limit budgeting, the batch APIs used for large backfills, content-hash caching, preprocessing decisions, cost modelling, query-path latency, vector storage formats, million-scale operations, and quality guards that catch a bad run before it poisons search. It stops where similarity and indexing begin: what you do with the vectors is 06.3 onwards.

What you'll learn

  • How to pack embedding requests under each provider's per-request input, token and batch limits — including token-aware greedy packing, length-sorted batching for local models, and partial-failure handling — with order preserved end to end
  • How to run embedding jobs asynchronously at the right concurrency, budget tokens-per-minute and requests-per-minute, back off on 429s, and make a multi-million-chunk job resumable
  • Which providers offer batch embedding APIs (OpenAI, Gemini, Voyage, Cohere, Jina, Mistral, OpenRouter), what they cost, how they reconcile results, and when a batch beats real time
  • How to build a content-hash → vector cache keyed by (model, version, dimensions, task type, preprocessing hash, text hash), with a CachingEmbedder you can drop in front of any embedder
  • What to embed and what not to: preprocessing for embeddings (whitespace, Unicode, markup, boilerplate, deduplication, structured records)
  • How to model embedding cost before you spend it: tokens × price, storage, re-embedding, query-time cost, batch vs real-time, and local vs API break-even — as a calculator with prices as parameters
  • How to keep query-time embedding latency low, and what to do when the embedding API is down
  • How vectors are stored: float32 vs float16 vs int8 vs binary, .npy/Parquet/Arrow/pgvector formats, memory arithmetic, and how to measure compression quality
  • How to run embedding at scale: sharded jobs, checkpoints, idempotent writes, backfills, blue/green re-embedding and freshness
  • Quality guards: NaN/zero/duplicate/dimension checks, a validate_embeddings function, and sanity query tests after each run
  • Embedding things other than chunks: queries, images, tables, code, profiles, clustering/dedup, and classification on top of embeddings

What you don't need

  • API keys for most of this lesson. The batching, caching, validation, cost and storage code is pure Python/NumPy and runs on your machine with no network. Provider samples are written against official docs and labelled illustrative; they show the exact request shapes without needing a key to read.
  • A vector database. Where storage formats matter, this lesson gives you the arithmetic and the format trade-offs; 06.5 owns the deep dive into each database.
  • Knowledge of how embeddings are made. 02.3 covers embeddings as a concept; 06.1 covers calling the models. This lesson links back rather than repeating them.

Setup

Most samples need only the standard library and NumPy. If you don't have a project yet, create one first (uv init embeddings-pipeline --bare --python 3.13 && cd embeddings-pipeline), then:

bash
uv add numpy
# or: pip install numpy

Provider samples additionally need the OpenAI SDK (OpenRouter goes through it too), python-dotenv for .env loading, and tiktoken for Exercise 1:

bash
uv add openai tiktoken python-dotenv
# or: pip install openai tiktoken python-dotenv

These commands install the newest release of each package. The samples were checked against numpy 2.5.4, openai 3.42.1 and tiktoken 0.14.0 as of November 2026; a newer major version may change names or defaults, so check the library's changelog if a sample does not match. The .env file holds OPENAI_API_KEY, GEMINI_API_KEY, VOYAGE_API_KEY and OPENROUTER_API_KEY (never commit it). Sync-call samples for the other providers live in 06.1 — its Setup installs google-genai, voyageai, cohere and mistralai; this lesson's only provider sample is the OpenAI Batch example in 4.4, and everything else is pure Python/NumPy that runs with no key. Every provider sample below is labelled illustrative — the request shapes are verified against official documentation as of November 2026, but the outputs shown are not live captures.


What you must be able to do after this lesson#

  • Pack embedding requests into batches under provider limits
  • Handle rate limits and make an embedding job resumable
  • Cache embeddings so unchanged text is not paid for twice
  • Estimate the cost of embedding a corpus
  • Normalize vectors and choose a storage dtype
  • Add quality guards that catch bad embeddings

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The embedding job died at item 80,000 — start it over?" 3.5 Progress, checkpoints and resumability
"We're hitting 429s on the embeddings endpoint." 3.2 TPM/RPM budgeting and 3.3 Backoff and Retry-After
"Should we use the Batch API for the re-index?" 4.5 The batch decision table
"Why are we paying to embed the same chunk twice?" 5.2 The cache key and 5.3 CachingEmbedder
"The search broke after we switched embedding models." 5.6 Invalidation on model change (and 06.1, 7.5)
"How much will embedding 2M chunks cost?" 7.2 The cost calculator
"Vectors take too much RAM at query time." 9.2 Storage formats and 9.3 Memory arithmetic
"Half the vectors came back as NaN." 11.1 What can go wrong and 11.2 validate_embeddings
"The embedding API is down — is search down too?" 8.1 Timeouts and fallbacks
"We re-embedded everything and search got worse." 6. Preprocessing for embeddings and 11.4 Sanity checks

Part 1: Where the embedding pipeline sits#

1.1 The shape of the problem#

Module 05 ends with a stream of chunks: clean text pieces, each with an ID, metadata and a content hash. Module 06.3 onwards consumes vectors: one dense vector per chunk, stored alongside the chunk's ID and metadata, searchable by similarity. This lesson is the machinery that converts the first into the second.

Three properties of the problem drive every decision in this lesson:

  1. It runs twice at different scales. Documents are embedded once per chunk, at index time, in bulk — millions of texts, latency-tolerant, cost-sensitive. Queries are embedded once per search, at query time — one short text, latency-critical, must be cheap. A pipeline tuned for one is wrong for the other.
  2. It is a paid, rate-limited external call (for API models) or a GPU job (for local models). Both have hard ceilings: requests per minute, tokens per minute, inputs per request, tokens per request. Exceeding them doesn't corrupt data — it stalls, fails or bills you for retries.
  3. Its output is only useful if it stays consistent. A vector is meaningless without knowing which model, version, dimensions, task type and preprocessing produced it. Mix two configurations in one index and search silently degrades — the failure mode 06.1 and 02.3, 7.5 cover in depth.
flowchart LR
    subgraph m5 ["Module 05 output"]
        CH["Chunks<br/>id, text, metadata, content_hash"]
    end
    subgraph pipe ["This lesson: the embedding pipeline"]
        PRE["Preprocess<br/>(whitespace, markup, boilerplate)"]
        BATCH["Batch under provider limits"]
        CACHE["Content-hash cache"]
        CALL["Embedder<br/>API or local model"]
        VAL["validate_embeddings"]
        PRE --> BATCH --> CACHE --> CALL --> VAL
    end
    subgraph store ["Storage"]
        VEC[("Vectors + metadata<br/>vector DB / files")]
    end
    CH --> PRE
    VAL --> VEC
    Q["Query text<br/>(query time: same pipeline, one item)"] -.-> PRE

1.2 The Embedder seam#

Everything in this lesson is written against a tiny interface rather than a provider SDK, so the same batching, caching and validation code works for OpenAI, Gemini, Voyage, a local sentence-transformers model, or a fake you control in tests:

python
from typing import Protocol

class Embedder(Protocol):
    """The seam every provider adapter and every fake fulfils."""
    spec: "EmbedSpec"          # model, version, dims, task_type, preprocessing hash

    def embed(self, texts: list[str]) -> list[list[float]]:
        """One vector per input, in input order."""
        ...

1.3 Index time vs query time#

Index time (documents) Query time (searches)
Volume Millions of texts One per request
Latency budget Hours to days OK Milliseconds to ~1 s
Cost driver Total tokens × price Round-trip latency
Failure tolerance Resume and retry freely Degrade gracefully (see 8.1)
Batching Pack to provider limits Single text, keep-alive connection
Caching Content-hash → vector Query-text → vector (privacy care, 5.5)
Batch API? Yes, usually the right tool for big jobs Never — it's asynchronous

Keep this table in mind: several "obvious" choices (batch everything, cache everything, use the biggest model) are right at index time and wrong at query time, or vice versa.


Part 2: Batching#

2.1 Why batching is the first optimisation#

Every embedding API accepts a list of texts per request, and every local model runs faster per text in a batch (GPU kernels amortise setup, and padding is shared). The naive loop — one HTTP request per chunk — is wrong at any real scale: it multiplies latency by N, burns rate-limit budget on request count rather than tokens, and for a million chunks would take days.

Batching has three separate problems, and confusing them causes most bugs:

Problem Question Where it's solved
Packing Which texts go in which request? 2.3–2.5
Ordering Did result i come back for text i? 2.6 Order preservation
Failure What if one text in a batch is bad? 2.7 Partial failures

2.2 The three limits every provider imposes#

Verified against each provider's official documentation as of November 2026 (the Further resources list links them):

Provider Inputs per request Tokens per input Tokens per request Notes
OpenAI text-embedding-3-* 2,048 8,192 300,000 total Empty string rejected; token-array inputs ≤ 2,048 dims
Gemini embed_content Practically bounded by total tokens 2,048 (-001) / 8,192 (-2) Per-request token cap applies gemini-embedding-2 aggregates a bare list into ONE vector — wrap each item in its own Content (06.1)
Voyage voyage-4* 1,000 texts 32,000 ctx 120K–1M total depending on model Lite models get the largest caps
Cohere embed-v4.0/embed-v5.0-* 96 texts/inputs 128K (max_tokens) — truncate: NONE/START/END controls over-length (AWS Bedrock spells the same options LEFT/RIGHT)
Jina /v1/embeddings No hard item cap 8,192–32,768 by model TPM rate limit is the real bound truncate: true opts into truncation
Mistral mistral-embed List input ~8K ctx — output_dimension, output_dtype supported
OpenRouter /embeddings Array input Per underlying model Per underlying model Limits inherit from the provider serving the model

The pattern: there is always a per-request total-token ceiling well below inputs × per-input limit. A request of 2,048 chunks × 500 tokens is ~1M tokens — OpenAI rejects it at 300K. Packing must therefore be token-aware, not just item-count-aware.

2.3 Token-aware batching: greedy packing#

The standard algorithm is greedy first-fit: walk the texts in order, keep a running token total, and start a new batch when adding the next text would break either cap. It's not optimal (first-fit decreasing would pack tighter) but it's O(n), preserves order, and is within a few percent of optimal for real chunk-size distributions.

For token counting, use the provider's own tokenizer when you can — tiktoken with cl100k_base for OpenAI's third-generation embedding models (their docs say so explicitly), the provider's count endpoint where one exists, or the model's own tokenizer for local models. When you can't count exactly, a characters-per-token heuristic (~4 for English prose; Anthropic-family tokenizers run nearer 2.5 — see 03.7, 2.7) is fine for packing because the caps have generous margins; it's not fine for billing estimates, where you want the real count.

This is pure Python and runs as-is — the output below is real:

python
import math

def estimate_tokens(text: str) -> int:
    """Cheap estimate: ~4 chars per token for English prose (02.2)."""
    return max(1, math.ceil(len(text) / 4))

def pack_batches(texts, max_request_tokens=300_000, max_input_tokens=8_192,
                 max_items=2_048, count_tokens=estimate_tokens):
    """Greedy first-fit under BOTH caps. Raises on an oversized single input.

    Two different provider limits, per the 2.2 table: max_input_tokens bounds
    ONE text (OpenAI: 8,192); max_request_tokens bounds the SUM across a whole
    request (OpenAI: 300,000). Defaults are OpenAI's — pass your provider's."""
    batches, cur, cur_tokens = [], [], 0
    for text in texts:
        t = count_tokens(text)
        if t > max_input_tokens:
            raise ValueError(
                f"single input of ~{t} tokens exceeds per-input limit {max_input_tokens}"
            )
        if cur and (cur_tokens + t > max_request_tokens or len(cur) >= max_items):
            batches.append(cur)
            cur, cur_tokens = [], 0
        cur.append(text)
        cur_tokens += t
    if cur:
        batches.append(cur)
    return batches

chunks = [
    "Refund policy: returns accepted within 30 days.",
    "Two-factor authentication setup guide for new accounts.",
    "x" * 2000,  # a long chunk ~500 tokens
    "Invoice PDFs are on the Billing page.",
    "International shipping takes 5-10 business days.",
]
for i, b in enumerate(pack_batches(chunks, max_request_tokens=600, max_items=3)):
    print(f"batch {i}: {len(b)} items, ~{sum(estimate_tokens(t) for t in b)} tokens")
try:
    pack_batches(["y" * 40000], max_input_tokens=8192)
except ValueError as e:
    print(f"oversized -> ValueError: {e}")
Output3 lines
batch 0: 3 items, ~526 tokens
batch 1: 2 items, ~22 tokens
oversized -> ValueError: single input of ~10000 tokens exceeds per-input limit 8192

Three things to notice:

  • The long chunk (~500 tokens) fit under the 600-token budget alongside two short ones; the item cap of 3, not the token cap, forced the second batch. Both caps matter — check which one binds for your data.
  • The oversized input raises before any API call. In production, route it to the chunker (05.6) or a long-context path rather than letting the provider reject the whole batch.
  • count_tokens is a parameter: swap the heuristic for tiktoken or the model's tokenizer in production, keep the packing logic identical.

2.4 Length-sorted batching for local models#

When you run sentence-transformers (or any local encoder) yourself, batch throughput is dominated by the longest sequence in the batch: every sequence is padded to it. Sorting texts by token length before batching — then restoring original order afterwards — can cut padding dramatically on mixed-length corpora.

python
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

texts = [
    "Short one.",
    "A much longer support ticket describing a billing dispute " * 8,
    "Medium length question about refunds?",
    "Tiny.",
]

# Sort by length so each batch pads to a similar maximum
def token_len(t):
    return len(model.tokenizer.tokenize(t))

order = sorted(range(len(texts)), key=lambda i: token_len(texts[i]))
sorted_texts = [texts[i] for i in order]
vecs_sorted = model.encode(sorted_texts, batch_size=2, normalize_embeddings=True)

# Restore original order: unsort
vecs = np.empty_like(vecs_sorted)
vecs[order] = vecs_sorted
for t, v in zip(texts, vecs):
    print(f"{float(v @ vecs[0]):.3f} vs first  {t[:50]!r}")
Example output · illustrative4 lines
1.000 vs first  'Short one.'
0.412 vs first  'A much longer support ticket describing a billin'
0.388 vs first  'Medium length question about refunds?'
0.731 vs first  'Tiny.'

2.5 Batching for GPU throughput#

On local models, batch size is a throughput dial with a memory ceiling:

Batch size Effect
1 Maximum latency per text; never use for bulk jobs
8–64 Typical sweet spot on a consumer GPU for 384–1024-dim embedding models
128–512 Data-centre GPUs; watch activation memory (~batch × seq_len × hidden × bytes)
Too large CUDA OOM mid-job; the fix is a smaller batch_size, not a smaller model

sleep between batches is rarely needed on your own GPU — the bottleneck is compute, not an external rate limit. What you do need is checkpointing so a crash at batch 4,000 of 40,000 doesn't restart from zero — that's 3.5.

2.6 Order preservation#

Two layers of ordering must survive the pipeline:

  1. Within a provider response. OpenAI returns data[i].index matching the input position; Voyage and Cohere return arrays in input order; Gemini returns embeddings in request order. Never assume — sort by the explicit index field where the API provides one, and assert len(output) == len(input) before zipping.
  2. Across batches. Your packer emits batches; the writer must place each result at its chunk's position, not append blindly. The safe pattern is a dict keyed by chunk ID (or position) that you flush in order at the end.
python
def embed_in_order(embed_fn, texts, batch_size):
    """Embed in batches, return vectors in input order regardless of
    how the provider orders (or splits) its response."""
    out = [None] * len(texts)
    for start in range(0, len(texts), batch_size):
        chunk = texts[start:start + batch_size]
        vecs = embed_fn(chunk)               # provider call
        assert len(vecs) == len(chunk), "provider returned wrong count"
        for j, v in enumerate(vecs):
            out[start + j] = v
    assert all(v is not None for v in out)
    return out

2.7 Partial failures within a batch#

A batch request is atomic at the HTTP level but not at the item level in practice:

  • OpenAI rejects the whole request if any input is empty or over-limit — you find out at request time, and the fix is upstream (filter empties, pre-split oversized inputs).
  • Gemini returns per-item errors inside a batch response; successful items still come back.
  • Local models fail per batch (OOM), not per item.

The robust pattern is isolate the bad item: on a batch-level rejection, bisect — retry halves until the failing input is isolated, embed the rest, log the offender. For million-chunk jobs, wrap each batch call in your retry layer (03.8) and treat a persistent per-item error as data to quarantine, not a reason to abandon the job.


Part 3: Concurrency, rate limits and resumability#

3.1 Async embedding with bounded concurrency#

Index-time embedding is I/O-bound for API models: each call is mostly waiting on the network. 03.9 teaches the mechanics — async clients, asyncio.Semaphore, TaskGroup vs gather, retry-inside-the-bound. Apply them here with one embedding-specific twist: the unit of concurrency is the batch, not the text. You want, say, 8–32 requests in flight, each carrying a packed batch, not 8–32 texts.

python
import asyncio

async def embed_corpus_async(embed_batch, batches, max_in_flight=8):
    """embed_batch: async callable taking a list[str] -> list[vector].
    batches: list[list[str]] from pack_batches(). Returns vectors in order."""
    sem = asyncio.Semaphore(max_in_flight)
    results = [None] * len(batches)

    async def run(i, batch):
        async with sem:
            results[i] = await embed_batch(batch)

    async with asyncio.TaskGroup() as tg:
        for i, b in enumerate(batches):
            tg.create_task(run(i, b))
    # flatten batch results back to per-text order
    return [v for batch_vecs in results for v in batch_vecs]

3.2 TPM and RPM budgeting#

Rate limits for embedding APIs are expressed in requests per minute (RPM) and tokens per minute (TPM) — and TPM almost always binds first for embedding jobs, because a single request can carry 300K tokens (OpenAI) or 120K–1M (Voyage). Budgeting is arithmetic:

text
sustainable_requests_per_minute = min(RPM_limit,
                                      TPM_limit / avg_tokens_per_request)

With OpenAI's published embedding tiers (as of November 2026, e.g. Build tier ~5,000 RPM / 1M TPM for text-embedding-3-large — check your own tier on the limits page): at 300K tokens/request you can only sustain ~3 requests/minute before TPM binds, even though RPM allows 5,000. TPM counts tokens, not requests, so how you slice the work does not change the ceiling: smaller batches mean more requests for the same tokens per minute, and packing tighter just reaches the same token ceiling with fewer requests.

The practical knobs:

Knob Effect
Fewer texts per request More requests, same tokens/min — helps only when RPM (not TPM) binds
More texts per request Fewer requests, same tokens/min — required when RPM binds
Lower concurrency Directly caps requests/min in flight
Second API key / region Raises limits only if your plan and terms allow it — see 3.4

3.3 Backoff and Retry-After#

Embedding endpoints return the same error shapes as chat endpoints: 429 with Retry-After or x-should-retry, 5xx, timeouts. 03.8 owns the full taxonomy — exponential backoff with jitter, Retry-After parsing, retry budgets, the "never retry without a cap" rule. For embedding jobs, three specifics:

  • Retries are cheap here relative to chat. An embedding call has no reasoning tokens and no long generation; a retry costs one round-trip, not a regenerated answer. You can afford more aggressive retry counts than for chat — but still bounded, because a poisoned batch retried forever burns TPM budget that healthy batches need.
  • Respect Retry-After literally. On a 429 the server is telling you the exact delay; jittered backoff that ignores it just re-collides.
  • Back off the whole worker pool on sustained 429s, not just the failing request — if TPM is saturated, every in-flight request will fail; pausing the semaphore briefly is cheaper than 32 simultaneous retries.

3.4 Multi-key and multi-region caution#

The instinct on rate limits is "add keys". Before doing it, check the provider's terms:

  • OpenAI rate limits are per organisation/project (and per model); a second project or key helps only within the terms — using multiple free-tier keys to multiply quota is a terms violation that gets accounts banned.
  • Voyage limits are per account/team.
  • Gemini quotas are per project; a second GCP project is a legitimate way to get a separate quota, and is the intended scaling path — but each project is a separate billing account to manage.
  • Batch APIs sidestep this entirely for bulk work: OpenAI's batch queue has its own much larger limits (batch queue limits per tier are ~20M–4B tokens), which is why Part 4 exists.

3.5 Progress, checkpoints and resumability#

A job that can't resume is a job that will eventually lose work. The minimum viable resumable embedder:

python
def embed_with_checkpoint(embed_batch, batches, store, job_id,
                          checkpoint_every=50):
    """store: any KV store (sqlite3, disk, Redis). Records done batch indices."""
    done = store.get_set(f"{job_id}:done")
    for i, batch in enumerate(batches):
        if i in done:
            continue
        vecs = embed_batch(batch)          # retry-wrapped caller's job
        store.put(f"{job_id}:batch:{i}", vecs)
        done.add(i)
        if i % checkpoint_every == 0:
            store.put_set(f"{job_id}:done", done)   # fsync-ish durability
            print(f"{job_id}: {i+1}/{len(batches)} batches")
    store.put_set(f"{job_id}:done", done)

Design rules that matter more than the code:

  • Idempotent writes. Writing vector i twice must produce the same stored state. Achieve it with upserts keyed by chunk ID, never append-only inserts (05.9 owns incremental ingestion; this is its embedding-side contract).
  • Checkpoint granularity = batch index, not text index. A batch is the unit that either fully succeeded or fully failed; per-text checkpoints inside a batch buy little and cost a write per item.
  • Store vectors durably before marking done. Order is: embed → write vectors → mark batch done. The reverse order loses vectors on crash.
  • Progress bars (tqdm, or a simple counter) are not cosmetic: on a 6-hour job they're how you distinguish "slow" from "stuck".

Part 4: Batch embedding APIs#

Deep-dive

4.1 What "batch" means here — three different things#

03.9, 1.4 already separated the senses; embedding jobs hit all three:

Sense Example Owner
Many texts per request input=[...] on /v1/embeddings Part 2
Many requests in flight async + semaphore Part 3
Provider batch API OpenAI Batch, Gemini batches, Voyage Batch, Jina /v1/batch/embeddings, Cohere Embed Jobs This part

This part is only about the third: an asynchronous, discounted, high-throughput path for jobs where nobody is waiting — backfills, re-embedding a corpus, nightly refreshes.

4.2 Which providers offer one (verified November 2026)#

Provider Batch path for embeddings Discount Turnaround Key limits
OpenAI client.batches.create(endpoint="/v1/embeddings", ...) on a JSONL file 50% ≤ 24 h (usually much less) ≤ 50,000 embedding inputs across all requests in a batch; file ≤ 200 MB
Gemini client.batches.create_embeddings(...) or REST :batchEmbedContents 50% target 24 h inline requests (< 20 MB) or JSONL file upload
Voyage Batch API (/v1/batches-style job over v1/embeddings) 33% 12 h window ≤ 100K inputs per batch; automatic retries/threading
Cohere Embed Jobs API — async job v3 embedding models only (e.g. embed-english-v3.0), dataset-based, aimed at 100K+ docs
Jina POST /v1/batch/embeddings — async ≤ 50K inputs via GCS file URL or 10K inline; output expires after 24 h
Mistral Batch feature on the platform — async Check current docs for embedding support
OpenRouter POST /api/v1/batches with endpoint: "/v1/embeddings" ~50% typical ≤ 24 h (Vertex up to 96 h) ≤ 200 MB per batch; custom_id join; batch-level provider.only/allow_fallbacks documented (no per-request order/sort)
Anthropic — — — No embeddings API, so no batch path either (06.1, 2.3)

4.3 The shared shape#

Every batch API is a variation on the same lifecycle, which 03.9, Part 6 teaches for chat: submit → poll/webhook → download results → reconcile by custom_id → handle partial failures → expire outputs. The embedding-specific bits:

  • Input is a list of embedding requests, each carrying the texts and the model/settings. OpenAI wants a JSONL file where each line is {"custom_id": ..., "method": "POST", "url": "/v1/embeddings", "body": {...}}; Voyage takes the same custom_id/body JSONL shape; Gemini's create_embeddings accepts inline request objects or a JSONL src; Jina and OpenRouter take JSONL/inline bodies with custom_id; Cohere Embed Jobs is dataset-based (upload a dataset of texts, not per-request JSONL lines).
  • Output is vectors, which are large: a 3,072-dim float32 vector is ~12 KB in binary but ~30–65 KB as JSON numbers (each float serializes to ~10–20 characters of text). A 50K-vector batch output is ~1.5–3 GB of text — plan storage and parse streaming (ijson/line-by-line), don't json.loads a giant blob.
  • Reconciliation is by custom_id, not position. Results arrive unordered; your custom_id must encode the chunk ID (or batch+index) so you can place each vector correctly — the same order-preservation problem as 2.6, one level up.

4.4 OpenAI Batch for embeddings — the worked example#

python
import json
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

# 1. Build the JSONL: one line per embedding REQUEST (a request can hold many texts)
def build_jsonl(chunks, path, batch_size=256, model="text-embedding-3-small"):
    with open(path, "w") as f:
        for i in range(0, len(chunks), batch_size):
            group = chunks[i:i + batch_size]
            line = {
                "custom_id": f"emb-{i // batch_size:05d}",
                "method": "POST",
                "url": "/v1/embeddings",
                "body": {
                    "model": model,
                    "input": [c["text"] for c in group],
                    "encoding_format": "float",
                },
            }
            f.write(json.dumps(line) + "\n")

# 2. Write the file, upload it, create the batch
#    chunks = [{"id": ..., "text": ...}, ...] from Module 05
build_jsonl(chunks, "embeddings.jsonl")
with open("embeddings.jsonl", "rb") as f:
    file = client.files.create(file=f, purpose="batch")
batch = client.batches.create(
    input_file_id=file.id,
    endpoint="/v1/embeddings",
    completion_window="24h",
)

# 3. Poll (or use a webhook). Batches often finish well inside the window.
import time
while True:
    batch = client.batches.retrieve(batch.id)
    print(batch.status, batch.request_counts)          # validating -> in_progress -> ...
    if batch.status in {"completed", "failed", "expired", "cancelled"}:
        break
    time.sleep(60)

# 4. Download. Output files are deleted 30 days after completion: copy them
#    into your own storage straight away. Requests that failed are in the
#    error file, not the output file.
if batch.output_file_id:
    output_lines = client.files.content(batch.output_file_id).text.splitlines()
if batch.error_file_id:
    error_lines = client.files.content(batch.error_file_id).text.splitlines()

#    Each output line: {"custom_id": ..., "response": {"status_code": 200,
#    "body": {"data": [{"index": 0, "embedding": [...]}, ...]}}, "error": null}
#    Reconcile: custom_id -> group index -> per-item `index` -> chunk position.

Provider sample — illustrative. The request/response shapes follow OpenAI's Batch and Embeddings API references as of November 2026 (OpenAI's batch guide, checked November 2026: embeddings are a supported endpoint at 50% lower cost, a batch holds at most 50,000 requests and 50,000 embedding inputs, the input file is capped at 200 MB, the only completion window is 24h, and output files are deleted 30 days after completion). Note that the 50,000-input ceiling means a 2M-chunk backfill is 40 or more separate batches, not one.

The step people get wrong is the last one, so here is the reconciliation as runnable, pure-stdlib code with a fabricated output file: three requests of two chunks each, lines out of order, and one request that failed on the provider side.

python
import json

def reconcile(output_lines, group_size, n_chunks):
    """Turn a downloaded batch output file into vectors in chunk order.
    Returns (vectors, failed_custom_ids, missing_positions)."""
    vectors = [None] * n_chunks
    failed = []
    for line in output_lines:
        rec = json.loads(line)
        resp = rec.get("response") or {}
        if rec.get("error") or resp.get("status_code") != 200:
            failed.append(rec["custom_id"])
            continue
        group = int(rec["custom_id"].split("-")[1])      # "emb-00002" -> 2
        for item in resp["body"]["data"]:
            vectors[group * group_size + item["index"]] = item["embedding"]
    missing = [i for i, v in enumerate(vectors) if v is None]
    return vectors, failed, missing

def ok(custom_id, embeddings):
    return json.dumps({"custom_id": custom_id, "error": None, "response": {
        "status_code": 200,
        "body": {"data": [{"index": i, "embedding": e}
                          for i, e in enumerate(embeddings)]}}})

# 5 chunks, 2 per request -> 3 requests. Lines arrive OUT of order and
# request emb-00001 failed on the provider side.
lines = [
    ok("emb-00002", [[0.5, 0.5]]),
    ok("emb-00000", [[1.0, 0.0], [0.0, 1.0]]),
    json.dumps({"custom_id": "emb-00001", "response": None,
                "error": {"code": "server_error", "message": "boom"}}),
]
vectors, failed, missing = reconcile(lines, group_size=2, n_chunks=5)
print("failed requests:", failed)
print("missing chunk positions:", missing)
print("chunk 4 vector:", vectors[4])
Output3 lines
failed requests: ['emb-00001']
missing chunk positions: [2, 3]
chunk 4 vector: [0.5, 0.5]

Chunks 2 and 3 are the casualties of the failed request. The follow-up is a second, smaller batch containing only the missing positions, never a re-run of the whole job, and the job's completion check is not missing, the batch-level version of the processed = succeeded + quarantined rule from 2.7.

4.5 The batch decision table#

Situation Use batch API? Why
Initial index of > ~100K chunks ✅ Yes 50%-class discount + queue limits far above sync RPM/TPM
Nightly incremental refresh (thousands of chunks) Maybe Sync with bounded concurrency is simpler and fast enough; batch if you want the discount
Re-embedding after a model change (whole corpus) ✅ Yes The canonical use case — large, latency-tolerant, expensive
Query-time embedding ❌ Never Async by definition; adds minutes of latency
Small corpus (< ~10K chunks) ❌ No Sync finishes in minutes; batch overhead (file upload, polling, reconciliation) isn't worth 50% of a small bill
Latency-sensitive backfill ("search must reflect new docs in 10 min") ❌ No Batch turnaround is hours, not minutes

The honest trade: batch APIs trade turnaround time for price and throughput. If your freshness SLO (10.3) is tighter than the batch window, you need the sync path regardless of cost.


Part 5: Caching#

5.1 Why cache embeddings at all#

Three independent reasons, in order of how often they pay off:

  1. Cost. Embedding is billed per input token. Re-embedding a text you've already embedded is pure waste — and it happens constantly: unchanged chunks re-ingested, retries that re-send texts, query repetition, A/B tests, model-eval reruns.
  2. Latency. A cache hit is a local lookup — microseconds to milliseconds — versus a network round-trip of tens to hundreds of milliseconds.
  3. Determinism in tests. A cached/fake embedder makes downstream code (indexing, search, evaluation) testable with zero network — the same role 03.10's fakes play for chat.

5.2 The cache key#

A vector is only valid for an exact configuration. The key must capture everything that changes the output:

text
key = (model_id, model_version, dimensions, task_type/input_type,
       preprocessing_hash, text_hash)
Component Why it's in the key
model_id + version Different models = different spaces (02.3, 7.5)
dimensions dimensions=256 vs 3072 are different vectors from the same model
task_type / input_type / prefixes Voyage query vs document, Gemini task_type, E5 query:/passage: prefixes all change the vector
preprocessing_hash A hash of your cleaning/normalization config — change the cleaner, invalidate the cache
text_hash SHA-256 of the exact string sent (after preprocessing, including any prefix the embedder adds)

5.3 CachingEmbedder: full code#

A decorator that sits in front of any Embedder — pure Python + sqlite3, runs as-is. The embedder below is a deterministic fake (hash → pseudo-vector) so the whole thing runs with no API key; swap fake_embed for a real adapter and nothing else changes.

python
import hashlib
import json
import math
import sqlite3
import time
from dataclasses import dataclass

@dataclass(frozen=True)
class EmbedSpec:
    """Everything that determines a vector. Part of every cache key."""
    model: str
    version: str
    dimensions: int
    task_type: str
    preprocessing: str          # e.g. "preprocess:v3" or a config hash


def fake_embed(texts, spec):
    """Deterministic stand-in: hash each text into `dimensions` floats,
    L2-normalized. Same text + same spec -> same vector, always."""
    out = []
    for t in texts:
        h = hashlib.sha256(f"{spec.model}:{t}".encode()).digest()
        vals = [(h[i % len(h)] / 255.0) - 0.5 for i in range(spec.dimensions)]
        n = math.sqrt(sum(v * v for v in vals)) or 1.0
        out.append([round(v / n, 6) for v in vals])
    return out


class SQLiteCache:
    """On-disk KV store. Swap for Redis/dict in production; the interface
    is just get(key) -> vector|None and put(key, vector)."""
    def __init__(self, path="embeddings_cache.db"):
        self.conn = sqlite3.connect(path)
        self.conn.execute(
            "CREATE TABLE IF NOT EXISTS embeddings "
            "(key TEXT PRIMARY KEY, vector TEXT NOT NULL, created REAL)")

    def get(self, key):
        row = self.conn.execute(
            "SELECT vector FROM embeddings WHERE key=?", (key,)).fetchone()
        return json.loads(row[0]) if row else None

    def put(self, key, vector):
        self.conn.execute(
            "INSERT OR REPLACE INTO embeddings VALUES (?,?,?)",
            (key, json.dumps(vector), time.time()))
        self.conn.commit()


class CachingEmbedder:
    def __init__(self, spec, cache, embed_fn=fake_embed):
        self.spec = spec
        self.cache = cache
        self.embed_fn = embed_fn
        self.calls = 0        # real embedder invocations
        self.hits = 0         # texts served from cache

    def _key(self, text):
        th = hashlib.sha256(text.encode()).hexdigest()[:16]
        s = self.spec
        return f"{s.model}|{s.version}|{s.dimensions}|{s.task_type}|{s.preprocessing}|{th}"

    def embed(self, texts):
        keys = [self._key(t) for t in texts]
        out = [self.cache.get(k) for k in keys]

        # Group miss positions by key: a text repeated inside one call is
        # embedded once, not once per occurrence.
        spots = {}
        for i, (k, v) in enumerate(zip(keys, out)):
            if v is None:
                spots.setdefault(k, []).append(i)
        if spots:
            uniq_keys = list(spots)
            uniq_texts = [texts[spots[k][0]] for k in uniq_keys]
            fresh = self.embed_fn(uniq_texts, self.spec)
            self.calls += 1
            for k, vec in zip(uniq_keys, fresh):
                self.cache.put(k, vec)
                for i in spots[k]:
                    out[i] = vec

        self.hits += len(texts) - sum(len(p) for p in spots.values())
        return out

Then a demo and the guarantees as asserts — both run as-is:

python
spec = EmbedSpec("fake-embed", "v1", 8, "document", "preprocess:v3")
texts = [
    "How do I reset my password?",
    "Refunds are issued within 14 days.",
    "Two-factor authentication setup.",
]

# Two wrappers, one shared cache: the second run is all hits.
# In-memory store so every run of this demo starts cold; pass a file path such as
# "embeddings_cache.db" to keep the cache between runs (then 'first run' shows hits).
emb = CachingEmbedder(spec, SQLiteCache(":memory:"))
v1 = emb.embed(texts)
emb2 = CachingEmbedder(spec, emb.cache)          # same store, new wrapper
v2 = emb2.embed(texts + [texts[0]])              # repeat inside the call
print(f"first run:  embedder calls={emb.calls}, hits={emb.hits}")
print(f"second run: embedder calls={emb2.calls}, hits={emb2.hits}")
print(f"repeat of first text identical: {v1[0] == v2[0]}")

# A spec change is a different key space: nothing falsely hits.
emb3 = CachingEmbedder(
    EmbedSpec("fake-embed", "v2", 8, "document", "preprocess:v3"),
    emb.cache)
emb3.embed(texts[:1])
print(f"model version change -> calls={emb3.calls}")

# Duplicates inside ONE call are embedded once, not once per occurrence.
seen = []
def spy_embed(ts, s):
    seen.append(list(ts))
    return fake_embed(ts, s)

emb4 = CachingEmbedder(spec, SQLiteCache(":memory:"), embed_fn=spy_embed)
emb4.embed(["brand new text", "brand new text", "other new text"])
print(f"duplicate in one call -> embedder saw {seen[0]}")

# --- the guarantees, as asserts ---
tcache = SQLiteCache(":memory:")
t = CachingEmbedder(spec, tcache, embed_fn=spy_embed)
t.embed(["alpha", "alpha", "beta"])
assert seen[-1] == ["alpha", "beta"], seen[-1]      # embedded once, not twice
assert t.embed(["alpha", "beta"]) == t.embed(["alpha", "beta"])  # stable
assert t.hits == 4                                  # 2 texts x 2 cached runs
t_v2 = CachingEmbedder(
    EmbedSpec("fake-embed", "v9", 8, "document", "preprocess:v3"),
    tcache, embed_fn=spy_embed)
before = len(seen)
t_v2.embed(["alpha"])
assert len(seen) == before + 1                      # new spec -> re-embed
print("tests passed: dedup-in-call, cache stability, spec invalidation")
Output6 lines
first run:  embedder calls=1, hits=0
second run: embedder calls=0, hits=4
repeat of first text identical: True
model version change -> calls=1
duplicate in one call -> embedder saw ['brand new text', 'other new text']
tests passed: dedup-in-call, cache stability, spec invalidation

Reading it: hits=4 is the three cached texts plus the repeat of the first one, and calls=1 after the version bump is the cache correctly refusing to reuse a vector made under the old spec.

What to notice:

  • Batching is preserved: embed calls the real embedder once per unique missing text, not once per occurrence — cache misses still get packed into provider-sized batches upstream, and a text repeated inside one call costs one embedding, not two.
  • The spec is the invalidation story: bump version or preprocessing and every key changes, so stale vectors are simply never hit — no explicit flush needed. Old rows can be garbage-collected by created timestamp.
  • calls/hits are your observability: log the hit ratio per job; a sudden drop to 0% means your preprocessing changed (and you're about to re-embed the world).

5.4 Cache backends#

Backend Good for Watch out for
SQLite (above) Single-node jobs, laptops, tests One writer at a time; fine to ~millions of rows
Flat files / .npy + manifest Bulk offline jobs where vectors are written once No random access; rebuild index to query
Redis Shared cache across workers/services, query-time cache Memory cost; set a TTL or size cap
The vector DB itself Production: dedupe by content hash before insert Depends on your store's upsert semantics (06.5)
Nothing (recompute) Tiny corpora, one-off evals Fine — don't build a cache you don't need

5.5 The query-embedding cache#

Repeated queries are common ("what's the refund policy?" asked daily). Caching query → vector is tempting but has a privacy wrinkle the document cache doesn't: a query cache stores what users asked, which can be sensitive. Rules:

  • Cache keyed by (spec, query_hash) with a short TTL (hours–days), not forever — queries drift, and a stale cache hides that.
  • Don't log raw queries into the cache table; the hash is enough for lookup but you lose debuggability — keep a separate, access-controlled query log if you need it (03.10).
  • For multi-tenant systems, scope the cache per tenant or accept that a shared cache can leak "someone asked about X" via timing — see 06.6 for the tenancy model this plugs into.

5.6 Invalidation on model change#

The cache makes model changes safer (old keys never collide with new) but doesn't make them free: a model change means every document needs a fresh vector, which is a full re-embed. 05.9 owns incremental ingestion and the re-embed-on-change pattern; the embedding-side contract is: the cache key's spec IS the version boundary. When spec.version changes, old rows are dead weight — delete them (they also hold vectors you may need to drop for erasure requests, 02.3, 10.7).

For chunk-level reuse during incremental ingestion: if only some chunks changed, their content hashes are unchanged → cache hits → only new/edited chunks hit the embedder. That's the whole point of keying on text_hash: unchanged text is free forever, under the same spec.


Part 6: Preprocessing for embeddings#

Deep-dive

6.1 What to embed#

05.6 and 05.7 own how to chunk; this is the narrower question of what string goes into the embedder for each chunk:

Candidate Embed it? Why
Chunk body text only ✅ Default The content being searched
Title + body ✅ Often better The title carries topic signal the body buries; format as title: X | text: Y (Gemini-2 style) or "{title}\n\n{body}"
Breadcrumbs / section path ✅ For hierarchical docs "Getting started > Billing > Refunds" disambiguates short chunks
Metadata (dates, IDs, authors) ❌ Usually not Numbers/IDs embed poorly (02.3, 10.6); keep them as filters, not vector content
Boilerplate (nav, footer, "cookie" text) ❌ Adds tokens, cost, and noise — every page's vector drifts towards the boilerplate

6.2 Normalization for embeddings#

05.5 owns general text cleaning; embedding-specific rules:

Transform Do it? Reason
Collapse whitespace/newlines ✅ "a b" vs "a b" tokenize differently; consistency matters more than beauty
Unicode NFC normalization ✅ é as one codepoint vs e+accent are different token streams
Lowercasing ⚠️ Myth-busted Modern tokenizers/models handle case; lowercasing can hurt (proper nouns, code identifiers). Test on your data, don't assume
Strip HTML/markup ✅ <p> tags become tokens that mean nothing
Strip boilerplate ✅ See 6.1
Truncate to model limit ✅ Deliberately Never let the model truncate silently (02.3, 5.7); chunk instead
Deduplicate before embedding ✅ Exact-duplicate chunks produce identical vectors — embed once, reference many (5.3 makes this free)

The meta-rule: whatever you do, do it identically at index and query time, and version it. The preprocessing field in EmbedSpec exists precisely so a change here invalidates the cache instead of silently mixing vector spaces.

6.3 Embedding structured records#

Not everything you embed is prose. Templates keep records consistent:

python
def embed_invoice_record(inv):
    """Structured record -> stable text for embedding."""
    return (f"Invoice {inv['number']} from {inv['vendor']} "
            f"for {inv['amount']} {inv['currency']}, "
            f"status {inv['status']}, dated {inv['date']}")

Rules: fixed field order, explicit labels, no JSON dumps (key order and punctuation add noise), and the same template at query time if you embed queries of the same shape. For tabular data, embed the row rendered as text, not the raw CSV line — structure is signal, syntax is noise.


Part 7: Cost modelling#

7.1 The cost equation#

Embedding cost has three additive parts, and people routinely forget the third:

text
total_cost = API_tokens_cost + storage_cost + reembed_cost
Term Formula Scales with
API tokens total_input_tokens × price_per_1M / 1e6 Corpus size × avg chunk tokens × re-embeds
Storage N × dims × bytes_per_number (+ index overhead) N, dims, dtype
Re-embed full_corpus_cost × number_of_model_changes How often you switch models

Prices are volatile — never hard-code them. 03.7, Part 4 builds a prices.yaml + loader for exactly this; the calculator below takes price as a parameter so you plug in whatever the provider's pricing page says today.

7.2 The cost calculator#

Pure Python, real output (parameters below are illustrative placeholders, not current prices):

python
def embedding_cost_usd(num_texts, avg_tokens_per_text, price_per_1m_tokens,
                       batch_discount=1.0, dims=0, bytes_per_float=4):
    tokens = num_texts * avg_tokens_per_text
    api_cost = tokens / 1e6 * price_per_1m_tokens * batch_discount
    storage_gb = num_texts * dims * bytes_per_float / 1e9 if dims else 0.0
    return tokens, api_cost, storage_gb

# ILLUSTRATIVE parameters only — look up real prices on each provider's page.
for label, price in [("illustrative cheap model", 0.02), ("illustrative large model", 0.13)]:
    tokens, cost, gb = embedding_cost_usd(
        num_texts=2_000_000, avg_tokens_per_text=350,
        price_per_1m_tokens=price, dims=1536)
    print(f"{label}: {tokens/1e9:.2f}B tokens -> API ${cost:,.0f}, "
          f"vectors {gb:.1f} GB (float32, 1536-d)")
tokens, cost, _ = embedding_cost_usd(2_000_000, 350, 0.02, batch_discount=0.5, dims=1536)
print(f"same job via 50%-off batch API: ${cost:,.0f}")
Output3 lines
illustrative cheap model: 0.70B tokens -> API $14, vectors 12.3 GB (float32, 1536-d)
illustrative large model: 0.70B tokens -> API $91, vectors 12.3 GB (float32, 1536-d)
same job via 50%-off batch API: $7

Reading it: 2M chunks × 350 tokens = 700M tokens. At illustrative $0.02/1M that's ~$14; at $0.13/1M ~$91. Storage at 1536 dims × 4 B is 12.3 GB — small next to the API bill for a one-off, but it dominates query-time memory and index size over the corpus's life. The batch discount halves the API term.

7.3 Dry-run mode: estimate before you spend#

Before any real job, run a dry run that counts tokens without calling the embedder:

python
import math

def estimate_tokens(text: str) -> int:
    """~4 chars/token heuristic — swap for tiktoken or the provider's
    counter when you need the real number (this is only an estimate)."""
    return max(1, math.ceil(len(text) / 4))


def dry_run_cost(chunks, price_per_1m, count_tokens, dims=1536):
    total = sum(count_tokens(c) for c in chunks)
    storage_gb = len(chunks) * dims * 4 / 1e9
    print(f"{len(chunks):,} chunks, ~{total:,} tokens")
    print(f"est. API cost @ ${price_per_1m}/1M: ${total/1e6*price_per_1m:,.2f}")
    print(f"est. float32 storage ({dims}-d): {storage_gb:.1f} GB")


# Demo corpus: five realistic chunks repeated into a 500K-chunk backfill.
demo_chunks = [
    "Refund policy: returns are accepted within 30 days of delivery for "
    "unused items in original packaging. To start a return, open the order "
    "in your account, choose 'Return item', and print the prepaid label. "
    "Refunds are issued to the original payment method within 5 business "
    "days of the warehouse receiving the package.",
    "Two-factor authentication: open Settings, choose Security, then "
    "'Two-factor authentication', and pick an authenticator app or SMS. "
    "Scan the QR code with your app, enter the 6-digit code it shows, and "
    "save your recovery codes somewhere safe — they are shown only once.",
    "Invoices and billing: every invoice is available as a PDF on the "
    "Billing page of your account. You can download past invoices, update "
    "the billing address, add a purchase-order number, or change the "
    "payment method. Questions about a charge go to billing@example.com.",
    "Shipping: standard delivery takes 5-10 business days within the "
    "country and 10-20 internationally. Expedited shipping arrives in "
    "2-4 business days for an extra fee shown at checkout. You'll get a "
    "tracking number by email as soon as the order leaves the warehouse.",
    "Contact support: use the help widget at the bottom of any page for "
    "instant answers, or email support@example.com for account-specific "
    "issues. Include your account email and order number so we can find "
    "your records quickly. Phone support runs 9am-6pm on weekdays.",
]
corpus_chunks = demo_chunks * 100_000        # 500,000 chunks
# ILLUSTRATIVE price — check the provider's pricing page for the real one.
dry_run_cost(corpus_chunks, price_per_1m=0.02, count_tokens=estimate_tokens)
Output3 lines
500,000 chunks, ~34,600,000 tokens
est. API cost @ $0.02/1M: $0.69
est. float32 storage (1536-d): 3.1 GB

Two things the numbers teach: half a million chunks cost under a dollar of API tokens at illustrative prices — embedding APIs are cheap per token, so the bill is dominated by re-embeds (7.4) and storage/index over the corpus's life, not the first pass. And the estimate is only as good as count_tokens: the ~4-chars/token heuristic is fine for a sanity check, but run tiktoken (or the provider's counter) on a sample of real chunks before committing to a backfill. Make dry_run a first-class mode of your ingestion job — same code path, embedder swapped for a counter — so it catches "we're about to embed 40M tokens" before the invoice does.

7.4 Re-embedding cost and model changes#

Every model change is a full corpus re-embed — there's no partial migration (vectors from different models don't mix, 02.3, 7.5). Budget it as corpus_cost each time, and amortize: a model that's 10% better but costs 3× per token may not pay back unless you re-embed rarely. The Voyage-4 family's documented shared space (including the open-weight voyage-4-nano) and Cohere's embed-v5.0-pro/embed-v5.0-fast pair (06.1) are the exceptions that prove the rule — within a documented-compatible family you can switch sizes (index with the large model, query with the cheap one) without re-embedding.

7.5 Query-time vs batch vs local: the break-even#

API real-time API batch Local model
Cost per token list price ~50–67% of list hardware + ops, ~zero marginal
Latency typically ~50–500 ms RTT (order of magnitude — measure on your path) hours typically ~5–50 ms on CPU/GPU
Best for query path, small jobs backfills, re-embeds high-QPS query path, privacy, offline

Local vs API break-even is arithmetic, not ideology: local_cost = gpu_hours × $/hr + ops; api_cost = tokens × price. For a query path doing 10M short embeddings/day, a small local model on one GPU often beats API cost and latency — but you carry model ops, updates and quality risk. For a document corpus embedded once, API batch is almost always cheaper than standing up GPU capacity. The decision table in Part 13 consolidates this.


Part 8: Latency of the query path#

Deep-dive

Query embedding sits before the vector search on every request — its latency is added to every search. Budget it deliberately:

Component Typical cost Lever
DNS + TCP + TLS handshake ~1 RTT (typically ~50–200 ms cold; order of magnitude — measure yours) Reuse the client/connection (03.1, 7.5)
Request → first byte provider processing Smaller model, fewer dims don't help latency much; region does
Regional endpoint cross-region typically adds ~50–150 ms Use the provider's nearest region if offered
Cache hit < 1 ms Query cache (5.5)
Local small model typically ~5–50 ms on CPU sentence-transformers MiniLM-class on CPU

Rules:

  • Create the client once, reuse it — a new OpenAI()/genai.Client() per query pays connection setup every time (03.1).
  • Set an explicit timeout sized to your SLO (03.8, Part 6); an embedding call that hangs is a hung search.
  • The query path should never batch — one text, one call, keep-alive.

8.1 Timeouts and fallbacks#

When the embedding API is down or slow, search doesn't have to be:

Fallback What you lose When it's acceptable
Serve keyword/BM25 only Semantic recall Always better than an error page; 06.8 owns hybrid
Serve cached/stale vectors for repeated queries Freshness Only with the query cache and a clear TTL
Degrade to a smaller/faster local model Some quality If you run one anyway
Return "search degraded" to the user Nothing silently Honest UX; pair with alerting

Part 9: Normalization, dtype and storage#

9.1 The dtype ladder#

Format Bytes/dim Quality When
float32 4 Reference Default; store this if unsure
float16 2 ~lossless for normalized embeddings Halves memory; most DBs accept it
int8 1 Small recall loss, needs calibration 4× smaller; Voyage/Cohere/Mistral can emit it directly
binary 1/8 Largest loss; needs rescoring 32× smaller; candidate generation + float32 rescore

02.3, 10.2 showed int8/binary on a toy set; 06.4 owns index-level quantization (PQ, SQ). This lesson's job is the storage and measurement discipline.

9.2 Storage formats#

Format Good for Notes
NumPy .npy Prototypes, single-node brute force Simple, fast mmap; no metadata
Parquet / Arrow Columnar storage, analytics, interchange pyarrow list/fixed-size-list columns; compresses well
SQLite + blob Embedded, single-file Fine to ~millions of rows; brute-force scan
pgvector vector/halfvec/bit Postgres-native halfvec = float16, bit = binary; 06.5 owns it
Dedicated DB Production scale Qdrant/Chroma/etc.; 06.5

The choice is mostly "do you already run Postgres / need CRUD / need ANN at scale" — which is 06.5's decision, not this lesson's.

9.3 Memory arithmetic for N vectors#

text
raw_bytes = N × dims × bytes_per_number
index_overhead ≈ 1.2–2× raw (HNSW graphs, payloads) — estimate, measure yours
RAM_needed ≈ hot_vectors × raw_bytes + index_overhead

For 10M chunks at 1536 dims: float32 = 61.4 GB raw — already large for RAM; float16 = 30.7 GB; int8 = 15.4 GB. This is why dimension choice (06.1) and dtype are cost decisions, and why 06.4's quantization exists.

9.4 Measuring compression quality#

Never compress on faith — measure recall@k vs the float32 ground truth on your own queries. The metric plus a small synthetic harness (clustered data, seeded — swap in your real vectors for the real answer):

python
import numpy as np

def recall_at_k(queries, vecs_exact, vecs_approx, k=10):
    """Fraction of exact-top-k that approx-top-k also returns."""
    def topk(Q, M):
        return np.argsort(-(Q @ M.T), axis=1)[:, :k]
    exact, approx = topk(queries, vecs_exact), topk(queries, vecs_approx)
    return float(np.mean([len(set(a) & set(b)) / k
                          for a, b in zip(exact, approx)]))

# Harness: 20 tight clusters of 256-dim unit vectors + 50 queries.
rng = np.random.default_rng(42)
N, D, K, NQ = 2000, 256, 10, 50
centres = rng.normal(size=(20, D))
labels = rng.integers(0, 20, size=N)
V = centres[labels] + 0.6 * rng.normal(size=(N, D))
V /= np.linalg.norm(V, axis=1, keepdims=True)
queries = centres[rng.integers(0, 20, size=NQ)] + 0.3 * rng.normal(size=(NQ, D))
queries /= np.linalg.norm(queries, axis=1, keepdims=True)

# int8: per-dimension min/max calibration fit on a held-out sample
lo, hi = V[:500].min(axis=0), V[:500].max(axis=0)
scale = (hi - lo) / 255.0
scale[scale == 0] = 1.0
Q8 = np.clip(np.round((V - lo) / scale) - 128, -128, 127).astype(np.int8)
V8f = (Q8.astype(np.float32) + 128) * scale + lo
print(f"dataset: {N} vectors x {D} dims, {NQ} queries, top-{K}")
print(f"int8  recall@{K}: {recall_at_k(queries, V, V8f, K):.3f}   "
      f"({D} B/vector vs {D * 4} B float32)")

# binary: sign bits nominate 200 candidates, float32 rescores them
Vb = (V > 0).astype(np.int8)
Qb = (queries > 0).astype(np.int8)
agree = Qb @ Vb.T                              # per-pair sign agreement
cands = np.argsort(-agree, axis=1)[:, :200]    # oversample ~20x
exact = np.argsort(-(queries @ V.T), axis=1)[:, :K]
rescored = np.array([
    c[np.argsort(-(queries[i] @ V[c].T))[:K]] for i, c in enumerate(cands)
])
rb = float(np.mean([len(set(a) & set(b)) / K for a, b in zip(exact, rescored)]))
print(f"binary+rescore recall@{K}: {rb:.3f}   "
      f"(1 bit/dim + float32 rescore of top-200)")
Output3 lines
dataset: 2000 vectors x 256 dims, 50 queries, top-10
int8  recall@10: 0.908   (256 B/vector vs 1024 B float32)
binary+rescore recall@10: 1.000   (1 bit/dim + float32 rescore of top-200)

int8 with per-dimension calibration kept ~91% of the top-10 here; binary with oversample-and-rescore matched exactly — because rescoring with the true vectors repairs the candidate list's errors. The lesson: binary is a candidate generator, not a ranker. Always pair aggressive compression with a float32 (or float16) rescore stage, and always measure recall on your data — synthetic clusters flatter compression that real, noisier embeddings wouldn't.


Part 10: Embedding at scale#

Deep-dive

10.1 The million-chunk job#

At millions of chunks the pipeline stops being "a loop" and becomes a distributed job:

flowchart TB
    subgraph job ["Embedding job (resumable)"]
        MAN["Manifest<br/>chunk_id, text_hash, status"] --> SHARD["Shards<br/>(by hash / range)"]
        SHARD --> W1["Worker 1"] & W2["Worker 2"] & W3["Worker N"]
        W1 & W2 & W3 --> CKPT[("Checkpoint store<br/>done-set per shard")]
        W1 & W2 & W3 --> OUT[("Vector store<br/>idempotent upserts")]
    end
    OUT --> VAL["validate_embeddings<br/>+ sanity queries"]

The non-negotiables, all covered above but worth restating as a checklist:

  • Shard the work by chunk-ID range or content-hash so workers don't overlap; each shard checkpoints independently.
  • Idempotent writes: upsert by chunk ID; a re-run of shard 7 must be a no-op, not duplicates.
  • GPU batching for local models: largest batch_size memory allows, length-sorted (2.4).
  • Spot/preemptible instances for local GPU jobs: fine because the job is checkpointed — a preemption costs one shard's redo, not the corpus.
  • Monitor: chunks/sec, tokens/sec, $/hour, failure rate per batch, cache hit ratio. Alert on failure-rate spikes and cost-per-1K-chunks drift.

10.2 Backfills and blue/green re-embedding#

A model change or preprocessing change is a backfill: re-embed the whole corpus under the new spec. 05.9 and 06.1 cover the migration pattern; the embedding-side shape is blue/green:

  1. Build the new index (new spec) in parallel — "green" — while "blue" (old) keeps serving.
  2. Write new content to both during the transition.
  3. Compare on your eval set (06.10); switch queries to green.
  4. Keep blue until confidence, then drop it — and drop its vectors (they're also a privacy liability, 02.3, 10.7).

Never do an in-place re-embed that leaves the index half-old/half-new — that's the mixed-models failure (02.3, 7.5) at scale.

10.3 Freshness#

"How quickly does new content become searchable?" = ingestion latency + embedding latency + index-commit latency. For API sync embedding that's minutes; for batch-API backfills it's hours. If your product needs near-real-time search, the embedding step must be synchronous per document (embed on write, before the doc is marked searchable) — which is another argument for the query-path embedder being fast (Part 8).


Part 11: Quality guards#

11.1 What can go wrong#

Failure Symptom Caught by
NaN / inf values Vectors that break similarity maths validate_embeddings
All-zero vectors Failed/empty inputs embedded as zeros norm check
Wrong dimensions Shape mismatch at insert dimension check
Un-normalized vectors Dot-product scores > 1 or meaningless norm check
Near-duplicate vectors One chunk's vector copied to many duplicate-pair check
Mixed specs in one index Silent quality collapse spec guard (06.1)
Silent truncation Long docs embed only their first N tokens token counting upstream (05.10)

11.2 validate_embeddings: full code#

Runs on any batch of vectors before they're written — pure NumPy, runs as-is. It assumes unit-normalised vectors (every model in 06.1 emits them); the norm check runs whenever the input is a 2-D array, with or without expected_dim:

python
import numpy as np

def validate_embeddings(vectors, expected_dim=None, norm_tol=1e-3, name="batch"):
    """Return human-readable problems; ['...: OK'] means clean."""
    problems = []
    try:
        arr = np.asarray(vectors, dtype=np.float32)
    except (ValueError, TypeError):
        return [f"{name}: ragged input — vectors have different lengths"]
    if arr.ndim != 2:
        return [f"{name}: expected 2-D array, got shape {arr.shape}"]
    n, d = arr.shape
    if expected_dim is not None and d != expected_dim:
        problems.append(f"{name}: dimension {d} != expected {expected_dim}")
    if not np.isfinite(arr).all():
        problems.append(f"{name}: {int((~np.isfinite(arr)).sum())} "
                        f"non-finite values (NaN/inf)")
    norms = np.linalg.norm(arr, axis=1)
    zero = int((norms == 0).sum())
    if zero:
        problems.append(f"{name}: {zero} all-zero vectors")
    off = np.abs(norms - 1.0) > norm_tol
    if off.any():
        problems.append(f"{name}: {int(off.sum())} vectors not unit-length "
                        f"(norms {norms[off][:3].round(3).tolist()}...)")
    if n > 1:
        # Cosine, not raw dot product: normalise first so a large-norm
        # vector can't fake similarity. Zero rows stay zero.
        unit = arr / np.maximum(norms[:, None], 1e-12)
        sims = unit @ unit.T
        np.fill_diagonal(sims, -np.inf)
        dup = int(np.triu(sims > 0.9999, k=1).sum())  # unordered pairs only
        if dup:
            problems.append(f"{name}: {dup} near-duplicate pairs "
                            f"(cos > 0.9999)")
    return problems or [f"{name}: OK ({n} x {d})"]


# Deliberately broken inputs, plus one clean batch.
rng = np.random.default_rng(7)
good = rng.normal(size=(5, 8)).astype(np.float32)
good /= np.linalg.norm(good, axis=1, keepdims=True)
bad_dim = [list(row) for row in good] + [list(rng.normal(size=16))]
with_nan = good.copy(); with_nan[2, 3] = np.nan
zeros = good.copy(); zeros[1] = 0.0
unnormalized = good.copy(); unnormalized[0] *= 3.0
dup = np.vstack([good, good[0:1]])

for nm, v in [
    ("good", good), ("bad_dim", bad_dim), ("with_nan", with_nan),
    ("zeros", zeros), ("unnormalized", unnormalized), ("dup", dup),
]:
    for p in validate_embeddings(v, expected_dim=8, name=nm):
        print(" ", p)
Output7 lines
  good: OK (5 x 8)
  bad_dim: ragged input — vectors have different lengths
  with_nan: 1 non-finite values (NaN/inf)
  zeros: 1 all-zero vectors
  zeros: 1 vectors not unit-length (norms [0.0]...)
  unnormalized: 1 vectors not unit-length (norms [3.0]...)
  dup: 1 near-duplicate pairs (cos > 0.9999)

Two honest caveats the output teaches:

  • Cosine can't see scaling — by design. The "unnormalized" batch was one vector ×3: the pair check correctly ignores it (cosine is scale-invariant), and the norm check is what catches it. That's why both checks exist — similarity verifies direction, norms verify scale.
  • Near-duplicates are counted as unordered pairs. np.triu counts each (i,j) once, so dup's single copied row reports 1, not 2 — the old raw-dot-product version both miscounted and, worse, flagged scaled vectors as duplicates because it never normalised first.

11.3 Where it runs#

  • Per batch, before write: cheap, catches provider-side corruption.
  • Per job, after completion: aggregate stats (mean norm, % non-finite, dup rate) into your job report.
  • On a schedule against the live index: catch drift (02.3, 10.5) — a sudden norm shift means the model or preprocessing changed upstream.

11.4 Sanity query tests#

After each index build or model change, run a fixed set of known queries with known-relevant chunks and check they still rank top-k (05.10 owns data-quality checks; 06.10 owns retrieval metrics). A pipeline that produces valid vectors can still produce worse vectors — validation checks shape, sanity queries check meaning. This is the cheapest regression test your search will ever have.


Part 12: Embedding other things#

Deep-dive

The pipeline you built generalises — the same batching/caching/validation machinery works for any text:

What Notes
Queries Same embedder, task_type="query"/prefix side. Query rewriting before embedding is covered in 06.10 and Module 07 — link, don't build here
Images / multimodal gemini-embedding-2, voyage-multimodal-3.5, the Jina v5-text/v5-omni families — same pipeline, different modality; 02.3, 10.4
Tables / code / structured Render to text template first (6.3); code has domain models (voyage-code-4, jina-code-embeddings)
Conversations / profiles Embed a rendered summary, not raw turns; user/item vectors power recommendations (02.3, 8.3)
Clusters / centroids Mean of member vectors ≈ cluster centroid for exploration/dedup

12.1 Clustering and dedup — a short example#

Pseudo-vectors stand in for real embeddings so the whole pattern runs keyless — hash each word into one of 16 dims, L2-normalise, then rank pairs by cosine. Swap the pseudo-vector builder for your Embedder and the maths is identical:

python
import hashlib
import numpy as np

texts = [
    "Reset your password from the sign-in page.",
    "Forgot your password? Use 'Forgot password' to reset it.",
    "Refunds are issued within 14 days of return.",
    "You can return items within 30 days for a refund.",
    "Our mobile app is on iOS and Android.",
    "Download the app from the App Store or Google Play.",
]

# Pseudo-vectors for the demo: count hashed words in 16 dims.
V = np.zeros((len(texts), 16), dtype=np.float32)
for i, t in enumerate(texts):
    for w in t.lower().replace("'", "").split():
        h = int(hashlib.md5(w.encode()).hexdigest()[:8], 16)
        V[i, h % 16] += 1.0
V /= np.linalg.norm(V, axis=1, keepdims=True)

S = V @ V.T
pairs = sorted(
    ((S[i, j], i, j)
     for i in range(len(texts)) for j in range(i + 1, len(texts))),
    reverse=True)
print("most similar pairs:")
for s, i, j in pairs[:3]:
    print(f"  {s:.3f}  #{i} ~ #{j}   "
          f"{texts[i][:34]!r} ~ {texts[j][:34]!r}")
Output4 lines
most similar pairs:
  0.645  #4 ~ #5   'Our mobile app is on iOS and Andro' ~ 'Download the app from the App Stor'
  0.600  #2 ~ #3   'Refunds are issued within 14 days ' ~ 'You can return items within 30 day'
  0.572  #1 ~ #3   "Forgot your password? Use 'Forgot " ~ 'You can return items within 30 day'

The top two pairs are exactly the paraphrase pairs — the two app-download phrasings (#4~#5) and the two refund phrasings (#2~#3) — even with crude word-count vectors; real embeddings sharpen this further. The pattern: embed once → cosine matrix → threshold or cluster. For real dedup at scale you'd use an ANN index (06.3/06.4) rather than the full N×N matrix, which is O(N²) memory — fine to ~10K items, not beyond.

12.2 Classification on top of embeddings#

Embeddings + a small classifier beats zero-shot for repeated tasks: embed labelled examples once, train logistic regression / a linear probe, classify new items by their vector. scikit-learn makes it a few lines — 06.1 covers the selection side; the engineering point here is that the classifier is cheap to retrain when you re-embed, so keep the pipeline's EmbedSpec with the trained artifact.

python
# Illustrative — pip install scikit-learn. X_train/y_train come from your
# Embedder + labels (cached per 5.3); new_vectors are fresh embeddings.
from sklearn.linear_model import LogisticRegression

clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
label_scores = clf.decision_function(new_vectors)   # rank by score

Two production notes: store the fitted clf with its EmbedSpec — a classifier trained on text-embedding-3-small vectors is meaningless on text-embedding-3-large vectors (or on a different dimensions setting), same mixed-space trap as the index itself. And keep a held-out labelled set: when you re-embed under a new spec, refit and compare accuracy before cutting over (06.10 owns the eval harness).

12.3 Beyond search: tables, code, conversations and profiles#

Everything above assumed chunks of prose. The same machinery embeds anything you can render as a stable string — but what you render changes per use-case, and that choice is where the engineering lives. 6.3 showed the rule for records; the rest:

Tables and structured records — embed the row rendered as labelled text ("Invoice INV-1042 from Acme Ltd for 1,240.00 EUR, status paid, dated 2026-10-02"), never the raw CSV/JSON line: field labels carry meaning, syntax is noise. Embeddings capture content similarity — two invoices of similar size from similar vendors land near each other — but they can't do equality: status="paid" vs "unpaid" is a filter for 06.6, not a vector dimension. Keep categorical and numeric fields as payload metadata and embed only the descriptive text.

Code — the unit of embedding is the symbol, not the file: a function with its docstring, a class with its signature, rarely a whole module. Domain-tuned models exist for a reason — voyage-code-4 and codestral-embed (both in 06.1's tables) are trained on code, so identifiers, types and control flow carry signal a prose model dilutes. Two practical notes: normalise formatting before embedding (minified vs formatted code is the same program with different tokens), and remember embeddings answer "what is this like", not "is this identical" — near-duplicate detection wants a similarity threshold plus a diff, not cosine alone.

Conversations — never embed raw transcripts: they overflow input limits, drown the signal in pleasantries, and drag PII into your vector store. Embed a rendered summary or the customer's problem statement — for support analytics that's usually the first user message or an LLM-written one-line intent. The clustering machinery from 12.1 then works unchanged: cluster conversation embeddings to surface recurring issue themes.

Recommendations and profiles — the two-sided case: you need user and item vectors in one space. The classical pattern (what matrix factorisation did with learned factors) maps cleanly onto embeddings: embed each item's content (title + description), represent a user by the centroid of the items they interacted with, and ANN-search items nearest that centroid — "users who liked X also liked Y" falls out of the same index you already built. Production recommenders replace the centroid with learned two-tower encoders trained to map users and items into a shared space; 09.9 covers the multimodal version of the same idea, and Module 13A owns the product-metric side (engagement, retention, unit economics). Two caveats specific to this use-case: the eval is recall on held-out interactions, not relevance labels (06.10), and cold-start users have no history — fall back to content embeddings or popularity, never to an empty vector.


Part 13: A decision table for the whole pipeline#

Reference
Decision Small job (<10K) Medium (10K–1M) Large (>1M)
Request packing Simple list batches Token-aware pack_batches Sharded + checkpointed
Concurrency Sequential OK Bounded async (8–32) Workers + per-shard checkpoints
Provider batch API Skip Maybe (cost) Yes (cost + throughput)
Cache In-memory dict SQLite/Redis Shared store, hit-ratio monitoring
Storage .npy/SQLite Parquet/pgvector Dedicated DB (06.5)
dtype float32 float32/float16 int8/binary + rescore (06.4)
Validation Per batch Per batch + job stats Per batch + scheduled drift checks

Parts 2–11 each name their own failure modes; this gallery collects the pipeline-level ones — the bugs that don't crash, they corrupt. The pattern to internalise: almost every entry is a silent failure, caught by an explicit check, not by an exception.

Failure Symptom Detection Fix
Order corruption — vectors attached to wrong chunks Plausible-but-wrong results; nothing errors index/custom_id assertions; sanity queries; spot-check vector↔text pairs Sort by the explicit index field; key writes by chunk ID (2.6)
Silent preprocessing change Quality drift while cache hit ratio stays ~100% Hit-ratio monitoring; sanity queries after every deploy preprocessing in EmbedSpec; bump it on any cleaner change (5.2)
Mixed specs in one index Retrieval quality collapses with no error Spec stored per vector; write-time guard; sanity queries Blue/green re-embed; refuse mixed-spec writes (10.2)
Poison item fails a whole batch 400/422 on a request containing one bad text Request error naming the item Filter empties upstream; bisect to isolate; quarantine (2.7)
Rate-limit stampede Sustained 429s; throughput collapses 429 rate and Retry-After headers in metrics Pool-wide backoff; budget TPM not just RPM (3.2, 3.3)
Duplicate texts embedded repeatedly Bill exceeds what the corpus size implies Embedder call logs; hit ratio ~0% on re-runs Content-hash cache; dedupe misses by key (5.3)
OOM mid-batch on local GPU CUDA OOM crash at batch N of M The crash itself Smaller batch_size, length-sort, checkpoint (2.4, 3.5)
Lost work on crash/preemption Worker dies; shard restarts from zero Throughput drops to 0 for one shard Per-batch checkpoints; idempotent upserts (3.5)
Batch output expired or unreconciled Results 404 (e.g. Jina's 24 h expiry) or orphaned vectors Coverage check: every custom_id accounted for Download on completion; reconcile by custom_id, never position (4.3)
NaN/zero/wrong-dim vectors written NaN scores, garbage rankings downstream validate_embeddings per batch Quarantine the batch; inspect the provider response (11.2)
Silent truncation of long inputs Long-document queries miss content past the cap Token counts vs chunk lengths, upstream Deliberate chunking; count before sending (6.2)

Common misconceptions#

Misconception Reality
"One text per API call is fine." It's the slowest, most rate-limit-expensive option. Batch under the token cap (Part 2).
"The provider returns results in order." Usually, but verify index/custom_id — order bugs silently mislabel vectors (2.6).
"Batch API is just a bigger batch." It's asynchronous, discounted and separately quota'd — hours of turnaround for ~50% off. Different tool for backfills (Part 4).
"Caching embeddings is premature optimisation." Re-embedding unchanged chunks is pure waste; the content-hash cache makes incremental ingestion nearly free (Part 5).
"The cache makes model changes free." It prevents collisions, not cost — a model change still re-embeds everything (5.6).
"Lowercase everything before embedding." Modern models handle case; lowercasing can hurt proper nouns and code. Test, don't assume (6.2).
"Cheaper embedding model = cheaper project." Re-embedding cost on every model change can dwarf per-token savings (7.4).
"int8/binary vectors are just as good." They need calibration and usually a float32 rescore; measure recall on your data (9.4).
"If the vectors are valid, search is fine." Validation checks shape, not meaning — run sanity queries after every build (11.4).
"When the embedding API is down, embed with a different model." Different model = different vector space = garbage results with no error. Fall back to keyword search instead (8.1).

Key takeaways#

  • Batch under token caps, not item caps. Every provider limits total tokens per request far below inputs × per-input; pack greedily, preserve order by explicit index, isolate poison items.
  • Concurrency is for throughput, batch APIs are for cost. Async + bounded semaphore for live jobs; provider batch APIs (~50% off, hours) for backfills and re-embeds.
  • Budget TPM, not just RPM — embedding requests are token-heavy, so the token ceiling binds first.
  • Cache by (model, version, dims, task_type, preprocessing_hash, text_hash). It makes retries, re-ingestion and incremental updates nearly free, and the spec IS your invalidation boundary.
  • Embed deliberately: title+body, strip boilerplate and markup, never embed metadata/IDs as vector content, version your preprocessing.
  • Cost = API tokens + storage + re-embeds. Model prices as parameters, dry-run before you spend, and remember every model change is a full re-embed.
  • Query-path embedding is latency-critical: reuse connections, cache repeated queries (with privacy care), set timeouts, and fall back to keyword search — never to a different vector space — when the API is down.
  • Store float32 until you measure. int8/binary need calibration and a rescore stage; verify recall@k against float32 on your own queries.
  • At scale: shard, checkpoint, upsert idempotently, monitor, and re-embed blue/green.
  • Validate every batch (NaN/zero/dim/norm/dup) and run sanity queries after every build — valid vectors can still mean worse search.

Terms introduced in this lesson#

Term One-line definition
Embedder / EmbedSpec The provider-agnostic seam and the config tuple that determines a vector
Token-aware batching Packing texts into requests under a token budget, not just an item count
Greedy first-fit packing O(n) batching that fills each request until the next item would overflow
Order preservation Matching result i to input i via explicit index/custom_id, never position assumptions
Partial failure One bad item in a batch; isolate via bisection, quarantine, don't abandon the job
Bounded concurrency A semaphore capping requests in flight so you don't stampede rate limits
TPM / RPM budgeting Tokens-per-minute vs requests-per-minute rate-limit arithmetic
Batch embedding API Provider async job: JSONL in, vectors out, ~50% off, hours turnaround
custom_id reconciliation Joining batch results to inputs by an explicit ID, since output is unordered
Content-hash cache text_hash → vector store keyed by the full EmbedSpec
CachingEmbedder Decorator that serves cache hits and batches only misses to the real embedder
Preprocessing hash Version tag for your cleaning/normalization config, part of the cache key
Dry-run mode Counting tokens and estimating cost without calling the embedder
Re-embedding cost The full corpus re-embed every model change forces
Blue/green re-embedding Building the new index alongside the old, then switching
validate_embeddings Per-batch check for NaN/zero/dim/norm/duplicate vectors
Sanity query test Fixed known queries run after each build to catch quality regressions
Oversample-and-rescore Binary/quantized candidate generation repaired by float32 rescoring

Exercises#

  1. Packing (2.3): write pack_batches with a real token counter (tiktoken cl100k_base) instead of the char heuristic, and measure how different the batch count is on 1,000 real chunks.
  2. Order (2.6): modify embed_in_order to handle a provider that returns results out of order by sorting on index — then break it deliberately and watch the assertion catch it.
  3. Cache (5.3): add a stats() method to CachingEmbedder reporting hit ratio, and a test that a preprocessing change forces re-embedding.
  4. Cost (7.3): take a real corpus (Module 05's handbook chunks), run dry_run_cost with three different avg_tokens estimates, and see how sensitive the bill is to chunk size.
  5. Latency (8.1): implement the keyword fallback — when embed_query raises, return whatever keyword search you have (a trivial in-operator scorer over chunk text is fine; 06.7 builds the real BM25 later). What does the caller see?
  6. Quality (11.2): feed validate_embeddings a batch from a real embedder and a deliberately corrupted one; tune norm_tol until legit vectors pass.
  7. Scale (10.2): sketch the blue/green re-embed as a state machine (states + transitions), then identify where a crash leaves you.
  8. Dedup (12.1): replace the hash pseudo-vectors with real embeddings of the six texts and see if the same pairs surface.
  9. Reconcile (4.4): extend the reconcile function so it also validates each returned vector with validate_embeddings, and so it returns the chunk IDs (not positions) of the casualties. Hint: keep a chunk_ids list in the same order as the JSONL groups and map missing positions through it; the job is complete only when missing is empty.

Check yourself#

  1. Why is token-aware packing necessary when an API already accepts "a list of texts"?
  2. What's the difference between the per-input token limit and the per-request token limit, and which binds first for OpenAI?
  3. Why must you sort by index/custom_id rather than trusting response order?
  4. When does a provider batch API beat bounded async concurrency, and when does it lose?
  5. What six components make up the embedding cache key, and what breaks if you omit preprocessing_hash?
  6. Why does lowercasing before embedding sometimes hurt?
  7. Name the three terms of the embedding cost equation and which is easiest to forget.
  8. Why is a query-embedding cache a privacy concern that a document cache isn't?
  9. What does validate_embeddings check that cosine similarity can't?
  10. Why must an embedding-API fallback be keyword search and never a different embedding model?
  11. int8 vs binary: which needs a rescore stage, and why?
  12. What does blue/green re-embedding protect you from that in-place re-embedding doesn't?

Further resources#


← 06.1 — Embedding Models and APIs in Practice | Module 06 overview | 06.3 — Similarity Metrics and Nearest-Neighbour Search →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close