Re-embedding 10 million documents without taking search offline

Re-embedding 10 million documents without taking search offline

Part 3 of 7 in the Embedding Migration in Production series (change the model, not the reliability): engineer-level, on Azure AI Search and Microsoft Foundry, mapped to Microsoft exam AI-103.

TL;DR for managers. Re-embedding a large knowledge base is a batch job measured in weeks, limited by the embedding model's quota rather than by Azure AI Search. It has to survive throttling, crashes and restarts without re-paying for work already done, and it has to keep up with documents that are edited, deleted or re-permissioned while it runs. A 1% pilot gives you the real numbers before you commit.

Parts 1 and 2 established that every document vector must be regenerated, into a new index that production doesn't use yet. This part is about doing that at scale: the arithmetic, the shape of a pipeline that can be stopped and restarted, and the part teams forget, which is everything that changes while the backfill is running.

The arithmetic first

Using the series scenario (illustrative): 10 million documents, 10 chunks each, about 500 tokens per chunk.

documents        = 10_000_000
chunks_per_doc   = 10            # measure this in the pilot; it is rarely a round number
tokens_per_chunk = 500
chunks = documents * chunks_per_doc                  # 100,000,000
tokens = chunks * tokens_per_chunk                   # 50,000,000,000

# Request shape: at most 2,048 inputs AND 300,000 tokens per embeddings request
per_request = min(2048, 300_000 // tokens_per_chunk)  # 600 chunks, so use e.g. 256 to leave headroom
requests = chunks / 256                               # ~390,625 requests

tpm = 1_000_000                                       # EXAMPLE quota per deployment, check yours
minutes = tokens / tpm                                # 50,000 minutes
print(f"{minutes / 60 / 24:.1f} days at 100% utilisation")   # ~34.7 days

price_per_million = PRICE_FROM_YOUR_DEPLOYMENT        # don't hard-code; read your pricing page
retry_overhead = 1.05                                 # measured in the pilot
print(f"embedding cost ~ {tokens / 1e6 * price_per_million * retry_overhead:,.0f}")

Three things fall out of this:

  • 50 billion tokens is the number to price. Multiply by your deployment's price per million tokens, then add the retry overhead you measure in the pilot. Microsoft's guide adds the less obvious items: source reads, paid enrichment if your pipeline uses it, export storage, duplicate index capacity, and the overlap period when both old and new pipelines process changes.
  • Time is set by quota. At an example 1 million tokens per minute, the job takes about five weeks of continuous running. More quota, or several deployments, shortens it. If you add deployments in other regions, check your data residency requirements first.
  • Request shape matters. The embeddings API accepts at most 2,048 inputs and 300,000 tokens per request, and 8,192 tokens per input. With 500-token chunks the token cap bites first, at 600 chunks.

Run the 1% pilot. Embed 100,000 documents into a test index with the settings you intend to use. Record actual chunks, billed tokens, retries, sustained throughput, elapsed time and index size, then multiply. Microsoft recommends measuring a representative pilot before estimating the full corpus, and says to use the provider's actual billing units, because not every model bills by tokens.

Run the baseline golden set from part 5 against the pilot index too. If the new model is no better on 1% of the corpus, find out why before paying for the other 99%. For a forced retirement you still migrate, but you go in knowing what to expect.

Reuse the chunks (Approach A)

The cheapest and cleanest migration keeps everything except the vectors: same chunk boundaries, same chunk IDs, same text, same metadata, same permissions. Only the embedding is regenerated. That makes the comparison in part 5 a controlled experiment, because the model is the only variable.

If you also want to improve parsing, OCR or chunk sizes (Approach B), run that as a separate, versioned experiment. Microsoft advises comparing chunking changes separately where practical "so you can distinguish its effects from the model change". Re-chunking also changes chunk counts and keys, which means reconciling obsolete child records later.

A manifest, not a progress bar

The single most useful object in a long migration is a durable record per chunk. It answers "what's done?", "what failed and why?" and "is this vector still current?" after any crash. Microsoft's guide warns that a simple Boolean such as vectorV2Ready "doesn't prove freshness after a source change", so record the versions that produced each vector:

CREATE TABLE chunk_manifest (
  chunk_id          TEXT PRIMARY KEY,     -- deterministic: f"{doc_id}:{chunk_no}", same in old and new index
  doc_id            TEXT NOT NULL,
  source_version    TEXT NOT NULL,        -- etag / last-modified / revision from the source system
  content_hash      TEXT NOT NULL,        -- sha256 of the exact text that was embedded
  acl_version       TEXT NOT NULL,        -- version of the permission data written with the chunk
  contract_version  TEXT,                 -- EmbeddingContract.version used for the stored vector (part 2)
  status            TEXT NOT NULL,        -- pending | embedded | written | failed | dead_letter | deleted
  attempts          INTEGER DEFAULT 0,
  error_class       TEXT,                 -- throttled | bad_input | auth | server | write_conflict
  target_index      TEXT,
  updated_at        TEXT NOT NULL
);
-- Work to do = anything not written with the current contract and current source version
-- SELECT chunk_id FROM chunk_manifest
--  WHERE status != 'deleted' AND (status != 'written' OR contract_version != :new_contract);

Store it outside the search index (a database table or Azure Table Storage), and never store document text, tokens or credentials in it. A chunk is marked written only after Azure AI Search confirms that document. Indexing returns a result per document, and a batch can partly succeed.

A pipeline that can stop and restart

A sketch of the worker, using the async OpenAI client against an Azure deployment. It is illustrative: adapt names to your SDK versions and test it on the pilot.

import asyncio, random
from openai import AsyncAzureOpenAI, RateLimitError, APIConnectionError, APITimeoutError, APIStatusError

class DeadLetter(Exception):
    """Input the model will never accept (too long, empty): record it and move on."""

async def embed_batch(client: AsyncAzureOpenAI, texts: list[str], contract, attempts: int = 8):
    for attempt in range(attempts):
        try:
            resp = await client.embeddings.create(
                model=contract.deployment, input=texts, dimensions=contract.dimensions)
            vectors = [d.embedding for d in resp.data]
            if any(len(v) != contract.dimensions for v in vectors):
                raise DeadLetter("dimension mismatch")            # never write a wrong-sized vector
            return vectors
        except (RateLimitError, APIConnectionError, APITimeoutError) as e:
            wait = _retry_after(e) or min(60, 2 ** attempt)
        except APIStatusError as e:
            if e.status_code < 500:
                raise DeadLetter(f"HTTP {e.status_code}") from e   # 400: bad input, retrying won't help
            wait = min(60, 2 ** attempt)
        await asyncio.sleep(wait + random.uniform(0, wait / 2))    # jitter stops workers retrying in lockstep
    raise RuntimeError("retry budget exhausted")                    # leave it 'failed' for the next pass

def _retry_after(e):
    resp = getattr(e, "response", None)
    value = resp.headers.get("retry-after") if resp is not None else None
    return float(value) if value else None

async def run(batches, client, search_client, ledger, contract, concurrency=8):
    gate = asyncio.Semaphore(concurrency)                           # bounded concurrency = predictable TPM
    async def one(batch):
        async with gate:
            try:
                vectors = await embed_batch(client, [c.text for c in batch], contract)
            except DeadLetter as e:
                ledger.mark(batch, "dead_letter", str(e)); return
            except RuntimeError as e:
                ledger.mark(batch, "failed", str(e)); return
            docs = [c.to_search_doc(vector=v) for c, v in zip(batch, vectors)]   # text, metadata, ACLs, vector
            results = await search_client.upload_documents(docs)
            ledger.mark_results(batch, results, contract.version)    # per-document: only succeeded -> 'written'
    await asyncio.gather(*(one(b) for b in batches))

The design choices behind it:

  • Bounded concurrency. A semaphore caps requests in flight, so throughput stays near your quota instead of producing a wall of 429s.
  • Retry classification. Throttling, timeouts and 5xx errors are retried with exponential backoff and jitter, honouring the retry-after header when the service sends one. A 400 means bad input and goes to a dead-letter list for a human, because retrying it only spends quota.
  • A retry budget. After a fixed number of attempts the batch is marked failed and the run moves on. The next pass picks it up. Microsoft notes that interruptions and retries "can repeat work and consume model quota and budget": there is no exactly-once processing, so the manifest is what stops you paying twice.
  • Idempotent writes. Chunk IDs are deterministic, so re-uploading a chunk replaces it rather than creating a duplicate.
  • Validate before writing. Every vector is checked for the expected dimensions. Never write a vector you haven't checked.

The hard part: changes during the backfill

Five weeks is a long time in a live knowledge base. Documents are edited, deleted and re-permissioned while the job runs, and "queries stay online against the old index" doesn't mean the new index is current. Microsoft describes three strategies:

Strategy How it works Trade-off
Pause writes Freeze ingestion during the backfill, catch up afterwards Simple, but five weeks of stale content is rarely acceptable at this scale
Snapshot and replay Backfill from a consistent snapshot; record a watermark; replay creates, updates, deletes and permission changes after it Needs a durable change stream; usually the best fit
Dual ingestion New and changed documents are embedded with both models and written to both indexes Always current; costs double embedding for changes and careful coordination

Whichever you choose, three traps need explicit handling:

  • Deleted documents coming back. If the backfill read a chunk before the document was deleted, a late upload or mergeOrUpload recreates it in the new index. Route deletes and backfill writes for the same document through one owner that rejects stale source versions, and reconcile deletions before cutover.
  • Stale overwrites. A slow embedding request for version 3 of a document can finish after version 4 was written. Compare the source version before writing and keep the newer one. A "ready" flag is not a lock.
  • Permission changes. A permission change with no text change still has to reach the new index. Track acl_version separately from content_hash, and re-write chunks whose permissions changed even when the vector doesn't need regenerating.

If you use integrated vectorisation

With built-in indexers, the pipeline above is Azure's job, but the same rules apply. Create a new index, a new skillset pointing at the new deployment and a new indexer, created disabled. Test it on a limited source scope, then run the full load and monitor execution history, errors and warnings. Don't change the shared production skillset, and don't routinely reset the indexer to retry failures: Microsoft notes that a reset followed by a run requests full reprocessing. The enrichment cache is a preview feature that belongs to one indexer, so don't count on it to make the rebuild cheaper.

Security during the backfill

  • Permissions on each chunk must come from the trusted source or connector, not be inferred from document content or copied from a field because it has a permission-like name.
  • The new index holds the same sensitive content as production. Apply the same network rules, encryption and access roles from the first write, not at cutover.
  • Logs and the manifest hold IDs, hashes and error classes, never text or access tokens.

Common mistakes

  • Estimating from document count instead of measured chunk count.
  • Treating "indexer finished" or "row count matches" as done. Matching counts don't prove the right documents, versions and permissions are there.
  • Retrying 400 errors until the quota runs out.
  • Forgetting deletes, so the new index ends up with documents that no longer exist.

Key takeaways

  • Price the tokens, then plan the time: quota, not search capacity, usually sets the schedule.
  • Keep chunks and permissions identical and change only the vectors.
  • A per-chunk manifest with source, content, ACL and contract versions makes the job restartable and auditable.
  • Decide how changes, deletes and permission updates reach the new index before you start, not after.

Next, part 4: blue-green migration for Azure AI Search, with aliases, application routing, shadow queries, canary traffic and a rollback you've actually tested.

References

Learning this for AI-103? Microsoft's AI-103 exam (Azure AI Apps and Agents Developer Associate) covers implementing RAG with Azure AI Search, vector and hybrid search, and monitoring retrieval quality. Our live online AI-103 course builds these pipelines hands-on in Microsoft Foundry and Azure AI Search, on UK time, with mock assessments before you book the exam.

The Embedding Migration in Production series

Change the model, not the reliability.

  1. Part 1: Your embedding model is being retired
  2. Part 2: Why you can't simply swap embedding models
  3. Part 3: Re-embedding 10 million documents (you are here)
  4. Part 4: Blue-green migration for Azure AI Search
  5. Part 5: Did the new model improve retrieval?
  6. Part 6: BM25, hybrid and semantic ranking
  7. Part 7: The enterprise migration playbook
  8. Bonus: Document permissions in a migration
Back to blog

Ready to take the first step?

Live online courses on UK time, mapped to the current Microsoft AI exams. No coding needed for AI at work.

Explore AI coursesAsk us a question