LearnTopic guide

Data pipelines for ML and LLM systems

Data pipelines turn raw sources into training sets, feature stores and retrieval indexes, and must keep them correct as sources change. Interviewers test whether you can design ingestion that is incremental and idempotent, propagate updates and deletions (including UK GDPR erasure) to every derived copy, parse messy documents and streamed model output robustly, parallelise large jobs and shuffle, deduplicate and shard datasets at scale. The ideas are classic data engineering (immutable logs, partitioning, idempotent writes, lineage, backfills) applied to embeddings, tokens and activations.

Applied LLM · ML engineering · Research8 key concepts14 questions

Start: Key concepts 6 lessons · about 18 min
Contents

Key concepts

Batch, streaming and the log

Batch jobs recompute over partitions (simple and replayable, but data is hours old); streaming jobs process events continuously (fresh, but harder: ordering, late data, state and exactly-once effects). Distinguish event time from processing time and decide how late data is handled. Change data capture turns a source database’s commit log into an event stream, and an append-only log lets you rebuild any derived view by replaying it.

Idempotency and exactly-once effects

Distributed systems deliver at least once, so make every write idempotent: upsert by a deterministic key (document ID plus content hash, not a random UUID), write outputs atomically (to a temporary path, then rename or commit), and record processed offsets with the output. Then retries and replays are safe and the result is effectively exactly once.

Incremental indexing, updates and deletions

For retrieval indexes, detect changes by content hash, re-chunk and re-embed only what changed, and propagate deletes as tombstones to the dense index, the lexical index and any caches. Upgrade the embedding model by building a parallel index, backfilling, comparing retrieval metrics and cutting over. For erasure requests keep a data map of every copy (raw store, chunks, embeddings, caches, logs, eval sets, fine-tuning data, backups); UK GDPR expects a response within one month.

Parsing documents and streams

Document parsing (PDF layout, tables, OCR, reading order) decides retrieval quality; tools such as Docling and vision-language OCR models (olmOCR, trained with unit-test rewards) convert documents into structured text, and structure-aware chunking keeps tables and sections intact. Streamed model output needs an incremental parser: a state machine with a small buffer that handles tags or braces split across chunks, runs in linear time and defines behaviour for malformed or unterminated input.

Parallelising large jobs

Profile first: is the job CPU, IO or accelerator bound? Shard independent records across processes or machines (on standard CPython builds the GIL means threads help only IO-bound work; free-threaded builds, officially supported since Python 3.14, change that for thread-safe code; async suits many concurrent IO waits). If records depend on each other, partition by key and add a shuffle and reduce stage, as in MapReduce. Amdahl’s law caps the speed-up by the serial fraction, and stragglers and retries need idempotent tasks.

Training-data pipelines

Pretraining and fine-tuning data go through extraction, language and quality filtering, deduplication (exact hashes, MinHash for near-duplicates, suffix arrays for repeated substrings), benchmark decontamination, PII handling, tokenisation and packing into sharded formats such as Parquet or WebDataset. Loaders stream shards with several workers and pinned memory, and must resume mid-epoch from saved state; a shuffle buffer only approximates a global shuffle. Newer stages include synthetic rephrasing of web text (structured formats help most; generators above about 1B parameters added little in 2026 work) and generation of executable tasks with tests for RL.

Point-in-time correctness and feature pipelines

Training rows must see feature values as they were available at prediction time: as-of joins on available-at timestamps, versioned snapshots, and offline stores for training with online stores for serving, fed by the same definitions. Backfills recompute history when a definition changes.

Validation, lineage and orchestration

Check schema, nulls, ranges, volume and freshness at each boundary and quarantine bad partitions rather than failing everything. Orchestrators run the DAG with retries and backfills; dataset versioning and lineage answer “which models and indexes used this record?”, which matters for debugging, audits and erasure.

Next: Worked examples Lesson 3 of 6 · about 6 min

Worked examples

Shuffling 300 TB that fits on no single machine

You must globally shuffle 300 TB of cached activations stored in object storage. You have 100 workers, each with 256 GB of RAM (about 200 GB usable for a bucket) and roughly 1 GB/s of read and 1 GB/s of write throughput. Each worker can keep at most 1,000 output files open. Design the shuffle and estimate its cost.

Idea: scatter, then shuffle locally (the classic two-pass, or Rao–Sandelius, shuffle). Assign every record to a uniformly random bucket, then shuffle each bucket in memory and concatenate the buckets. Because the procedure treats every record identically, the result is a uniformly random permutation, not an approximation.

