Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Data Engineering for AI
Handbook~15 min readFoundationsworked math + runnable code
The Data Engineering for AI Handbook

Garbage in,
garbage out.

Every RAG system and every fine-tune is only as good as the data you feed it — and raw data is never ready. It arrives as sprawling documents, riddled with duplicates and boilerplate and junk. The pipeline that turns that pile into something usable — chunk it, dedup it, filter it — is unglamorous and decisive: it's where most of the quality is won or lost, long before the model sees a token. And it has a humbling arithmetic: your usable dataset is a compounding fraction of what you started with, and that's exactly as it should be. This handbook is that pipeline.

01

Data is the product

It's tempting to obsess over the model or the retriever and treat data as a given. But in practice the data pipeline is where most AI quality is decided. A great embedding model retrieving over badly-chunked, duplicate-ridden, low-quality passages returns bad results; a modest one over a clean, well-structured corpus returns good ones. The data is the product, and the pipeline that produces it — ingest, chunk, deduplicate, quality-filter — is the real engineering.

This is true for both uses of data. For RAG, the pipeline decides what a retriever can even find: the shape of the chunks, whether duplicates crowd out diversity, whether junk pollutes the results. For training, it decides what the model learns: duplicates get over-weighted, noise teaches bad patterns, and quality filtering is what separates a useful dataset from a large one. Same stages, same discipline. And the humbling truth the pipeline reveals is that most of the raw pile shouldn't survive.

The one-sentence version

Turn raw documents into usable data by chunking, deduplicating, and quality-filtering — and accept that the usable set is a compounding fraction of the raw, because quality beats quantity.

02

Chunk it

Retrieval and context windows work best on focused passages, not whole documents — so the first transform is chunking: split each long document into smaller windows. A retriever can then return the specific passage that answers a query instead of a giant document where the answer is buried. Chunks usually carry a bit of overlap so a fact that straddles a boundary isn't lost between two chunks.

Chunk size is a genuine trade-off. Too large and each chunk mixes several topics, so a query matches on the wrong part and retrieval precision drops. Too small and a chunk lacks the surrounding context to be meaningful on its own. The right size depends on the content (dense technical text vs. narrative) and the task, and it directly sets how many chunks a document becomes — a sliding window of a given size and overlap turns one document into a predictable number of pieces. Chunking is the stage that multiplies your item count up; the next stages cut it back down.

03

Dedup it

Raw corpora are full of copies — the same article syndicated across sites, boilerplate headers and footers, near-identical templates. Deduplication keeps one representative of each distinct piece and drops the rest, and it matters more than it looks.

The pipeline — count goes up, then down
IngestRaw documents from many sources — messy, redundant.
ChunkSplit into overlapping passages — count goes up.
DedupDrop near-identical copies — keep distinct content.
FilterKeep only good chunks — the usable dataset.

In retrieval, duplicates crowd out diversity: ask for the top 5 passages and get 5 copies of the same thing instead of 5 different relevant ones — a real loss of information. In training, duplicated text is over-weighted, driving memorization, wasting compute on redundant examples, and risking eval-data leaking into training. Dedup — exact-match or near-duplicate detection — restores diversity and ensures every surviving item carries new information. It's one of the highest-leverage, least-glamorous steps in the whole pipeline.

04

The yield math

Chunking maps one document of length L to a number of windows of size s with overlap o — roughly the length divided by the step, rounded up:

chunks(L)  ≈  ⌈ (L − o) / (s − o) ⌉   (step = s − o; overlap keeps boundary-spanning facts)

A 1000-token doc at size 200, overlap 50 (step 150) → about 7 chunks. Smaller chunks or more overlap → more pieces.

Then dedup and quality-filter each keep only a fraction, and — crucially — those fractions compound. The usable dataset is the raw count times every stage's keep-rate:

usable  =  raw · rdedup · rquality   ⟹   1000 · 0.6 · 0.5 = 300 usable

Multiplicative: two stages that each keep 60% and 50% leave 30%. That shrinkage is the point — you're keeping the good part, not all of it. The runnable version below chunks a doc, dedups, quality-filters, and computes the compounding yield.

RUN IT YOURSELF

Build the pipeline

The AI data pipeline is a few transforms in sequence. Chunking splits a long document into overlapping windows — a 1000-token doc at size 200, overlap 50 becomes 7 chunks. Deduplication drops copies, keeping the first occurrence and preserving order, so the surviving set is diverse. Quality filtering keeps only chunks above a bar. And the usable dataset is the raw count times each stage's keep-rate — a compounding fraction, so two stages at 60% and 50% leave 30%. Quality beats quantity: fewer, cleaner items win. Change the chunking or the keep-rates and watch the yield.

