Course contents

16. AI System Design Lesson 2 of 10

Embedding Pipelines

Turn documents into vectors at scale: chunking, batched embedding calls, queue-based ingestion, throttling, idempotent upserts and re-embedding on model change.

16 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Ingestion is extract → chunk → embed → upsert, once per document version.
  • Chunk size is a retrieval decision; batching is the throughput lever for embedding calls.
  • A queue turns bulk imports into a backlog; workers set the drain rate, the embedding quota caps it.
  • At-least-once delivery means duplicates: upsert by deterministic chunk ids.
  • A new embedding model means a new index: backfill, compare, switch reads, delete the old one.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

An embedding pipeline keeps a vector index in sync with a body of documents. For every new or changed document it extracts the text, splits it into chunks, sends the chunks to an embedding model that returns one vector per chunk, and upserts those vectors, together with the chunk text and metadata, into a vector store. Deleted documents and permission changes flow through the same pipeline.

Why it exists

Semantic search and retrieval-augmented generation need vectors for everything they might retrieve. Producing them is slow (a network call per batch), metered (embedding APIs bill and throttle by tokens), and has to happen again whenever a document changes or the embedding model does. A pipeline makes that work reliable, repeatable and scalable instead of a script someone reruns.

How it works

Extract. Get clean text out of PDFs, Office files, HTML or wiki markup, keeping structure (headings, lists, tables) where possible. Extraction quality limits everything downstream.

Chunk. Embedding models accept a limited input, and one vector per long document blurs its topics together. Split into chunks of a few hundred tokens, often with a small overlap. Structure-aware splitting (by heading, paragraph, table row) usually retrieves better than fixed character counts. Attach metadata to each chunk: document id, chunk index, section title, source URL, tenant and access-control information, timestamps.

Embed. Send chunks in batches; most embedding APIs accept many inputs per request, which cuts per-request overhead and request-count limits. The same model (and version) must embed both documents and queries.

Upsert. Write vector + text + metadata keyed by a deterministic id such as documentId#chunkIndex. When a document shrinks, delete the chunk ids past its new last index; when it is deleted, delete all of them.

Queue and workers. Accepting a change should be fast; embedding it is not. The ingest endpoint validates and enqueues; stateless workers consume at their own pace. Bursts become backlog: backlog grows at arrivals minus processing rate, and drains at processing rate once the burst ends.

Throttling. The embedding API’s quota (tokens per minute) caps throughput no matter how many workers run. Workers should back off on 429 (respecting Retry-After), and total concurrency should be sized to the quota. Messages that keep failing go to a dead letter queue.

Change detection. Store a content hash per chunk. If a document is edited, only chunks whose hash changed need a new embedding call.

When to use it

  • Any retrieval or semantic search feature whose corpus changes over time.
  • Bulk onboarding of a large corpus (a new customer, a connected document library).
  • Model migrations and re-indexing, which are bulk imports in disguise.

When not to

  • A small, static corpus that fits in one batch job: embed it once offline and load the index.
  • Managed ingestion that already does this for you (for example, search services with built-in indexers and integrated vectorisation) when its chunking and scheduling fit your needs.
  • Data you should not copy: if documents must stay in their source system for compliance, consider querying that system’s own search instead of duplicating content into a vector store.

Trade-offs

Choice You gain You pay
Small chunks Precise matches, less noise in prompts Lost context, more vectors to store and search
Large chunks More context per hit Blurred vectors, fewer relevant passages fit in a prompt
Queue-based ingestion Fast uploads, burst absorption, retries Freshness lag, another component to operate
More workers Faster drain Hits the embedding quota or store write limit; more 429s
Content hashing Skip unchanged chunks, lower cost Extra state to store and keep correct

Alternatives

  • Synchronous inline embedding: fine for low, steady volume and when the caller needs the document searchable immediately.
  • Provider batch APIs: submit large embedding jobs asynchronously at lower cost and higher latency; good for backfills.
  • Change data capture from the source database instead of webhooks or polling, so no change is missed.
  • Hybrid without vectors: keyword search (BM25) needs no embedding pipeline at all and is a strong baseline.

Failure modes

  • Bulk import outage: inline processing rejects uploads during a burst.
  • Retry storms against the quota: many workers retrying 429s immediately keep the quota exhausted.
  • Duplicate chunks: at-least-once delivery plus random ids returns the same passage several times per query.
  • Stale or orphaned chunks: deleted documents or revoked permissions stay searchable because deletes were never propagated.
  • Mixed model versions: part of the corpus embedded with an old model, part with a new one; similarity scores become meaningless.
  • Poison documents: a file that crashes extraction is redelivered forever unless a dead letter queue catches it.

