Build a Vector Embedding Versioning and Migration System
databases data-engineering reliability
AI System Design Deep Dive
Embedding Versioning and Migration
Re-embedding a live corpus costs $446. Keeping every answer stable while you do it is the expensive part.
Replacing a building’s foundation while the tenants keep living in it is a solved engineering problem, and the solution is never “lift the building”. You shore up one bay, cut out the old footing under that bay alone, pour the new one, let it cure, move to the next bay. The building never leaves the ground and no apartment is ever unsupported. What makes the job hard is not the concrete. It is that the new footing sits two centimetres higher than the old one, so every doorframe in the finished building is slightly out of square relative to the ones you have not done yet, and the tenants notice the doors long before they notice the foundation.
That is an embedding migration. We have 840 million chunk-level vectors across 212 million source documents, 1,900 tenants, 6,200 queries per second at peak, and a new retrieval tower that is unambiguously better than the one in production. Offline, on a 31,000-query golden set, recall@100 goes from 0.931 to 0.952 and nDCG@10 from 0.604 to 0.642. Every reason to ship it. And then we measured the thing nobody puts in the model card: for the median production query, the overlap between the old top 10 and the new top 10 is 3 documents. Jaccard similarity 0.18. The new epoch is better, and roughly seven out of every ten answers on the first page are different documents.
That number is the whole design brief. A migration that improves the metric still rewrites the product. 1,900 tenants have built saved searches, dashboards, agent prompts, and support macros against the old ranking, and 73 of them have contractual answer-stability language. So we are not allowed to treat this as a data job that finishes when the last vector lands. We have to treat it as a release, which means the embedding version has to be a first-class, addressable, per-tenant, rollback-able thing in the system rather than a model path in a config file.
An embedding migration is a ranking release, not a backfill. The backfill is the cheap, finite, testable part. The expensive part is that you cannot roll back a read: once a user has seen the new answer and adjusted their query to match it, reverting the index does not revert the user.
This post assumes the epoch model from Build a Cross-Modal Embedding Store for Text, Image, and Video, which introduced embedding_epochs as a table, put epoch_id inside the vector record identity, and derived the tower-skew failure and the two-resident-epochs RAM arithmetic. We will not re-derive any of that. We are going to spend this post on everything that one deliberately left out: the online dual-write and shadow-read protocols, backfill scheduling under a live query SLA, interleaved per-epoch traffic splitting instead of a hard cutover, rollback after writes have landed only in the new epoch, dimension changes where the old and new vectors are not even the same shape, and Matryoshka truncation as the migration you do not have to run.
We need to solve for write correctness across two epochs that are both live, a cutover decision made from online evidence rather than an offline metric, and a rollback path that stays open long enough to be useful, simultaneously, without the backfill ever touching the 48ms p99.
Requirements and Constraints
Functional Requirements
- Register an embedding epoch with its tower identity, dimension, normalisation, PQ codebook id, and lifecycle state
- Resolve, per tenant and per request, which epoch serves reads and which epochs accept writes
- Dual-write every ingest to every epoch in
acceptingstate, idempotently and in a defined order - Backfill the historical corpus into a new epoch without ever overwriting a newer live write for the same document
- Report truthful backfill progress, including documents deleted or re-chunked mid-backfill
- Mirror a sampled fraction of production queries against the candidate epoch with no effect on the served response
- Compare epochs on live traffic by interleaving results from both into one page, not by splitting users
- Promote and demote a tenant between epochs as an atomic, audited state transition
- Roll a tenant back to the previous epoch after an arbitrary fraction of writes have landed only in the new one
- Support a candidate epoch whose dimension differs from the current one (1024 to 1536), including a different PQ codebook and a different
efSearch - Expose
epoch_id,epoch_state, andbackfill_watermarkon every query response for debuggability
Non-Functional Requirements
- Latency: 48ms p99, 14ms p50 end to end during migration, identical to steady state. Backfill is not allowed to move either number by more than 2ms.
- Throughput: 6,200 QPS peak, 2,100 QPS average. Backfill ingest up to 19,000 chunks/second when the query tier has spare capacity, 0 when it does not.
- Quality: no tenant may regress more than 1.0
nDCG@10point against its own pre-migration baseline; fleet-widerecall@100must not drop at any point during cutover - Cost: full re-embedding of 840M chunks under $500 of GPU, and total migration infrastructure under $9,000
- Capacity: 223 GB resident for the current epoch, 277 GB for the 1536-dimensional candidate, against 1,152 GB of usable index RAM across 12 nodes
- Rollback: any tenant returnable to the previous epoch within 90 seconds of the decision, for at least 14 days after its promotion
- Durability: zero lost writes across epoch transitions, verified by a per-tenant checksum reconciliation that runs continuously
Constraints
- Current epoch is a 1024-dimensional tower with
L2normalisation, PQ-128,HNSWatM = 16,maxM0 = 32,efConstruction = 200,efSearch = 160 - Candidate epoch is 1536-dimensional, Matryoshka-trained with nested dimensions at 768, 1024, and 1536, PQ-192,
efSearch = 192 - Index nodes are 12 x
r7i.4xlarge: 128 GB RAM, 16 vCPU, 96 GB usable per node after thefp16rescore cache and page-cache reserve - Encoder fleet is
H10080GB at $4.66 per GPU-hour on demand, with spot capacity available for backfill only - Chunking is unchanged between epochs. A chunk boundary change is a different and harder migration, and it is out of scope.
- Out of scope: cross-epoch score comparison (impossible, and the reason interleaving exists), multi-vector or late-interaction retrieval, and distillation of the new tower back into the old dimension
High-Level Architecture
Six components. Four of them exist only because rollback has to stay possible.
The Epoch Registry is the control plane and the only writer of epoch state. It holds one row per epoch and one row per tenant-epoch binding, and every other component reads its decisions rather than inferring them. The Dual-Write Fanout sits in the ingest path and fans each chunk to the encoder for every epoch currently in accepting state, which during a migration is two. The Backfill Scheduler walks the historical corpus into the new epoch, throttled by a signal from the query tier, and maintains the watermark that makes “how far along are we” a real answer instead of a ratio of two moving numbers.
On the read side the Epoch Router resolves the serving epoch for the tenant on the request, and the Shadow Reader mirrors a sampled slice of traffic to the candidate epoch out of band, logging both result sets without ever letting the candidate influence the response. Once shadow comparison looks acceptable, the Interleaving Router takes over for a subset of tenants and builds one page from both epochs using team-draft interleaving, which is what actually produces the promotion decision. The Cutover Controller consumes interleaving outcomes and reconciliation state and executes the per-tenant transitions, including the reverse ones.
A write takes the long path. A document update lands in the ingest log with a monotonic write_lsn from the source of truth, gets chunked, and then fans to two encoders: the 1024-dimensional tower and the 1536-dimensional one. Both produce vectors, both upsert into their own index keyed by (tenant_id, chunk_id, epoch_id), and both carry the write_lsn into the record. That last detail is the entire correctness story of this system, and the next section is about why.
The single most important architectural decision is that the old epoch keeps accepting writes for the full 14-day rollback window after a tenant has been promoted off it. Draining the old epoch the moment reads move away is the obvious optimisation, costs 46 GB of RAM to avoid, and is what turns a 90-second rollback into a six-hour reverse backfill.
The Dual-Write Fanout
Its job is to make sure that a document written during the migration is correct in both epochs, in any interleaving of live writes and backfill writes.
The non-obvious part is that this is not a fanout problem. A smart engineer looks at “write to two places” and reaches for the familiar toolkit: a transactional outbox, two-phase commit across the two index writers, or a Kafka topic with two consumer groups and at-least-once delivery plus idempotent upserts. All of that is correct and none of it is sufficient, because the race that actually loses data is not between the two epochs. It is between the backfill and the live write, inside a single epoch.
Here is the failure, and it is the one every embedding migration hits in week two. The backfill scheduler reads document d at 09:00:00, queues it, and the encoder pool is 40 seconds deep. At 09:00:12 a user edits d. The live path chunks it, embeds it, and upserts the new vector into the new epoch at 09:00:13. At 09:00:40 the backfill’s encoder finishes and upserts the vector it computed from the 09:00:00 snapshot, overwriting the newer one. Nothing errors. No queue is lossy. The index now holds a stale vector for d in the new epoch and a fresh one in the old epoch, and the only symptom is that one document’s results differ between epochs for reasons unrelated to the model.
The fix is a conditional upsert guarded on the version the vector was computed from.
# LSN-guarded epoch upsert: the one invariant that makes backfill and live writes commute.
from dataclasses import dataclass
@dataclass(frozen=True)
class VectorRecord:
tenant_id: str
chunk_id: str
epoch_id: int
write_lsn: int # LSN of the source doc revision this vector was computed FROM
vector: bytes # PQ codes, length depends on the epoch's codebook
source: str # "live" or "backfill", for accounting only
class EpochWriter:
"""Upserts into one epoch's index. Never trusts arrival order."""
def __init__(self, index, epoch_id: int, expected_code_len: int):
self.index = index
self.epoch_id = epoch_id
self.expected_code_len = expected_code_len
def upsert(self, rec: VectorRecord) -> str:
if rec.epoch_id != self.epoch_id:
# A 1024-d vector in a 1536-d index is silently garbage, not an error,
# because PQ codes are just bytes. Check the epoch, not the shape.
raise ValueError(f"record for epoch {rec.epoch_id} sent to writer {self.epoch_id}")
if len(rec.vector) != self.expected_code_len:
raise ValueError(
f"code length {len(rec.vector)} != {self.expected_code_len} for epoch {self.epoch_id}"
)
key = (rec.tenant_id, rec.chunk_id)
current_lsn = self.index.get_lsn(key)
if current_lsn is not None and current_lsn >= rec.write_lsn:
# Strictly-greater wins. Equality is a retry of the same revision, which
# is a no-op rather than an error so the ingest log can be at-least-once.
return "stale" if current_lsn > rec.write_lsn else "duplicate"
self.index.upsert(key, rec.vector, lsn=rec.write_lsn)
return "applied"
Think of write_lsn as a postmark rather than a timestamp. We do not care when the envelope arrived at the index; we care which revision of the document it was franked from. Two couriers racing with the same letter is fine. A courier arriving with last week’s letter must be turned away, and it can only be turned away if the letter says when it was written.
Premium Content
Unlock the full article along with everything else in the archive — all in one place.