How to Build a Document Ingestion Pipeline
Extract, normalise, chunk and index documents at scale with stable ids, content hashing and incremental updates that avoid full re-indexing.
On this page
Introduction
Indexing documents once is easy; keeping an index correct as documents change is the hard part. A naive pipeline re-extracts and re-embeds the entire corpus on every run, which is slow, expensive and fragile: one failing document aborts the batch, and there is no record of which version of a document an index entry came from. A production ingestion pipeline treats each document as a versioned unit, hashes its content, processes only what changed, and records enough provenance to debug a stale or duplicated index entry. This tutorial builds that pipeline.
Model Documents as Versioned Units
Give every document a stable id that survives edits, migrations and renames, and a content hash that changes whenever the extractable text changes. The id lets you update the index entry in place; the hash lets you skip work when the content is unchanged. Deriving the id from the source path is fragile because files move, so use an immutable source key such as a database row id or a content-addressed key.
Store the mapping from source to document id and the last ingested hash. When a source changes, the new hash differs, and the pipeline knows to re-extract, re-chunk and re-embed. When it does not, the pipeline does nothing. That single check turns a full rebuild into an incremental update.
import { createHash } from 'node:crypto';
export function contentHash(text: string): string {
return createHash('sha256').update(text, 'utf8').digest('hex');
}
export interface SourceRecord {
sourceKey: string; // stable, immutable source identity
docId: string; // stable index id derived from sourceKey
lastHash: string; // hash of the last ingested text
}
export function needsIngest(record: SourceRecord | null, text: string): boolean {
if (!record) return true;
return record.lastHash !== contentHash(text);
}
Extraction and Normalisation
Extraction converts a source format (PDF, HTML, DOCX, Markdown) into plain text plus metadata. Every extractor is a potential source of garbage: PDFs reorder columns, HTML carries navigation chrome, and scanned pages may need OCR. Normalise whitespace, strip boilerplate, and keep the metadata you will later filter on, such as title, source url and modification time.
Record which extractor version produced the text. When you improve the extractor, the resulting text changes, and you will want to re-ingest everything the old extractor touched. Without that provenance you cannot tell whether a quality problem is in the source, the extractor or the chunker.
import re
from dataclasses import dataclass
@dataclass
class Extracted:
text: str
title: str
source_url: str
extractor_version: str
def normalise(raw: str) -> str:
# Collapse runs of whitespace and drop control characters.
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", "", raw)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def extract_html(raw: str, url: str) -> Extracted:
title = re.search(r"<title>(.*?)</title>", raw, re.S)
body = re.sub(r"<[^>]+>", " ", raw)
return Extracted(normalise(body), (title.group(1) if title else url), url, "html-v3")
Chunking with Overlap and Stable Chunk Ids
Chunking splits long text into passages sized for the embedding model and the prompt. Chunk on natural boundaries such as paragraphs or headings before falling back to a fixed token count, because splitting mid-sentence damages the embedding. Overlap adjacent chunks so a passage that straddles a boundary is not lost.
Derive chunk ids deterministically from the document id, the chunk index and the chunk text, so the same content yields the same chunk id across runs. Stable ids let you upsert without duplicating and let you delete exactly the chunks that a document version no longer produces. Without stable ids, every re-ingest leaks orphaned chunks into the index.
Incremental Index Updates and Deletes
Ingestion becomes three operations: upsert new and changed chunks, delete chunks whose ids are no longer produced by the current version, and leave untouched chunks alone. Compute the set of desired chunk ids for a document, diff it against the ids currently in the index for that document, and apply the difference. This is idempotent: running it twice changes nothing the second time.
Do the writes in a transaction when the store allows it, so a crash mid-update does not leave a document half-indexed. Record the ingested hash only after the index write commits. If the process dies after embedding but before committing, the next run recomputes the same chunks and retries, which is safe because the ids are stable.
-- Upsert chunks and remove ones no longer produced.
INSERT INTO chunks (chunk_id, doc_id, content, embedding, updated_at)
VALUES ($1, $2, $3, $4, now())
ON CONFLICT (chunk_id)
DO UPDATE SET content = EXCLUDED.content,
embedding = EXCLUDED.embedding,
updated_at = now();
DELETE FROM chunks
WHERE doc_id = $5 AND chunk_id <> ALL($6::text[]);
Handling Failures and Poison Documents
One unparseable document must not stall the batch. Isolate each document so a failure marks that document as errored, records the error, and continues with the rest. Track a per-document retry count and quarantine a document after a bounded number of failures so a poison document does not consume the pipeline forever.
Make embedding calls resilient: network and rate-limit errors are transient and deserve retry with backoff, while a validation error such as an over-length chunk is permanent and should fail the document quickly. Distinguish the two so you do not retry a permanent error until the quota runs out.
Reprocessing and Backfills
Sometimes you must re-ingest everything: a new embedding model, a better extractor or a chunking change. Design for this from the start by making ingestion a pure function of the source version, so a backfill is just a run with the skip-hash check disabled. Version the embedding model alongside the chunks so you can rebuild one index without touching the others.
During a backfill, write to a new index and swap when it is complete, rather than mutating the live index in place. That keeps search available while the new index is built and gives you a rollback path if the new model performs worse. Keep both indexes until the new one passes quality checks.
Observability and Common Pitfalls
Emit counters for documents seen, skipped as unchanged, ingested, deleted and quarantined, plus a histogram of ingestion latency and a gauge for chunk count per document. A sudden jump in chunks per document usually means the chunker or extractor changed unexpectedly. Alert on the quarantine counter, because quarantined documents are silently missing from search.
Common pitfalls: deriving ids from file paths, which breaks on rename; re-embedding unchanged chunks and doubling cost; comparing hashes of raw bytes instead of normalised text, which triggers spurious re-ingests when only formatting changed; and forgetting to delete orphaned chunks. Avoid these and the pipeline stays correct and cheap as the corpus grows.
Conclusion
A document ingestion pipeline is fundamentally a diffing problem. Stable ids and content hashes let you detect change, extraction and chunking turn change into new chunks, and a transactional diff turns new chunks into index updates and deletes. Build the skip check, the provenance and the backfill path early, and the difference between re-indexing a whole corpus and updating the few documents that changed becomes one line of logic.
Sources: PostgreSQL: INSERT … ON CONFLICT, LangChain: Text splitters, Content-addressable storage (Wikipedia).
FAQ
- Should chunk ids include the chunk text?
- Hashing the text into the id makes ids change when content changes, which is exactly what you want for detecting changed chunks while keeping untouched ones stable. Just make the derivation deterministic so repeated runs of the same content produce the same ids.
- How do I re-ingest everything after changing the embedding model?
- Version the model with each chunk and write the rebuild into a fresh index, then swap once it passes quality checks. Treating the backfill as a run with the skip-hash check disabled reuses the same code path as normal ingestion.
Report a problem with this articleOpens a pre-filled issue on GitHub.