Bucket count. Each bucket must fit in memory: B = 300 TB / 200 GB = 1,500 buckets.

Passes. One scatter pass can write to at most 1,000 buckets, so scatter passes = ⌈log(1,500) / log(1,000)⌉ = ⌈1.06⌉ = 2: first scatter into, say, 40 buckets of 7.5 TB, then re-scatter each into 40 sub-buckets of about 190 GB (1,600 buckets). In general, passes grow with log(data / memory) / log(fan-out).

IO time per pass. Aggregate throughput = 100 × 1 GB/s = 100 GB/s each way, so reading and writing 300 TB takes 300,000 GB / 100 GB/s = 3,000 s ≈ 50 minutes. Two scatter passes plus one in-memory shuffle pass ≈ 2.5 hours and about 900 TB read plus 900 TB written. Object-storage request and egress charges matter at this scale, so keep the work in one region.

Cheaper approximation. Write many small shards (say 1 GB each, 300,000 shards), randomise the shard order each epoch and stream from 10–100 shards at once through a large shuffle buffer. That is fine when records inside a shard are not correlated; it is not fine for activations cached document by document, where neighbouring records are near-duplicates. Do the true shuffle once at write time, then use the cheap method per epoch.

CalculatorCost of a 300 TB shuffle

Buckets = ceil(Data (TB) × 1000 ÷ Usable memory (GB))

Aggregate throughput = Workers × Throughput per worker (GB/s)

IO time per pass = Data (TB) × 1000 ÷ Aggregate throughput

IO time per pass = IO time per pass ÷ 60

Worked cases
CaseData (TB)Usable memory (GB)WorkersThroughput per worker (GB/s)BucketsAggregate throughputIO time per passIO time per pass
Worked example30020010011,500100 GB/s3,000 s50 min
Change the data size, usable memory, worker count and per-worker throughput to see the bucket count and per-pass IO time.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

Incremental RAG ingestion that honours an erasure request

A retrieval index covers 2 million documents (about 60 million chunks of 400 tokens). About 1% of documents change daily. Design ingestion so that only changed content is re-embedded, then show how a UK GDPR erasure request for one customer propagates.

Deterministic IDs. chunk_id = sha256(doc_id + "\n" + chunk_text). An unchanged chunk keeps its ID even if its position moves; a changed chunk gets a new ID. Keep a doc_id → {chunk_id} table.

Daily update for one document.

  1. Re-parse and re-chunk; compute the new ID set N and load the old set O.
  2. Embed and upsert N − O; delete O − N from the vector index, the BM25 index and any caches keyed by those chunks; record the document version and timestamp.
  3. Every step is idempotent, so a crashed run is simply re-run.

Volume. 1% of 2M = 20,000 documents ≈ 600,000 chunks. If about 20% of a changed document’s chunks actually differ, 120,000 re-embeds a day instead of 60 million. At 1,000 chunks/s that is 2 minutes versus 16.7 hours; at an assumed $0.02 per million embedding tokens it is about $1 (48M tokens) versus about $480 (24B tokens) for a full re-index.

Erasure request. Keep a data map and walk it:

Copy Action
Raw documents and parsed text delete, write a tombstone with the request ID
Chunks, embeddings, lexical index delete by doc_id → chunk IDs; embeddings are personal data too
Response and semantic caches purge entries that cited those chunks, or rely on a short TTL
Prompt and trace logs delete or redact by subject ID within the retention policy
Eval sets and fine-tuning data remove; note which model versions were trained on it
Backups put beyond use and let them age out on schedule

Then verify by searching each store for the subject’s identifiers, record completion, and respond within one month. Monitor index staleness (age of the newest indexed version per source) and show document dates in answers.

Streaming parser for tool calls split across chunks

Model output arrives in arbitrary chunks. Emit plain text immediately and each <tool_call>…</tool_call> body as soon as it closes, even when the tags themselves are split across chunks, in linear time.

