Mental model
An embedding pipeline turns versioned documents into searchable vectors through deterministic chunking, model inference, and durable storage. A chunk needs a stable key, provenance, and embedding-model version so retries cannot silently duplicate or mix incompatible vectors. Batching raises accelerator utilization, but correctness depends on publishing a complete corpus generation and measuring retrieval quality after the data reaches its index.
Learning outcomes
- Design chunk identifiers that make a retry reproducible while preserving source revision and model provenance.
- Estimate embedding storage and batch execution time from corpus size, vector dimension, and measured batch latency.
- Choose when to use exact search or an approximate index, and activate a fully built corpus generation safely.
Theory
An ingestion run begins with a source snapshot, not an unordered collection of strings. Assign each document a stable identifier and revision, normalize its content under a named preprocessing version, and split it into chunks before embedding. Fixed token windows are easy to parallelize but can cut a table row, code block, or definition across a boundary. Structure-aware splitting preserves headings or records, while overlap carries context across adjacent chunks. Each choice affects retrieval recall, token cost, and the number of rows the index must hold.
Chunk identity is the backbone of safe retries. A useful key includes document ID, source revision, chunk ordinal, normalized content hash, and embedding model version. If a worker finishes inference but loses its database acknowledgement, replaying the same batch should target the same key. Hashing only the text is insufficient: two documents can contain identical text but carry different permissions, source links, or deletion lifecycles. Hashing only a document ID is also insufficient because replacing the source would overwrite old content without recording which revision was embedded.
Sentence-BERT style bi-encoders map a query and each passage independently into a shared vector space. That independence makes corpus encoding parallel: passages can be embedded once, stored, and compared with a query vector later. For query vector q and document vector d, cosine similarity is:
Here q and d are D-dimensional embedding vectors, and ||·||₂ is the Euclidean norm. When the model normalizes each vector to unit length, cosine similarity reduces to a dot product. This equivalence is useful only when the database operator, query preprocessing, and model output agree on normalization and model version; mixing spaces can produce plausible scores with meaningless rankings.
GPU throughput depends on feeding the accelerator batches large enough to amortize launch and transfer overhead. A local worker can group inputs by token length to reduce padding waste. A serving system such as Triton can combine stateless inference requests with a dynamic batcher, but its queue-delay limit is part of the retrieval latency budget. Waiting briefly may improve GPU occupancy; waiting too long makes a user-facing request slow even if vectors per second improves. Measure batch-size distribution, queue wait, padding ratio, GPU utilization, and p95/p99 request latency together.
Storage writes need a separate idempotency boundary from model execution. A worker may complete GPU inference and then time out before receiving the database commit response. A deterministic primary key plus INSERT ... ON CONFLICT turns a replay into an update of the same logical chunk instead of a second searchable passage. For a very large initial load, bulk COPY can move rows more efficiently than one insert per chunk; later incremental updates can use bounded upsert batches. Persist the source revision, model ID, chunking version, content hash, and access-control metadata beside the vector.
Build a new corpus generation away from the active reader path. Write all chunks, verify expected counts and source revisions, create or refresh its approximate nearest-neighbor index, and run retrieval checks before atomically changing the active-generation pointer. This keeps readers from seeing half of a re-embedding job. Retain the old generation until the new one passes recall and authorization checks, then garbage-collect old rows and index pages. The RAG formulation treats the dense index as non-parametric memory; the ingestion system must therefore make that memory versioned and inspectable.
Worked sizing example
Suppose a corpus has 48,000 chunks and the encoder returns 768-dimensional float32 vectors. The vector payload alone uses 48,000 × 768 × 4 = 147,456,000 bytes, or about 140.6 MiB before row headers, metadata, source text, and the HNSW graph. With batches of 256 chunks, the job makes ceil(48,000 / 256) = 188 inference batches. If a measured run takes 0.42 seconds of encoder time per full batch, the compute estimate is about 79 seconds. That figure excludes source reads, tokenization, queue waits, database WAL, index updates, and retries; benchmark each stage under representative concurrency before promising a backfill window.
Trade-offs
Larger batches often increase throughput but consume more device memory and can worsen tail latency while requests wait to be coalesced. Length bucketing saves padding work but adds scheduler complexity and can starve rare long inputs unless they have a bounded queue. Smaller overlap between chunks lowers storage and repeated-token cost; a query that needs a definition spanning the boundary may then miss necessary context. Choose the chunking rule from retrieval evaluation, not from an aesthetic preference for uniform text blocks.
Exact search scans all eligible vectors and provides exact nearest neighbors, which is useful for small corpora and recall baselines. HNSW trades memory and index-build or insertion work for faster approximate queries; pgvector's ef_construction and m affect the graph build and recall/latency trade-off. An index can also change the result set because approximate search may omit a true neighbor. Preserve an exact-search evaluation slice so recall loss is visible after index tuning.
Failure modes and misconceptions
- Re-embedding into the wrong column: A new model can change vector dimension or geometry. Store model/version metadata, validate dimensions before insert, and never compare vectors from incompatible spaces.
- Retry duplication: Random IDs turn a timed-out commit into duplicate passages. Derive stable chunk keys and test replay after a simulated lost acknowledgement.
- Partial generation becomes visible: If a new index is queried before backfill completion, retrieval silently loses documents. Keep an active-generation boundary and verify chunk counts and sampled source coverage before switching readers.
- Chunker drift: Changing tokenization or overlap alters chunk boundaries. Record the chunking version so a backfill can be compared with the prior retrieval set.
- Index tuning hides recall regressions: Higher query speed may drop relevant neighbors. Compare approximate results against exact search on a held-out query set and monitor recall alongside p95 latency.
- Access metadata is dropped: Re-embedding can preserve text and vectors but lose tenant or ACL metadata. Apply authorization filters before candidate content reaches the generator, and include ACL coverage in ingestion verification.
Monitor rows embedded per second, GPU queue delay, batch-size histogram, rejected or retried chunks, conflict counts, WAL growth, index build duration, stale-generation rows, and retrieval recall at a fixed k. A successful backfill is not just a row count: it must make the intended source revision searchable with the expected model, chunk policy, and access boundary.
The sample below assumes a pre-provisioned chunk_vectors table with embedding vector(384), a primary key on chunk_id, and an active pgvector extension. For an initial bulk load, ingest a complete generation first and build its HNSW index before moving the active-generation pointer; incremental updates can use the same stable-key upsert.
Decision scenario
A team re-embeds 20 million support passages with a newer model. The new encoder outputs 1,024 dimensions rather than the active index's 768, and a five-percent canary shows improved click-through but misses several exact-match troubleshooting questions. The safe action is to keep the old generation active, write the new vectors into a compatible versioned schema, verify chunk coverage and ACL metadata, and compare exact-search recall with the approximate index on a held-out query set. Change the active-generation pointer only after the regression is understood and retrieval quality meets its target. Faster encoding does not justify mixing vector spaces or exposing a partial migration.
Implementation pattern
pythonimport hashlibimport osimport numpy as npimport psycopgfrom pgvector.psycopg import register_vectorfrom psycopg.types.json import Jsonbfrom sentence_transformers import SentenceTransformerMODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"BATCH_SIZE = 128model = SentenceTransformer(MODEL_ID)def stable_chunk_id(row: dict) -> str:content_hash = hashlib.sha256(row["text"].encode("utf-8")).hexdigest()parts = [row["generation"], row["document_id"], row["revision"],str(row["chunk_index"]), MODEL_ID, content_hash]return hashlib.sha256("\0".join(parts).encode("utf-8")).hexdigest()def upsert_batch(connection, records: list[dict]) -> int:if not records:return 0texts = [record["text"] for record in records]vectors = model.encode(texts, batch_size=BATCH_SIZE,normalize_embeddings=True, convert_to_numpy=True)if vectors.shape != (len(records), 384):raise ValueError("encoder output shape does not match the pgvector schema")if not np.isfinite(vectors).all():raise ValueError("encoder returned a non-finite vector")values = [(stable_chunk_id(row), row["generation"], row["document_id"],row["revision"], row["chunk_index"], MODEL_ID, row["text"],Jsonb(row["metadata"]), vector)for row, vector in zip(records, vectors, strict=True)]sql = """INSERT INTO chunk_vectors(chunk_id, generation, document_id, revision, chunk_index,model_id, content, metadata, embedding)VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)ON CONFLICT (chunk_id) DO UPDATE SET metadata = EXCLUDED.metadataWHERE chunk_vectors.metadata IS DISTINCT FROM EXCLUDED.metadata"""with connection.cursor() as cursor:cursor.executemany(sql, values)return len(values)with psycopg.connect(os.environ["DATABASE_URL"]) as connection:register_vector(connection)records = [{"generation": "backfill-2026-11-21", "document_id": "doc-42","revision": "rev-8", "chunk_index": 0,"text": "Normalize the canonical chunk before embedding.","metadata": {"source_uri": "s3://docs/doc-42", "tenant": "team-a"}}]upsert_batch(connection, records)