In production

Track backlog size and age (oldest message), throughput, 429 rate and cost per document. Record the embedding model name and version with every vector, or in the index name. Run re-embedding as a blue/green migration: dual-write new changes, backfill through the queue (or a batch API), compare retrieval quality on an evaluation set, switch reads with an alias, then delete the old index. In .NET, Microsoft.Extensions.AI’s IEmbeddingGenerator<string, Embedding<float>> abstracts the provider; a hosted BackgroundService or a function triggered by Azure Service Bus or a storage queue makes a straightforward worker.

Common misconceptions

  • "More workers always ingest faster." Only until the embedding quota or the store’s write capacity is reached.
  • "The queue guarantees each document is processed once." Most queues deliver at least once; the write must be idempotent.
  • "Same dimension, same space." Two models with 1,024-dimensional output still produce incomparable vectors.
  • "Chunking is a detail." Chunk size and boundaries change what retrieval can find more than most model choices do.
  • "Indexing is done once." Documents change, get deleted and change permissions; the pipeline runs forever.

Interview angle

In a RAG or search design, interviewers want the ingestion side, not only the query side. Describe extract → chunk → embed → upsert, put a queue in front of workers, estimate backfill time (corpus ÷ throughput, bounded by the embedding quota), explain idempotent upserts and delete propagation, and how you would migrate to a new embedding model without downtime. Mention storing access-control metadata with chunks so retrieval can filter by permission.

Model assumptions