class ToolCallStream:
    OPEN, CLOSE = "<tool_call>", "</tool_call>"

    def __init__(self):
        self.buf, self.scan, self.in_call = "", 0, False

    def feed(self, chunk: str):
        """Yield ('text', s) and ('call', s) events as soon as they are complete."""
        self.buf += chunk
        while True:
            tag = self.CLOSE if self.in_call else self.OPEN
            i = self.buf.find(tag, self.scan)
            if i == -1:
                if self.in_call:          # resume the search near the end next time
                    self.scan = max(0, len(self.buf) - len(tag) + 1)
                else:                     # flush text, keep a possible partial tag
                    keep = self._partial(self.buf, tag)
                    cut = len(self.buf) - keep
                    if cut:
                        yield ("text", self.buf[:cut])
                        self.buf = self.buf[cut:]
                    self.scan = 0
                return
            if self.in_call:
                yield ("call", self.buf[:i])
            elif i:
                yield ("text", self.buf[:i])
            self.buf, self.scan = self.buf[i + len(tag):], 0
            self.in_call = not self.in_call

    @staticmethod
    def _partial(s: str, tag: str) -> int:
        """Length of the longest suffix of s that is a proper prefix of tag."""
        for n in range(min(len(s), len(tag) - 1), 0, -1):
            if tag.startswith(s[-n:]):
                return n
        return 0

    def close(self):
        if self.in_call:
            raise ValueError("stream ended inside an unterminated tool call")
        if self.buf:
            yield ("text", self.buf)
        self.buf = ""

Why it works:

  • Outside a call, at most len("<tool_call>") − 1 = 10 characters are held back (a possible partial opening tag such as "<tool_"), so text streams to the user with almost no delay.
  • Inside a call, the search restarts near the end of the buffer (scan), so each character is examined a bounded number of times: linear time. For very long calls, collect chunks in a list instead of repeated string concatenation.
  • End of stream inside a call raises a defined error the caller can surface or retry.

Tests: take a reference output with several calls, split it at every possible boundary (and at random boundaries 10,000 times) and assert the event sequence always equals parsing the whole string at once. Add cases for a call at the very start or end, two adjacent calls, and a stray < in plain text. If call bodies are JSON that may contain the closing tag inside a string, track JSON string state too.

Next: What changed Lesson 4 of 6 · about 2 min

What changed recently

  1. Synthetic rephrasing: format matters, generator size does not

    A large controlled study of rephrasing web text for pretraining found that structured formats (tables, maths problems, FAQs, tutorials) helped most, that generators above 1B parameters added no further benefit, and that the choice of source data mattered; it released FinePhrase, a 486-billion-token dataset, reporting generation costs up to 30 times lower than earlier synthetic baselines. Synthetic-data pipelines can be judged on prompt design, source selection and cost per token rather than generator size.

    Source

  2. olmOCR 2: document parsing trained with unit-test rewards

    AI2 trained its open vision-language OCR model with reinforcement learning against binary unit tests on synthetic pages with known HTML, with the largest gains on formulas, tables and multi-column layouts. VLM-based parsing is increasingly used in place of heuristic PDF extraction for training and retrieval corpora, which raises the question of how you would measure extraction quality and cost per page.

    Source

  3. Apache Iceberg V3: deletion vectors and row lineage

    With Iceberg 1.10 the V3 table spec was closed and its features declared ready to use, including deletion vectors, row lineage and a variant type for semi-structured data. Deletion vectors make row-level deletes, such as erasure requests against a training or RAG corpus, cheaper, and row lineage helps incremental pipelines track what changed.

    Source

  4. FineWeb2: a pretraining pipeline for 1,000+ languages

    FineWeb2 extended the FineWeb recipe to more than 1,000 languages (about 20 TB and 5 billion documents from roughly 100 Common Crawl snapshots), adapting filters per language and rebalancing by duplicate counts and quality. It is a worked reference for multilingual data handling, from language identification to per-language filtering and deduplication thresholds.

    Source

  5. SWE-smith: pipelines that produce executable tasks

    SWE-smith generated about 50,000 software-engineering task instances from 128 repositories by synthesising changes that break existing tests, and a 32B model trained on its data reached 40.2% on SWE-bench Verified. Data pipelines now produce environments and verifiable tasks for RL, which need their own validation, deduplication and contamination checks.

    Source

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

Pitfalls

  • Treating a nightly full re-index as the only update strategy, or using random chunk IDs so every re-run creates duplicates.
  • Forgetting derived copies (embeddings, caches, logs, eval and fine-tuning sets, backups) when deleting data.
  • Treating a local shuffle buffer as a global shuffle, or ignoring the IO cost of shuffling at terabyte scale.
  • Using threads for CPU-bound Python on a standard (GIL) build, or parallelising with no plan for failures, retries and ordering.
  • Joining features on the latest snapshot or on event time when the value only landed hours later.
  • Parsers that assume tags never span chunks, or that re-scan the whole buffer on every chunk.

