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.
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
- 1,500
- Aggregate throughput
- 100 GB/s
- IO time per pass
- 3,000 s
- IO time per pass
- 50 min
Buckets = ceil(Data (TB) × 1000 ÷ Usable memory (GB)) = 1,500
Aggregate throughput = Workers × Throughput per worker (GB/s) = 100 GB/s
IO time per pass = Data (TB) × 1000 ÷ Aggregate throughput = 3,000 s
IO time per pass = IO time per pass ÷ 60 = 50 min
| Case | Data (TB) | Usable memory (GB) | Workers | Throughput per worker (GB/s) | Buckets | Aggregate throughput | IO time per pass | IO time per pass |
|---|---|---|---|---|---|---|---|---|
| Worked example | 300 | 200 | 100 | 1 | 1,500 | 100 GB/s | 3,000 s | 50 min |
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.
- Re-parse and re-chunk; compute the new ID set N and load the old set O.
- 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.
- 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 = 10characters 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.
What changed recently
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.
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.
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.
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.
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.
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.
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.
How do you keep the index fresh and honour deletions — for example a UK GDPR erasure request — across the vector store, caches and logs?
Model answer, written in a candidate's voice
- Incremental ingestion: idempotent upserts by document ID and chunk hash; deletes/tombstones fan out to dense, lexical and caches
- Embedding upgrades: parallel index, backfill, compare, cut over with rollback
- Erasure: data map of raw store, chunks, embeddings, caches, logs, eval sets and training data; delete or anonymize, document retention exceptions, verify
- Monitors staleness and surfaces document dates/freshness in answers
- Honest limits: avoid raw PII in logs; backups and training data may need retention or retraining
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.
Model answer, written in a candidate's voice
- Use an incremental state machine over a small buffer, not a regex over the whole stream.
- Emit plain text immediately; buffer only a partial tag, brace, string, or escape until the call closes.
- Track nesting depth and string/escape state so JSON braces and XML tags split across chunks still parse correctly.
- Process each byte once for linear time; define EOF behaviour for unterminated or malformed calls as an explicit error/flush, never silent loss.
- For the server variant, stream words through bounded queues with backpressure, cancel on client disconnect, and flush partial output on close.
- Validate with property-style tests over random chunk boundaries, escapes, nesting, and malformed tails, comparing against a batch parser.
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?
Model answer, written in a candidate's voice
- Split by structure: headings/sections for PDFs and wikis, functions/classes for code, turns/threads for chat; keep tables intact or render as text with repeated headers.
- Small chunks retrieve precisely but lose context; large chunks add context but dilute embeddings and cost tokens; overlap protects boundaries but duplicates storage.
- Attach metadata (title, section path, date, ACL, URL) and prepend document/section context before embedding.
- Use parent-child retrieval: match small units, return the enclosing section/parent.
- Tune chunk size and overlap empirically on a labelled query set using recall@k and downstream answer quality.
You have finished this topic.
Reading
- Designing Data-Intensive ApplicationsThe standard reference on logs, partitioning, batch and stream processing and exactly-once semantics (read the batch and stream processing chapters first).
- MapReduce: Simplified Data Processing on Large ClustersThe map, shuffle and reduce model behind parallelising jobs whose records depend on one another.
- torch.utils.data (PyTorch documentation)Map-style versus iterable datasets, samplers, multi-process loading and pinned memory.
- Stream (Hugging Face Datasets documentation)Streaming, shard-level shuffling with buffers, interleaving and resumable iteration for large datasets.
- The FineWeb Datasets: Decanting the Web for the Finest Text Data at ScaleA detailed, open account of a 15-trillion-token pretraining data pipeline: extraction, filtering and deduplication.
- Deduplicating Training Data Makes Language Models BetterExact and near-duplicate removal at scale and its effect on memorisation and training efficiency.
- Docling Technical ReportAn open document-conversion pipeline (layout, tables, reading order) for RAG ingestion.
- olmOCR 2: Unit Test Rewards for Document OCRModern VLM-based PDF parsing, and a template for measuring extraction of tables, formulas and layouts with unit tests.
Practise this topic
- How do you keep the index fresh and honour deletions — for example a UK GDPR erasure request — across the vector store, caches and logs?
- 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.
- 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?
- 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?
- 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.
- How do you build a training set where every feature value is what was known at the moment of prediction?
- What automated checks would you put on data entering a training pipeline and a serving path?
- What problems does a feature store solve? Describe its offline and online parts and how features flow between them.
- 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.
- 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.
- 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?
- 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?
- 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.
- 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.