Data Sources & Ingestion
After this lesson, you will be able to:
- Identify the four major places ML data lives (APIs, databases, files, and event streams) and pick the right ingestion pattern for each based on freshness, scale, and cost
- Choose between row-oriented (CSV, JSON) and columnar (Parquet, ORC) file formats based on whether you'll read whole rows or just a few columns at a time
- Pull data reliably from rate-limited paginated APIs using retries with exponential backoff, idempotency keys, and incremental cursors so retries don't double-count records
- Pick a sampling strategy (uniform, weighted, stratified, or reservoir) that gives your model an honest view of the data distribution without blowing up storage or training time
Before you start
Don't worry if APIs, databases, and streams feel like four different worlds — they kind of are, but the same patterns (paginate, retry, validate, store) show up in all of them.
#The Four Worlds Where ML Data Lives
#World 1: APIs (REST, GraphQL, Webhooks)
APIs are how you pull data from someone else's running system in real time. They are the most common source for ML data in the wild because most data lives in SaaS tools today.
The four ingestion patterns for APIs
- Pull (you call them): Standard REST/GraphQL. You send a request, they return data. Used for one-shot extracts and scheduled batch pulls.
- Push / Webhooks (they call you): They send events to your endpoint when something happens. Used by Stripe, GitHub, Slack, and most event-driven SaaS.
- Long-polling / SSE / WebSocket: You hold a connection open and they stream events down it. Used by Twitter/X firehose, Slack RTM, and live feeds.
- GraphQL: One endpoint, you specify exactly which fields you want. Less wasted bandwidth, but more complex to cache.
#Pagination, Rate Limits, and Retries: the three things that always bite you
APIs almost never return your full dataset in one response. They paginate (return results in chunks), rate-limit (cap how many requests you can make per minute or hour), and fail intermittently (network blips, server hiccups). Production-grade ingestion has to handle all three.
Your script extracts 50,000 records from a paginated API. Halfway through page 250, the network drops and your script crashes. You restart it. What's the safest way to resume?
next_cursor or updated_after parameter for exactly this reason.#World 2: Databases (OLTP and OLAP)
Databases are where structured business data lives. The first distinction to learn:
- OLTP (Online Transaction Processing) — PostgreSQL, MySQL, SQL Server. Optimized for many small reads/writes (your app's user table). Row-oriented.
- OLAP (Online Analytical Processing) — BigQuery, Snowflake, Redshift, ClickHouse. Optimized for big aggregate queries (revenue by month). Columnar under the hood.
#Three ways to get data out of a database
- Full extracts:
SELECT * FROM usersonce a day. Simple, but expensive at scale. - Incremental extracts:
SELECT * FROM users WHERE updated_at > :last_run. Requires a reliable update timestamp on every row. Most production tables have one. - Change Data Capture (CDC): Listen to the database's transaction log directly (Postgres WAL, MySQL binlog) using tools like Debezium. You get every insert, update, and delete in near real time, without slamming the database with queries.
For ML, CDC is the gold standard when you need fresh features at low latency, because it gives you a stream you can replay and reprocess.
#World 3: Files (CSV, JSON, Parquet, Avro, ORC)
Files are the most common ML starting point. The format you choose decides whether your training job takes 10 minutes or 10 hours.
#When to use which format
| Format | Best for | Avoid for |
|---|---|---|
| CSV | Tiny datasets, human-editable inputs, debugging | Anything > 1 GB, anything with nested data |
| JSON / JSONL | API payloads, log lines, semi-structured docs | Wide tabular data, columnar queries |
| Parquet | Tabular ML training data, analytics, archives | Streaming row-by-row appends |
| Avro | Streaming pipelines, schema-evolving events (Kafka) | Ad-hoc analytics queries |
| ORC | Hadoop/Hive ecosystems | Outside the Hadoop world |
#World 4: Event Streams (Kafka, Kinesis, Pub/Sub)
When you need data within seconds of it happening — fraud detection, recommendation systems reacting to live behavior, autonomous vehicle sensors — you need streams.
A stream is an append-only log of events. Producers write to the end; consumers read forward through it. Each event has an offset (position in the log) so consumers can resume exactly where they left off after a crash.
- App produces events to Kafka (clicks, purchases, sensor readings)
- A streaming job (Flink, Spark Streaming) reads events, computes features
- Features land in a feature store with low-latency lookup
- Online inference reads from the feature store at request time
You don't need streams for most ML projects. Use batch unless your business requires sub-minute freshness. A daily batch pipeline is 10x simpler and 10x cheaper than a streaming one. Streams earn their cost only when stale predictions cost real money.
#Joins and Multi-Table Prep
users with orders with events with products. The mechanics of joining are easy; the cardinality is what bites people.- Inner join: Keep only rows that match in both tables. Loses unmatched rows on either side. Use when you genuinely need data from both.
- Left join: Keep all rows from the left table; fill nulls where the right table has no match. The most common ML join — "for every user, attach their last 30 days of orders, even if they have none."
- Full outer join: Keep everything from both. Rare in ML.
- Anti-join: Keep rows in the left that have no match in the right. Useful for "users who never placed an order."
SUM(order_total) GROUP BY user_id) when you only want one row per entity.#Sampling: When Your Data Is Too Big
When your full dataset is too big to train on directly, you sample. The sampling strategy determines whether your model sees an honest distribution or a distorted one.
How likely is it that a uniform sample misses a rare class entirely? The answer is a one-line product.
- Uniform random: Every row has equal probability. Default choice, but bad for rare classes.
- Weighted: Each row has a probability proportional to some weight. Useful when records have different importance.
- Stratified: Sample within each class proportionally (or equally). Guarantees rare classes are represented. Always your starting point for imbalanced data.
- Reservoir: Sample k items from a stream of unknown length, with each item having equal probability. Used when you can't store the full stream.
#Try It Yourself: A Resilient API Ingester
Tests: Verify all 57 records are pulled. Verify no duplicates after retries. Verify the script handles 429s and 503s gracefully without crashing.
#When Things Go Wrong
#The Pipeline View
Notice how the early stages (Sources, Extract) are exactly where this lesson lives. Everything you've learned about APIs, databases, files, and streams plugs into the "Sources" box. The patterns from later stages (validation, transformation, monitoring) come up in the next few lessons.
#Key Takeaways
- Four worlds, one contract. APIs, databases, files, and streams all need extraction that is faithful (no quiet drops), reliable (retries don't corrupt), and observable (you know when it breaks). The mechanics differ; the discipline doesn't.
- Pagination, rate limits, and retries always show up. Build exponential backoff with jitter, idempotency keys, and cursor-based resumption into your ingestion code from day one. Bolting them on later means rewriting the whole thing.
- Pick file format by query pattern. Parquet (or ORC) for tabular ML and analytics, JSON/JSONL for nested log data, CSV only for tiny human-editable files, Avro for evolving streaming schemas. Default to Parquet.
- Sample with care. Uniform sampling silently breaks rare-class problems. Use stratified sampling whenever class balance matters, and reservoir sampling when the stream length is unknown.
- Use streams only when you need them. Daily batch pipelines are 10x simpler and 10x cheaper than streaming pipelines. Streams earn their complexity only when stale predictions cost real money in real seconds.
#Quick Check
An API returns 100 records per page and you need 1M records. The rate limit is 60 requests per minute. What's the minimum wall-clock time to extract everything, ignoring retries?
Modern columnar formats (Parquet, Iceberg, Delta) and zero-copy engines (DuckDB, Polars) have collapsed the cost of "store everything raw and decide later", which is why every serious ML team in 2026 ingests into a lakehouse before doing any feature engineering.