How interviewers probe it

  • ‘Keep the index fresh and honour an erasure request’: follow-ups on embeddings as personal data, caches, logs and backups.
  • ‘Parallelise this slow script’: then ‘records now depend on each other’, then ‘a worker dies halfway — what happens?’
  • ‘Shuffle hundreds of terabytes’: passes, fan-out, IO cost, exact versus approximate shuffles.
  • ‘How would you chunk policy PDFs with tables, wiki pages, chat threads and code?’ and ‘how would you notice the parser broke?’
  • Research labs: build a pretraining or fine-tuning data pipeline — deduplication, quality filtering, decontamination, mixing ratios, resumable loading.
  • MLE: feature pipelines with point-in-time joins, backfills and freshness SLAs.
Next: Quiz Lesson 6 of 6 · about 3 min

Quiz

Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.

  1. Question 1 of 3 · Applied LLM · Technical · Medium

    How do you keep the index fresh and honour deletions — for example a UK GDPR erasure request — across the vector store, caches and logs?

  2. Question 2 of 3 · Applied LLM · Coding · Hard

    Model output arrives as arbitrary text chunks. Write a parser that emits each complete tool call (in a given XML or JSON format) as soon as it closes, while passing plain text straight through. Variant: write the server side that streams words incrementally like an LLM endpoint.

  3. Question 3 of 3 · Applied LLM · Technical · Easy

    How would you chunk a mixed corpus of policy PDFs with tables, wiki pages, chat threads and code? What do you trade off when picking chunk size and overlap?

Reading

Practise this topic

  1. How do you keep the index fresh and honour deletions — for example a UK GDPR erasure request — across the vector store, caches and logs?Applied LLM · Technical · Medium
  2. Model output arrives as arbitrary text chunks. Write a parser that emits each complete tool call (in a given XML or JSON format) as soon as it closes, while passing plain text straight through. Variant: write the server side that streams words incrementally like an LLM endpoint.Applied LLM · Coding · Hard
  3. How would you chunk a mixed corpus of policy PDFs with tables, wiki pages, chat threads and code? What do you trade off when picking chunk size and overlap?Applied LLM · Technical · Easy
  4. A single-process script that handles a huge dataset of independent records is too slow. How would you parallelise it, and what changes if the records depend on one another?Research · Technical · Medium
  5. You must shuffle a training set of hundreds of terabytes (for example, cached model activations) that cannot fit in memory on any one machine. Design an approach and analyse its cost.Research · System design · Hard
  6. How do you build a training set where every feature value is what was known at the moment of prediction?ML engineering · Technical · Medium
  7. What automated checks would you put on data entering a training pipeline and a serving path?ML engineering · Technical · Easy
  8. What problems does a feature store solve? Describe its offline and online parts and how features flow between them.ML engineering · Technical · Medium
  9. Design a pipeline that turns 50 million PDFs (born-digital reports, scanned forms, papers with tables and equations) into clean text for pretraining and retrieval. Choose between heuristic extractors and a vision-language OCR model, estimate the cost, and explain how you would measure quality.Applied LLM · System design · Hard
  10. You need RL training data for a coding agent: thousands of executable tasks, each with an environment and tests. Design a pipeline, in the spirit of SWE-smith, that generates, validates and decontaminates them.Applied LLM · System design · Hard
  11. Python 3.14 made the free-threaded (no-GIL) build officially supported. For an LLM data-processing service that tokenises, parses JSON and calls model APIs, what would you change, what would you keep, and what could break?Applied LLM · Technical · Medium
  12. A 2025 study found that about 250 poisoned documents could implant a backdoor in language models from 600M to 13B parameters, regardless of how much clean data they saw. What does this change about how you build and check a training corpus scraped from the web?ML engineering · Technical · Medium
  13. You lead a team training a 7B open model. Leadership asks why the plan has separate pretraining, mid-training, long-context and RL stages instead of just pretraining for longer. Using Olmo 3’s published model flow, justify the budget split and the gates between stages.AI leadership · Case study · Medium
  14. Your corpus is 2 million pages of scanned reports full of charts and tables. Compare an OCR-and-chunk text pipeline with retrieving page images using a ColPali-style vision-language retriever: quality, index size, latency and how you would evaluate the choice.ML engineering · Technical · Medium

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.