The simulation is a simplified model, not a benchmark. Document changes arrive randomly (Poisson). Processing one document (extract, chunk, one batched embedding call and the upsert) takes ~600 ms (lognormal, cv 0.3); the embedding model and vector store are scenery, and their calls are part of that time and drawn as scripted packets. Inline, the Ingest API has 8 workers and room for 8 waiting requests; with a queue it only enqueues (~15 ms). Each worker node has 4 slots. Embedding-API throttling is modelled as a 25% chance that processing fails; the message is not acknowledged and comes back after the visibility timeout. Duplicate processing happens when processing outlasts the visibility timeout. Chunk sizes, corpus size and backfill duration are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. From document to vectors

    Search over meaning needs every document turned into vectors. For each new or changed document the pipeline extracts the text, splits it into chunks, sends the chunks to an embedding model (one vector per chunk, a few hundred to a few thousand numbers each) and upserts the vectors with their text and metadata into a vector store.

    The scripted packets follow one document. Here the Ingest API does all of it inline, about 600 ms per document, while the caller waits. At 2 documents per second that is fine.

    Scene: A document change reaches the Ingest API, which sends its chunks to the Embedding Model, writes the vectors to the Vector Store and then answers. About 2 documents per second, all succeed in roughly 600 ms.

    Key idea: Ingestion = extract → chunk → embed → upsert, once per document version.

  2. 2. Why and how to chunk

    Embedding models accept a limited input (often a few thousand tokens), and one vector for a whole handbook would blur every topic into one point. So documents are split into chunks of a few hundred tokens, usually with a little overlap so a sentence cut at a boundary still appears whole somewhere.

    Better splitters follow the structure (headings, paragraphs, table rows) instead of counting characters, and attach metadata: document id, section title, tenant, permissions. In the walk-through five chunks go to the model in one batched call; batching is the main throughput lever on embedding APIs.

    Scene: Scripted: the Ingest API sends five chunks of one document to the Embedding Model as a single batch and gets five vectors back in one response.

    Key idea: Chunk size is a retrieval decision: small chunks are precise, large chunks keep context. Batch the embedding calls.

  3. 3. Someone imports a whole wiki

    Half a second in, an admin connects a document library: 30 documents per second arrive. Inline processing manages about 13 per second. The Ingest API’s workers are all busy, its short waiting line fills, and it starts rejecting uploads with 503.

    The caller (a sync job, a webhook from the document system) now has to retry, or documents silently go missing from search. The fast part, accepting a document, is stuck behind the slow part, embedding it.

    Scene: Document changes jump to 30 per second. The Ingest API is saturated and rejects a large share of them with 503.

    Key idea: Inline embedding couples upload capacity to embedding capacity: a bulk import becomes an outage.

  4. 4. Accept fast, embed later

    Now the Ingest API only validates the document and puts a message on a queue: about 15 ms. Two embed workers take messages off the queue at their own pace (about 13 documents per second together).

    The same bulk import (30/s for 3 s) is accepted without a single error. Watch the queue: the backlog climbs to about 50 messages during the import and drains once it is over. Search results lag a few seconds behind; nothing is lost.

    Scene: The Ingest API puts each document on a queue and answers at once. During the 3-second import at 30 documents per second the queue grows to about 50 messages, then drains; no upload fails.

    Key idea: A queue turns a burst into a backlog: uploads stay fast, freshness lags while the workers catch up.

  5. 5. More workers drain faster

    Two more workers double the processing rate to about 27 documents per second. The same import now barely builds a backlog, and it is gone a second or two after the import ends.

    Workers are cheap to add because they are stateless. The real ceiling is usually the embedding API’s quota (tokens per minute) or the vector store’s write rate, which is where we look next.

    Scene: Four workers process about 27 documents per second. The same bulk import leaves only a short backlog that drains quickly.

    Key idea: Workers scale the drain rate; the embedding quota and the store’s write capacity cap it.

  6. 6. The embedding API says 429

    A steady 10 documents per second flows in, but the embedding API now throttles about one call in four. A worker whose call is refused does not acknowledge the message. After the 5-second visibility timeout the queue delivers it again, and usually the second try works.

    Nothing is lost, but every throttled document costs a full timeout of delay. Better: back off and retry inside the worker (honouring Retry-After), and cap total worker concurrency to what the quota allows. After a few failed deliveries a message should go to a dead letter queue, not loop forever.

    Scene: About a quarter of embedding calls are throttled. Those messages are not acknowledged and the queue redelivers them after the visibility timeout; every document is eventually processed.

    Key idea: At-least-once delivery turns throttling into delay, not loss. Match worker concurrency to the embedding quota.

  7. 7. Same chunk, twice: make upserts idempotent

    The throttling is fixed, but someone shortened the visibility timeout to 0.7 s, while a large document can take longer than that. The queue assumes the worker died and hands the message to another worker: the same document is processed twice (the duplicates counter climbs).

    That is normal for at-least-once queues, so the write must be safe to repeat. Give every chunk a deterministic id, such as docId#chunkIndex, and upsert by that id: the second write overwrites the first (scripted packets show both upserts). Random ids would leave duplicate chunks in every search result. Store a content hash too, so unchanged chunks can skip the embedding call entirely.

    Scene: With a 0.7-second visibility timeout, slow documents are delivered to a second worker while the first is still working, so some documents are processed twice. Scripted packets show both workers upserting the same chunk id; the second write overwrites the first.

    Key idea: Upsert by a deterministic chunk id so reprocessing a document is harmless.

  8. 8. Changing the embedding model

    A better embedding model comes out. Vectors from different models live in different spaces: you cannot compare a v2 query vector with v1 document vectors, and dimensions often differ. Changing the model means re-embedding the whole corpus into a new index.

    Run it like a migration: write new documents to both indexes, backfill old ones through the same queue (here at 20 documents per second, which four workers handle), compare retrieval quality, then switch reads to v2 and delete v1. The backfill takes corpus size ÷ rate: 400,000 documents at 20/s is about 5.5 hours, plus the embedding bill.

    Scene: A second embedding model and vector store are added. Scripted packets show a worker embedding a chunk with both models and writing to both stores. The queue carries a 20-documents-per-second backfill that four workers keep up with.

    Key idea: An embedding model change is a full re-index: backfill a new index, then switch reads.

  9. 9. An ingestion pipeline, not a script

    Treat ingestion like any data pipeline: accept fast, queue, process with stateless workers, make writes idempotent, back off on throttling, dead-letter what keeps failing, and version the embedding model with the index.

    Also plan for deletes: when a document is removed or its permissions change, its chunks must leave the index too, or search will keep returning them. In .NET, Microsoft.Extensions.AI’s IEmbeddingGenerator gives workers one abstraction over embedding providers; the queue can be anything from Azure Service Bus to a database table.

    Scene: The final pipeline: Ingest API, queue, four embed workers, two embedding models and two vector stores during the migration.

    Key idea: Queue, idempotent upserts, throttling-aware workers and a versioned index: the four pillars of an embedding pipeline.