CPython · WebAssembly
05

Quality beats quantity

The filter stage is where the pipeline's philosophy lives. A few common quality signals:

FilterWhat it removes
Length / boilerplateToo-short stubs, nav menus, headers/footers, cookie banners — content-free chunks.
Language / encodingWrong-language, mojibake, or garbled text that pollutes the corpus.
Quality classifierA model scoring "textbook-like" usefulness — the lever behind data-quality wins.
Toxicity / PIIUnsafe content and personal data (see PII handling).
RelevanceOff-topic content that doesn't belong in this corpus at all.

The recurring lesson across the field — from the Phi models' textbook-quality data to every serious RAG deployment — is that a smaller, cleaner dataset beats a larger, noisier one. Because bad data doesn't just fail to help; it actively hurts, polluting retrieval and teaching wrong patterns. So the engineering goal is not to maximize how much data you keep but how much good data you keep — which means investing in the filters, not just the crawl. The compounding yield isn't a bug to minimize; it's the sign your filters are doing their job.

06

Pitfalls

The first mistake is bad chunk boundaries: splitting mid-sentence or mid-idea (naive fixed-size splitting) produces chunks that are individually meaningless, so retrieval returns fragments. Prefer semantic or structure-aware splitting (paragraphs, sections) and use overlap so nothing important falls in the gap. The second is skipping dedup because "more data is better" — it isn't; duplicates crowd retrieval and over-weight training, and the fix is cheap relative to the harm.

Two more. Over-filtering the other way: an aggressive quality filter can strip legitimate but unusual content and narrow your corpus, so validate that the filter keeps what matters, not just what's average. And no data lineage: when a bad answer traces to a bad chunk, you need to know where that chunk came from — track provenance through the pipeline so you can fix the source, not just patch the symptom. The whole discipline reduces to a mindset shift: treat the data pipeline as the primary engineering surface, measure the yield and quality at each stage, and remember that the goal is the best data, not the most. Get the pipeline right and the model, whichever you pick, has a fighting chance.

Worth knowing

The compounding yield is a feature, not a leak. A pipeline that keeps most of the raw pile probably isn't filtering hard enough — bad data hurts, so a smaller, cleaner dataset routinely beats a larger, noisier one. Invest in the filters, track provenance, and measure quality at each stage, not just count.

By the numbers

Worked example: 2,000 documents through the pipeline

Take 2,000 documents of about 1,000 tokens each (illustrative), and run them through the page’s own settings: chunk size 200, overlap 50, then dedup keeping 60% and the quality filter keeping 50%. Then price the result in what an index actually stores.

StepStageArithmeticResult
1Raw corpus2,000 × 1,000 tokens2,000,000 tokens
2Windows per docstarts at 0, 150, 300 … 900; ⌈950 ÷ 150⌉7 chunks per doc
3Chunk the corpus2,000 × 714,000 chunks
4Tokens stored6 full windows × 200 + one of 100 = 1,300 per doc2,600,000 tokens: 1.3× the raw, because of overlap
5Dedup keeps 60%14,000 × 0.68,400 chunks
6Quality keeps 50%8,400 × 0.54,200 chunks, 30% of step 3
7Vectors to store, 1,536-dim float324,200 × 1,536 × 4 bytes25.8 MB, against 86.0 MB unfiltered
8Tokens to embedabout 30% of 2,600,000about 780,000
9Same corpus at size 500, overlap 50⌈950 ÷ 450⌉ per doc3 chunks per doc, 6,000 in all

Step 4 is the cost people forget. Overlap protects facts at the boundaries, but every overlapping token is stored, embedded and searched twice. Steps 6 to 8 are the pay-off of the compounding yield: the clean index is less than a third of the size, and every passage in it is distinct and passed the bar. Step 9 shows how much the size knob matters. Larger chunks mean fewer, broader passages, cheaper to store but less precise to match. Step 8 assumes the filters drop chunks of roughly average length. A length-based filter does not, so measure the token count after the filter rather than estimating it.

Trade-offs

Cost and trade-offs, stage by stage

Here Time is compute, and Space is what the stage stores or multiplies.

