Your RAG Is Only as Good as Its Ingestion Pipeline
· Bilal Tahseen

When a RAG system gives a wrong answer, the team usually goes after the parts that are easy to see. They swap the reranker, tune top-k, rewrite the system prompt, try a bigger model. Often the real problem is in a part nobody looks at: the document that was fixed in the source system last Tuesday is still in the index in its old form. Or the policy that was deleted is still showing up in citations. Or half a PDF failed to parse and nobody found out.
Retrieval can only return what ingestion put in the index. If ingestion is a script someone runs when the docs "feel stale," then every quality problem you have downstream is really an ingestion problem.
My rule for every RAG build: the index is a replica of the source systems, and it gets the same discipline you'd give any other replica. That means it knows what changed, writes idempotently, deletes for real, tells you when it falls behind, and can move to a new embedding model without downtime.
This isn't a drop-in package. The sketches below show the shape of what I build on Postgres with pgvector. Your connectors, document formats, and embedding provider will be different, and the connectors are usually where most of the effort goes.
Why "just re-index everything" stops working
The first version of most pipelines is a full rebuild: crawl everything, chunk it, embed it, swap the index. It's simple, and for a small corpus that changes rarely, it's fine. I'll say so on a call if it's true.
It breaks down in four ways:
- Cost and time grow with the corpus, not with how much changed. You re-embed every unchanged paragraph on every run, so you run it less often, so the index gets staler.
- Deletes are implicit. If the crawler misses a folder because of an API error, that whole folder disappears from the rebuilt index. If deletes aren't modeled at all, removed content sticks around forever.
- No failure visibility. A document that fails to parse just isn't there. Nobody gets alerted. Users get worse answers, and they don't know why.
- Model changes are scary. Changing the embedding model means rebuilding everything while hoping retrieval quality doesn't drop. There's no comparison and no rollback.
The fix isn't a smarter rebuild. It's an incremental pipeline with explicit state.
The architecture

Seven pieces, each with one job:
- Source connectors list and fetch documents from each system (Drive, Confluence, a CMS, a database) and give every document a stable
doc_idfrom the source system. Never a file path or a title, because both change on rename. - Change detection hashes the fetched bytes. If the hash matches what's stored, we stop. No parse, no chunk, no embedding call. Deletes come through as tombstones, not as "missing from this crawl."
- Structure-aware parsing and chunking turns each format into sections that keep their heading path. Each chunk gets an ID derived from its content and position in the document tree, so the same paragraph gets the same ID on every run.
- Idempotent upsert writes chunks keyed by
(doc_id, chunk_hash). Running the same document twice is a no-op. Chunks that disappeared from the document are deleted in the same transaction. - The embedding worker fills one table per embedding index version, embedding only the chunks that index doesn't have yet. Unchanged chunks never get re-embedded.
- A dead-letter queue captures any document that fails to fetch, parse, or embed, with the stage and the error. The last good version stays live.
- Freshness metrics measure lag from source change to retrievable chunk, per source, against an SLO you actually alert on.
The schema
The tables carry the design. Chunks are the source of truth. Embeddings are derived data, one table per index version, and they cascade when a chunk goes away.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (
doc_id text PRIMARY KEY, -- stable id from the source, e.g. 'confluence:123456'
source text NOT NULL,
source_uri text NOT NULL,
content_hash text NOT NULL, -- sha256 of the fetched bytes
source_updated_at timestamptz NOT NULL,
ingested_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE chunks (
doc_id text NOT NULL REFERENCES documents (doc_id) ON DELETE CASCADE,
chunk_hash text NOT NULL,
heading_path text NOT NULL,
ordinal int NOT NULL,
content text NOT NULL,
PRIMARY KEY (doc_id, chunk_hash)
);
-- Deleted documents leave only an id and a timestamp behind, no content.
CREATE TABLE doc_tombstones (
doc_id text PRIMARY KEY,
source_deleted_at timestamptz NOT NULL
);
-- Registry of embedding index versions. Exactly one is 'active'.
CREATE TABLE embedding_indexes (
index_name text PRIMARY KEY CHECK (index_name ~ '^v[0-9]+$'),
model text NOT NULL,
model_version text NOT NULL,
dims int NOT NULL,
status text NOT NULL
CHECK (status IN ('building', 'shadow', 'active', 'standby', 'retired')),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX embedding_indexes_one_active
ON embedding_indexes ((true)) WHERE status = 'active';
-- One table per index version, so each has a fixed vector dimension.
CREATE TABLE chunk_embeddings_v1 (
doc_id text NOT NULL,
chunk_hash text NOT NULL,
embedding vector(1536) NOT NULL,
embedding_model text NOT NULL,
embedding_version text NOT NULL,
embedded_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (doc_id, chunk_hash),
FOREIGN KEY (doc_id, chunk_hash)
REFERENCES chunks (doc_id, chunk_hash) ON DELETE CASCADE
);
CREATE INDEX chunk_embeddings_v1_hnsw
ON chunk_embeddings_v1 USING hnsw (embedding vector_cosine_ops);
A few decisions in there are deliberate:
- One table per index version instead of one big table with a
modelcolumn. pgvector indexes need a fixed dimension, and two models usually have different dimensions. Even when the dimensions match, vectors from two different models aren't comparable, so they should never share an index. embedding_modelandembedding_versionon every row, even though the table name implies them. When something looks wrong six months from now, the row tells you what produced it.ON DELETE CASCADEall the way down. Delete a document and its chunks and every version of its embeddings go with it in the same transaction. No orphaned vectors that still show up in search.- The partial unique index makes "two active indexes" impossible at the database level, not just in application code.
Stable chunk IDs
If a chunk's ID changes every time someone fixes a typo three sections away, you re-embed the whole document on every edit and your upserts turn into delete-everything-insert-everything. The chunk ID has to come from the chunk itself.
I hash the document ID, the heading path, and the normalized text. Heading path is in the hash on purpose: if a paragraph moves under a different heading, its meaning in context changed, and I want it re-embedded. Ordinal is not in the hash, because inserting one paragraph near the top would otherwise change every ID below it. Identical text that repeats in the same section (boilerplate, a repeated table row) gets an occurrence counter so it doesn't collide.
import hashlib
from dataclasses import dataclass
from datetime import datetime
@dataclass(frozen=True)
class SourceDoc:
doc_id: str # stable id from the source system, never a path
source: str
source_uri: str
raw_hash: str # sha256 of the fetched bytes
source_updated_at: datetime
@dataclass(frozen=True)
class Chunk:
chunk_hash: str
heading_path: str
ordinal: int
content: str
def normalize(text: str) -> str:
# Reflowed whitespace is not a content change.
return " ".join(text.split())
def sha256(*parts: str) -> str:
h = hashlib.sha256()
for part in parts:
h.update(part.encode("utf-8"))
h.update(b"\x00") # separator so ("ab", "c") != ("a", "bc")
return h.hexdigest()
def make_chunks(doc_id: str, sections: list[tuple[str, str]]) -> list[Chunk]:
"""sections: (heading_path, text) pairs from a structure-aware parser."""
seen: dict[str, int] = {}
chunks: list[Chunk] = []
for ordinal, (heading_path, text) in enumerate(sections):
content = normalize(text)
base = sha256(doc_id, heading_path, content)
occurrence = seen.get(base, 0)
seen[base] = occurrence + 1
chunk_hash = base if occurrence == 0 else sha256(base, str(occurrence))
chunks.append(Chunk(chunk_hash, heading_path, ordinal, content))
return chunks
The parser is where the format-specific work lives, and it's usually the biggest piece of work in a build. The contract is simple: return (heading_path, text) pairs where a heading path looks like Refund Policy > EU Customers > Exceptions. Getting there is not simple. Tables stay whole or get split by row with the header repeated. Code blocks never get split in the middle. Headers and footers that repeat on every PDF page get removed before chunking. Long sections get split on paragraph boundaries under a size limit. A fixed 500-token window that cuts a table in half is how you end up with a chunk that has prices and no product names.
Change detection and the idempotent upsert
There are two levels of hashing, and each saves a different cost. The document hash on the raw bytes lets you skip parsing entirely. The chunk hash lets you skip embedding for every paragraph that didn't change, even when the document did.
The Python sketches use psycopg 3 and assume connections opened with autocommit=True, so each conn.transaction() block is its own real transaction and the advisory lock is released when it commits.
import psycopg
def needs_parse(conn: psycopg.Connection, doc: SourceDoc) -> bool:
row = conn.execute(
"SELECT content_hash FROM documents WHERE doc_id = %s", (doc.doc_id,)
).fetchone()
return row is None or row[0] != doc.raw_hash
def sync_document(
conn: psycopg.Connection, doc: SourceDoc, sections: list[tuple[str, str]]
) -> str:
"""Apply one parsed document. Returns 'stale', 'unchanged', or 'updated'."""
chunks = make_chunks(doc.doc_id, sections)
with conn.transaction():
# Serialize work per document across workers. hashtextextended is
# computed by Postgres, so every process gets the same lock key.
conn.execute(
"SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (doc.doc_id,)
)
tomb = conn.execute(
"SELECT source_deleted_at FROM doc_tombstones WHERE doc_id = %s",
(doc.doc_id,),
).fetchone()
if tomb and doc.source_updated_at <= tomb[0]:
return "stale" # an old update event arriving after the delete
current = conn.execute(
"SELECT content_hash, source_updated_at FROM documents WHERE doc_id = %s",
(doc.doc_id,),
).fetchone()
if current and current[1] > doc.source_updated_at:
return "stale" # out-of-order event; we already have something newer
if current and current[0] == doc.raw_hash:
conn.execute(
"UPDATE documents SET source_updated_at = %s WHERE doc_id = %s",
(doc.source_updated_at, doc.doc_id),
)
return "unchanged"
conn.execute("DELETE FROM doc_tombstones WHERE doc_id = %s", (doc.doc_id,))
conn.execute(
"""
INSERT INTO documents (doc_id, source, source_uri, content_hash, source_updated_at)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (doc_id) DO UPDATE SET
source_uri = EXCLUDED.source_uri,
content_hash = EXCLUDED.content_hash,
source_updated_at = EXCLUDED.source_updated_at,
ingested_at = now()
""",
(doc.doc_id, doc.source, doc.source_uri, doc.raw_hash, doc.source_updated_at),
)
# Chunks that no longer exist in the document are removed; their
# embeddings in every index version go with them via ON DELETE CASCADE.
conn.execute(
"DELETE FROM chunks WHERE doc_id = %s AND NOT (chunk_hash = ANY(%s))",
(doc.doc_id, [c.chunk_hash for c in chunks]),
)
# Unchanged chunks only get their position updated; new chunks are inserted.
with conn.cursor() as cur:
cur.executemany(
"""
INSERT INTO chunks (doc_id, chunk_hash, heading_path, ordinal, content)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (doc_id, chunk_hash) DO UPDATE SET ordinal = EXCLUDED.ordinal
""",
[(doc.doc_id, c.chunk_hash, c.heading_path, c.ordinal, c.content)
for c in chunks],
)
return "updated"
Run it twice with the same input and the second run returns "unchanged" without touching a chunk. Run two workers on the same document at once and the advisory lock serializes them. Replay last week's event stream after a bug fix and the timestamp checks stop old versions from overwriting new ones. If you change the parser or chunker, store a pipeline_version next to content_hash and treat a mismatch as a change, or unchanged documents keep their old chunks forever.
One tradeoff to know about: between this transaction committing and the embedding worker catching up, new chunks exist but aren't embedded yet, so they can't be retrieved. For a document that changed, removed chunks disappear immediately and new ones show up a moment later. That's the lag the freshness metric measures. If your use case can't tolerate that gap, embed before the transaction and write the vectors in it. That's more complex, and I only do it when it's needed.
Deletes are real deletes
Tombstones exist so a stale event can't bring a document back. They don't keep content around. When the source says a document is gone, the document, its chunks, and every embedding of it are deleted in one transaction, and only the ID and the delete timestamp stay behind.
def delete_document(
conn: psycopg.Connection, doc_id: str, source_deleted_at: datetime
) -> None:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (doc_id,))
newer = conn.execute(
"SELECT 1 FROM documents WHERE doc_id = %s AND source_updated_at > %s",
(doc_id, source_deleted_at),
).fetchone()
if newer:
return # stale delete: the document was updated after it
# Cascades to chunks and to every chunk_embeddings_* table.
conn.execute(
"DELETE FROM documents WHERE doc_id = %s",
(doc_id,),
)
conn.execute(
"""
INSERT INTO doc_tombstones (doc_id, source_deleted_at)
VALUES (%s, %s)
ON CONFLICT (doc_id) DO UPDATE SET source_deleted_at =
GREATEST(doc_tombstones.source_deleted_at, EXCLUDED.source_deleted_at)
""",
(doc_id, source_deleted_at),
)
Tombstones themselves get purged once they're older than the longest window in which a connector could replay old events. After that, there's nothing left to protect against.
Where deletes come from matters. Event-based connectors (webhooks, change feeds) send them directly. For sources that only support listing, the connector compares the full listing against what's stored and emits deletes for whatever is missing. That's where pipelines wipe out their own data. A listing call that fails halfway or gets rate-limited looks exactly like "everything after page three was deleted." My connectors refuse to emit listing-based deletes unless the listing finished cleanly, and if a single run would delete more than a set fraction of a source, it stops and asks a human.
Losing access counts as a delete too. If a user loses access to a document in the source system, the ACL sync has to catch that as fast as content changes. I covered that side in permission-aware RAG.
The embedding worker and versioned indexes
The embedding worker doesn't know about documents or connectors. It looks for chunks that a given index version doesn't have yet, embeds them in batches, and writes them. The same worker keeps the active index current and backfills a new one.
import time
import numpy as np
import psycopg
from psycopg import errors, sql
from pgvector.psycopg import register_vector
LIVE_STATUSES = ("building", "shadow", "active", "standby")
def embed_missing(
conn: psycopg.Connection, index_name: str, models: dict, batch_size: int = 64
) -> int:
"""Embed up to batch_size chunks missing from one index version.
Returns rows written, 0 when nothing is missing, or -1 when the batch was
rolled back and should simply be retried.
"""
idx = conn.execute(
"SELECT model, model_version, dims FROM embedding_indexes "
"WHERE index_name = %s AND status = ANY(%s)",
(index_name, list(LIVE_STATUSES)),
).fetchone()
if idx is None:
raise ValueError(f"index {index_name} is not live")
model_name, model_version, dims = idx
# Same registry lookup retrieve() uses, so the rows are always labeled
# with the model that actually produced them.
model = models[(model_name, model_version)]
table = sql.Identifier(f"chunk_embeddings_{index_name}")
rows = conn.execute(
sql.SQL("""
SELECT c.doc_id, c.chunk_hash, c.heading_path, c.content
FROM chunks c
LEFT JOIN {t} e
ON e.doc_id = c.doc_id AND e.chunk_hash = c.chunk_hash
WHERE e.doc_id IS NULL
ORDER BY c.doc_id, c.ordinal
LIMIT %s
""").format(t=table),
(batch_size,),
).fetchall()
if not rows:
return 0
# Embed the heading path with the text so the chunk carries its context.
vectors = [
np.asarray(v, dtype=np.float32)
for v in model.embed([f"{r[2]}\n\n{r[3]}" for r in rows])
]
if len(vectors) != len(rows) or any(v.shape != (dims,) for v in vectors):
raise ValueError(f"{model_name} returned vectors that don't match {index_name}")
try:
with conn.transaction():
with conn.cursor() as cur:
cur.executemany(
sql.SQL("""
INSERT INTO {t}
(doc_id, chunk_hash, embedding, embedding_model, embedding_version)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (doc_id, chunk_hash) DO NOTHING
""").format(t=table),
[(r[0], r[1], v, model_name, model_version)
for r, v in zip(rows, vectors)],
)
except errors.ForeignKeyViolation:
# A chunk was deleted while we were embedding, so the whole batch rolled
# back. Report "retry", not "done"; the next pass re-selects without it.
return -1
return len(rows)
def run_worker(dsn: str, index_name: str, models: dict, idle_seconds: float = 5.0) -> None:
"""Keep one index version current. Stops when the version is retired."""
with psycopg.connect(dsn, autocommit=True) as conn:
register_vector(conn)
while True:
if embed_missing(conn, index_name, models) == 0:
time.sleep(idle_seconds)
models maps each (model, model_version) in the registry to your provider client: a list of strings in, a list of vectors out. The worker looks its model up in the registry, the same way retrieval does, so it can't write vectors from one model under another model's name. Put rate limiting and retries in the client, and route anything that keeps failing to the dead-letter queue. Run one worker per live index version. It sleeps when it's caught up and stops with an error once its version is retired.
Retrieval reads the registry to find the active index, then embeds the query with that index's model. That second part sounds obvious, but it's an easy one to get wrong: if the query embedder is hardcoded in one service and the index model is a config value in another, the two can drift apart, and retrieval quietly turns into noise.
def retrieve(conn: psycopg.Connection, query: str, models: dict, k: int = 20):
row = conn.execute(
"SELECT index_name, model, model_version FROM embedding_indexes "
"WHERE status = 'active'"
).fetchone()
if row is None:
raise RuntimeError("no active embedding index")
index_name, model_name, model_version = row
model = models[(model_name, model_version)]
qv = np.asarray(model.embed([query])[0], dtype=np.float32)
table = sql.Identifier(f"chunk_embeddings_{index_name}")
return conn.execute(
sql.SQL("""
SELECT c.doc_id, c.heading_path, c.content,
e.embedding <=> %(q)s AS distance
FROM {t} e
JOIN chunks c
ON c.doc_id = e.doc_id AND c.chunk_hash = e.chunk_hash
ORDER BY e.embedding <=> %(q)s
LIMIT %(k)s
""").format(t=table),
{"q": qv, "k": k},
).fetchall()
In a real deployment, that query also gets the ACL pre-filter from the permission-aware post, and usually a hybrid keyword leg. I left both out here so the versioning stays readable.
Changing the embedding model: blue/green, not in place
Embedding models get replaced. A better one comes out, your provider deprecates the one you're on, or you move to a self-hosted model for cost or data residency. The tempting way is to re-embed in place, overwriting vectors row by row. While that runs, your index is a mix of vectors from two models that aren't comparable, so nearest-neighbor results are meaningless. And if the new model turns out worse on your data, there's no way back.

The blue/green sequence:
- Register the new version as
buildingand create its table with the new dimension. Chunks don't change. Only a new derived table is added. Give it the sameFOREIGN KEY (doc_id, chunk_hash) REFERENCES chunks ... ON DELETE CASCADE, or deletes leave orphaned vectors in it. - Backfill by running an embedding worker against the new version until
embed_missingreturns zero. The active version keeps serving and keeps getting new chunks, because a worker runs for every live version. - Build the HNSW index after the backfill. Building it once on a full table is faster than updating it on every insert during the backfill.
- Shadow by moving the version to
shadowand running retrieval against both versions: the golden set, plus a sample of real logged queries. Users only see results from the active version. - Cut over in one transaction once the shadow numbers clear the bar you agreed on before the run.
- Keep the old version on standby, still updated by the worker, until you're confident. Then retire it and drop its table.
The shadow eval reuses the golden set I described in the eval gate post. For retrieval, a hit-rate check over the top k chunks is a reasonable first gate:
def hit_rate_at_k(conn: psycopg.Connection, index_name: str, model, golden: list[dict], k: int = 10) -> float:
"""golden: [{"query": str, "relevant_doc_ids": set[str]}, ...]"""
if not golden:
raise ValueError("empty golden set")
table = sql.Identifier(f"chunk_embeddings_{index_name}")
stmt = sql.SQL(
"SELECT doc_id FROM {t} ORDER BY embedding <=> %s LIMIT %s"
).format(t=table)
hits = 0
for item in golden:
qv = np.asarray(model.embed([item["query"]])[0], dtype=np.float32)
retrieved = {row[0] for row in conn.execute(stmt, (qv, k))}
hits += bool(retrieved & item["relevant_doc_ids"])
return hits / len(golden)
Compare the two versions overall and per query category, because a new model that's better on average can still be worse on your product names or on non-English content. For the sampled live queries there's no ground truth, so I look at top-k overlap between the two versions and read through the queries where they disagree most. If you don't have a golden set yet, start with stop evaluating RAG with vibes.
The cutover itself is small, and the database enforces it:
def cutover(conn: psycopg.Connection, new_index: str) -> None:
with conn.transaction():
conn.execute("LOCK TABLE embedding_indexes IN EXCLUSIVE MODE")
conn.execute(
"UPDATE embedding_indexes SET status = 'standby' WHERE status = 'active'"
)
cur = conn.execute(
"UPDATE embedding_indexes SET status = 'active' "
"WHERE index_name = %s AND status = 'shadow'",
(new_index,),
)
if cur.rowcount != 1:
# Raising inside the transaction rolls back the demotion above.
raise RuntimeError(f"{new_index} is not in shadow; refusing cutover")
Rollback is the same function in reverse, after moving the standby version back to shadow. Because the standby kept getting new chunks, rolling back doesn't bring back a stale index.
The dead-letter queue
A document that fails to parse should never just vanish quietly, and it should never take its previous version down with it. Failures go to a table with enough context to fix them, and the last good chunks stay live.
CREATE TABLE ingest_dead_letters (
id bigserial PRIMARY KEY,
doc_id text NOT NULL,
source text NOT NULL,
stage text NOT NULL CHECK (stage IN ('fetch', 'parse', 'chunk', 'embed')),
error_class text NOT NULL,
error_message text NOT NULL,
source_updated_at timestamptz,
attempts int NOT NULL DEFAULT 1,
first_failed_at timestamptz NOT NULL DEFAULT now(),
last_failed_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (doc_id, stage)
);
-- Record a failure, or bump the attempt count on a repeat (run from the worker with bound parameters).
INSERT INTO ingest_dead_letters
(doc_id, source, stage, error_class, error_message, source_updated_at)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (doc_id, stage) DO UPDATE SET
attempts = ingest_dead_letters.attempts + 1,
error_class = EXCLUDED.error_class,
error_message = EXCLUDED.error_message,
source_updated_at = EXCLUDED.source_updated_at,
last_failed_at = now();
-- Clear a document's ingest failures once it's fetched and synced again, including
-- when needs_parse() says the bytes are unchanged.
DELETE FROM ingest_dead_letters
WHERE doc_id = %s AND stage IN ('fetch', 'parse', 'chunk');
When a document is fetched and synced again, including the case where its hash hasn't changed, the worker runs that DELETE. The queue is a work list, not an archive. Grouped by error_class, it tells you which parser to fix next. A spike in one class usually means a source changed its export format, and you want to hear about that from a dashboard, not from a user.
Freshness: an SLO, not a feeling
"The index is pretty up to date" isn't a number. I track three things per source:
- Connector lag: time since the last successful listing or change-feed poll. If this grows, nothing after it matters.
- Pipeline lag: for each document, the time from
source_updated_atuntil every one of its chunks exists in the active index. - Backlog: documents with at least one chunk the active index doesn't have yet, plus open dead letters.
-- Documents not yet fully retrievable in the active index (v1 here), per source.
SELECT d.source,
count(*) AS docs_behind,
max(now() - d.source_updated_at) AS worst_lag
FROM documents d
WHERE EXISTS (
SELECT 1
FROM chunks c
LEFT JOIN chunk_embeddings_v1 e
ON e.doc_id = c.doc_id AND e.chunk_hash = c.chunk_hash
WHERE c.doc_id = d.doc_id
AND e.doc_id IS NULL
)
GROUP BY d.source;
The SLO itself is a business decision. "A policy change is answerable within an hour" and "within a day" lead to very different connector designs and costs, so I make the team pick a number per source before I build. Then alert on it like you would on any replication lag.
Common failure modes
- Doc IDs from file paths. Renaming a folder deletes and re-adds everything inside it, and every citation link breaks.
- Chunk IDs from position. One inserted paragraph re-embeds the whole document.
- Deletes from missing listings, with no guard. One flaky API call wipes out a whole source.
- Parse failures that delete the old version. The document goes from slightly stale to completely missing.
- Query embedder and index model configured in different places. Retrieval quality drops after a deploy and nobody connects it to the model change.
- Re-embedding in place. Mixed vectors during the migration, and no rollback after.
- No freshness metric. Stale content shows up as "the model is hallucinating," and the team spends weeks on prompts.
Checklist
- Every document has a stable source ID, and every chunk has a content-derived ID.
- Unchanged documents skip parsing. Unchanged chunks skip embedding.
- Writes are idempotent and serialized per document. Old events can't overwrite new versions.
- Deletes remove the document, chunks, and every embedding version in one transaction, and leave only a tombstone.
- Listing-based deletes require a complete listing and have a blast-radius cap.
- Each embedding index version has its own table, its model and version recorded, and exactly one active version enforced by the database.
- Queries are embedded with the active index's model, looked up from the registry.
- Model changes go blue/green with a shadow eval and a standby for rollback.
- Failures land in a dead-letter queue and the last good version stays live.
- Freshness lag is measured per source against an agreed SLO, with alerting.
Close
Most RAG quality problems get worked on at the end of the pipeline, in prompts and rerankers. But the answer can only be as current, complete, and correct as the index, and the index is only as good as the pipeline that maintains it.
Treat ingestion like the replication system it is: change detection, stable IDs, idempotent writes, real deletes, a dead-letter queue, versioned indexes with blue/green cutover, and a freshness SLO someone gets paged on.
If you're running a RAG system that's drifting out of sync with its sources, or you need to move to a new embedding model without betting retrieval quality on it, I design and build these pipelines. Let's talk: https://www.bilaltahseen.com/hire-ai-engineer.
Building something with AI?
I help teams ship production AI agents, retrieval systems, and document intelligence. Let's talk about yours.