Embedding Cost, Latency and Batching

Batch, cache and parallelise embedding work for large document collections.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 5 · Lesson 8 of 9 · Intermediate

Embedding Cost, Latency and Batching

Batch, cache and parallelise embedding work for large document collections.

Embedding a few hundred chunks takes seconds. Embedding ten million takes planning. This lesson covers the practical side of embedding at scale: estimating cost and time, batching, using a GPU, caching so unchanged text is never embedded twice, and calling embedding APIs in parallel without hitting rate limits.

Estimate before you start

For a hosted API:

cost = total tokens × price per million tokens / 1,000,000

For a local model, measure throughput (chunks per second) on a sample and extrapolate:

import time
from rag_helpers import get_embedder

model = get_embedder()
sample = ["This is a sample sentence of typical chunk length. " * 8] * 512

start = time.perf_counter()
model.encode(sample, batch_size=64, normalize_embeddings=True)
rate = len(sample) / (time.perf_counter() - start)

total_chunks = 2_000_000
print(f"{rate:.0f} chunks/s -> {total_chunks / rate / 3600:.1f} hours for {total_chunks:,} chunks")

Query embedding cost is usually negligible: one short text per question.

Batching

Models process a batch of texts in one pass much faster than the same texts one at a time. encode() batches for you; tune batch_size to your hardware (32 to 128 on CPU, 128 to 1,024 on a GPU, limited by memory). Sorting texts by length reduces wasted padding; sentence-transformers does this internally.

vectors = model.encode(
    texts,
    batch_size=128,
    normalize_embeddings=True,
    show_progress_bar=True,
    convert_to_numpy=True,
)

Use the hardware you have

  • GPU: sentence-transformers uses CUDA or Apple Silicon (MPS) automatically when available. A GPU is often 10 to 50 times faster than a CPU.
  • Half precision on GPU: model.half() roughly doubles throughput with no meaningful quality loss.
  • Optimised CPU backends: sentence-transformers can run models with ONNX Runtime or OpenVINO for faster CPU inference: SentenceTransformer(name, backend="onnx").
  • Multiple processes: model.start_multi_process_pool() spreads encoding across several GPUs or CPU cores.

Cache embeddings by content hash

Documents change a little at a time. If you re-index nightly, most chunks are identical to yesterday's. Caching embeddings by a hash of the model name and chunk text means you only pay for new or changed chunks.

embedding_cache.py
import hashlib
import sqlite3
import numpy as np
from rag_helpers import EMBED_MODEL, embed

class CachedEmbedder:
    def __init__(self, path: str = "embeddings_cache.sqlite"):
        self.db = sqlite3.connect(path)
        self.db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, vector BLOB)")

    @staticmethod
    def key(text: str) -> str:
        return hashlib.sha256(f"{EMBED_MODEL}\n{text}".encode("utf-8")).hexdigest()

    def embed(self, texts: list[str]) -> np.ndarray:
        keys = [self.key(t) for t in texts]
        found = {}
        for i in range(0, len(keys), 500):   # stay under SQLite's parameter limit
            batch = keys[i:i + 500]
            rows = self.db.execute(
                f"SELECT key, vector FROM cache WHERE key IN ({','.join('?' * len(batch))})", batch)
            found.update({k: np.frombuffer(v, dtype=np.float32) for k, v in rows})

        missing = [i for i, k in enumerate(keys) if k not in found]
        if missing:
            new_vectors = embed([texts[i] for i in missing]).astype(np.float32)
            self.db.executemany("INSERT OR REPLACE INTO cache VALUES (?, ?)",
                                [(keys[i], v.tobytes()) for i, v in zip(missing, new_vectors)])
            self.db.commit()
            found.update({keys[i]: v for i, v in zip(missing, new_vectors)})
        print(f"cache hits: {len(texts) - len(missing)}, embedded: {len(missing)}")
        return np.vstack([found[k] for k in keys])

Including the model name in the key means a model change automatically invalidates the cache.

Calling embedding APIs in parallel

Hosted APIs accept batches (often up to 128 or 1,000 texts per request) and enforce rate limits. Send several batches concurrently, retry on rate-limit errors with exponential backoff, and keep concurrency modest:

import asyncio, random

async def embed_batch_with_retry(batch, call_api, max_retries: int = 6):
    for attempt in range(max_retries):
        try:
            return await call_api(batch)
        except Exception as error:               # narrow this to the provider's rate-limit error
            wait = min(60, 2 ** attempt + random.random())
            print(f"retrying in {wait:.1f}s: {error}")
            await asyncio.sleep(wait)
    raise RuntimeError("embedding failed after retries")

async def embed_all(texts, call_api, batch_size: int = 128, concurrency: int = 4):
    semaphore = asyncio.Semaphore(concurrency)
    batches = [texts[i:i + batch_size] for i in range(0, len(texts), batch_size)]

    async def run(batch):
        async with semaphore:
            return await embed_batch_with_retry(batch, call_api)

    results = await asyncio.gather(*(run(b) for b in batches))
    return [vector for batch in results for vector in batch]

Many providers also offer a cheaper batch API for large offline jobs that do not need results immediately.

Checkpoint long jobs

For multi-hour indexing runs, write vectors to storage after each batch (or rely on the cache above). A crash at 90% should not mean starting again from zero.

Key takeaways

  • Estimate time and cost from a measured sample before embedding a large collection.
  • Batch aggressively, use a GPU or an optimised backend, and use half precision on GPUs.
  • Cache embeddings by a hash of model name plus text so re-indexing only embeds changes.
  • Call APIs with bounded concurrency, exponential backoff and checkpoints.