CaseTimeSpaceWhy
Fixed-size chunkingLinear in tokensOverlap multiplies storage: 1.3× in the exampleSimplest, and it cuts mid-sentence. Fine for uniform prose.
Structure-aware chunkingLinear, plus a parser per formatUneven chunk sizesBetter boundaries. A huge section still needs a fixed-size fallback.
Exact dedupOne hash per chunk, linearOne set of hashesCatches identical copies only. A changed date or footer defeats it.
Near-dup, all pairsn² comparisons: 14,000 chunks is 97,993,000 pairsNothing extraFine for thousands of items, hopeless for millions.
Near-dup, MinHash + LSHRoughly linearA fixed-size signature per chunkFinds syndicated and templated copies at scale. The similarity threshold needs tuning on samples.
Heuristic filtersLinear and cheapNoneLength, symbol ratio, language ID. They remove the obvious junk first.
Classifier filterOne model call per chunk: the costliest stageNoneThe biggest quality lever. Run it last, on what the cheap stages left.

Order the stages by cost. Cheap filters and exact dedup first shrink the set the expensive ones touch. In the example, the classifier scores 8,400 chunks instead of 14,000.

In the wild

Where this shows up in production and interviews

  • RAG ingestion that stays correct

    Store each chunk with its source document id, chunk index and content hash. When a document changes, delete its old chunks by id before inserting the new ones. Otherwise the index serves both versions, and the retriever happily returns the outdated one.

  • Pretraining corpora

    Large public text datasets are mostly filtering. C4, for example, is Common Crawl put through heuristic rules that drop boilerplate, very short lines and pages that fail simple quality checks. Lee et al. (2021), Deduplicating Training Data Makes Language Models Better, found that removing near-duplicates cut how often models emit memorised text.

  • Eval contamination

    Hash every eval example, then dedup the training set against those hashes, near-duplicates included. If a benchmark’s questions leaked into training, the score measures memory, not skill. This is the cross-dataset version of the dedup stage.

  • The interview version

    “Design ingestion for RAG over a million documents.” Walk the stages in cost order, state the chunk size and overlap with the step 2 to 4 arithmetic, and explain incremental updates by document id. Then say how you would measure retrieval quality: recall at k on a set of labelled questions, before and after each change.

Self-check

Check yourself

A 1,000-token document is chunked at size 200 with overlap 100. How many chunks, and how many tokens are stored?

The step is 100, so ⌈(1,000 − 100) ÷ 100⌉ = 9 chunks. Windows start at 0, 100 … 800 and all nine are full, so 1,800 tokens are stored: 1.8× the document, against 1.3× at overlap 50. Doubling the overlap took the storage overhead from 30% to 80%.

Top-5 retrieval returns the same press release four times, each with a different site header. Your pipeline has exact dedup. What failed?

Exact dedup hashes the whole chunk, and the headers make each copy different. These are near-duplicates. Strip boilerplate before hashing, or add MinHash-based near-dup detection. Then top-5 brings back five different passages instead of one passage four times.

A new length-and-symbol filter raises average chunk quality, but code questions start failing. Why?

Code is short-lined and full of symbols, so a heuristic tuned on prose throws it away. This is over-filtering: the filter kept what is average, not what matters. Audit a sample of what each filter drops, broken down by source and content type, before you trust the keep-rate.

In the worked example, the dedup keep-rate rises from 0.6 to 0.9 after a crawler change. Good news?

Probably not. The corpus did not suddenly get more original. 14,000 × 0.9 × 0.5 = 6,300 chunks instead of 4,200, and most of the extra 2,100 are likely copies the dedup now misses, perhaps because the new crawler adds a per-page timestamp. A sudden jump in any stage’s keep-rate is a bug to explain before you ship the index.

Frequently asked

Quick answers

What is data engineering for AI?

The pipeline that turns raw documents into clean, usable data for RAG or training — ingest, chunk, deduplicate, and quality-filter.

Why chunk?

Retrieval and context windows work best on focused passages, so long documents are split into overlapping windows the retriever can match precisely.

Why dedup?

Duplicates crowd out diversity in retrieval and over-weight text in training, so keeping one representative of each distinct piece is high-leverage.

Why quality over quantity?

Bad data actively hurts, so a smaller clean dataset beats a larger noisy one; the usable set is the raw count times each stage's keep-rate.

Finished this one? 0 / 209 Handbooks done
NextThe Voice AI Real-Time Agents Handbook Next on the “Shipping an AI product” ladder · rung 3 of 4

This idea in other formats

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks