Databases, Files, APIs and Event Streams
The previous section was about how data is stored. This one is about where it comes from. For most ML projects inside a company, data arrives through four channels: databases, files that someone exports or uploads, APIs of other services, and event streams. Each channel has its own typical failure, and knowing it tells you what to check.
| Channel | Typical example | What usually goes wrong |
|---|---|---|
| operational database | orders, users, bookings | heavy queries slow the live system; tables change without notice; data is overwritten (no history) |
| data warehouse | the analytics copy of many databases, updated nightly | it is a day old; definitions differ between teams ("active user") |
| files | spreadsheet exports, partner CSVs, uploaded documents | manual edits, changing columns, encodings, version confusion ("final_v3_REAL.xlsx") |
| REST API | weather, payments, maps, a partner's product catalogue | pagination, rate limits, timeouts, changing fields, terms of use |
| event stream | clicks, sensor readings, transactions as they happen | duplicates, events arriving late or out of order, gaps |
Operational databases and warehouses
An operational (OLTP) database runs the business: it is optimised for many small reads and writes and usually stores only the current state. If a customer changes their address, the old one is gone, which means you cannot rebuild what the data looked like when a past decision was made. A data warehouse (BigQuery, Snowflake, Redshift, or a Postgres replica) copies the operational data for analysis, often with history (snapshots or "slowly changing dimension" tables). For ML, prefer the warehouse: it does not slow the live system and it can answer "what did we know on 1 March?". The SQL side is in Relational Databases.
REST APIs
A REST API returns data over HTTP, usually as JSON. Real APIs return large results in pages, limit how fast you may call them (rate limits, HTTP status 429), and sometimes fail temporarily (500, 503, timeouts). A client must page through results, wait and retry on temporary errors, and stop on permanent ones. Here a fake API stands in for the network, so the example runs offline; with a real service, the function would call requests.get(url, params=..., timeout=10):
import json
CATALOGUE = [{"sku": f"P{i:03}", "price": round(5 + 1.5 * i, 2)} for i in range(1, 12)]
calls = {"n": 0}
def fake_get(page, per_page=4):
"""Pretend HTTP GET /products?page=..: 429 on the 3rd call, then JSON pages."""
calls["n"] += 1
if calls["n"] == 3:
return 429, {"Retry-After": "1"}, ""
start = (page - 1) * per_page
items = CATALOGUE[start:start + per_page]
body = {"items": items, "next_page": page + 1 if start + per_page < len(CATALOGUE) else None}
return 200, {}, json.dumps(body)
def fetch_all(max_retries=3):
rows, page = [], 1
while page is not None:
for attempt in range(max_retries):
status, headers, body = fake_get(page)
if status == 200:
break
if status in (429, 500, 503):
wait = int(headers.get("Retry-After", 2 ** attempt))
print(f"page {page}: HTTP {status}, waiting {wait} s and retrying")
# a real client would call time.sleep(wait) here
continue
raise RuntimeError(f"HTTP {status}")
else:
raise RuntimeError(f"page {page}: gave up after {max_retries} attempts")
data = json.loads(body)
rows += data["items"]
print(f"page {page}: {len(data['items'])} items")
page = data["next_page"]
return rows
products = fetch_all()
print("total:", len(products), "products in", calls["n"], "calls; last:", products[-1])page 1: 4 items
page 2: 4 items
page 3: HTTP 429, waiting 1 s and retrying
page 3: 3 items
total: 11 products in 4 calls; last: {'sku': 'P011', 'price': 21.5}
Besides the mechanics, APIs come with terms of use: many forbid storing the data, using it to train models, or sharing it. Read them before you build a dataset from an API (more in Public, Licensed and Synthetic Data). Keep API keys out of code and notebooks.
Event streams
An event stream (Apache Kafka, Amazon Kinesis, Google Pub/Sub, MQTT for IoT devices) delivers records continuously, as things happen: a click, a payment, a temperature reading. Streams power real-time features ("number of payments by this card in the last 10 minutes") and are archived to the data lake for training.
Most streaming systems guarantee at-least-once delivery: a record is never lost, but it may arrive twice. Records may also arrive late or out of order, because devices buffer data when offline. Each event therefore needs a unique event id and the event time (when it happened), not only the arrival time:
import pandas as pd
events = pd.DataFrame({
"event_id": ["e1", "e2", "e3", "e2", "e4", "e5", "e6"],
"card": ["A", "A", "B", "A", "A", "B", "A"],
"event_time": pd.to_datetime(["10:01", "10:03", "10:04", "10:03", "10:12", "10:02", "10:14"],
format="%H:%M"),
"arrival_time": pd.to_datetime(["10:01", "10:03", "10:04", "10:05", "10:12", "10:13", "10:14"],
format="%H:%M"),
})
print("arrived:", len(events), "events,", events["event_id"].duplicated().sum(), "duplicate")
late = events["arrival_time"] - events["event_time"] > pd.Timedelta(minutes=5)
print("late events:", events.loc[late, "event_id"].tolist())
clean = events.drop_duplicates("event_id").sort_values("event_time")
per_10min = clean.groupby(["card", pd.Grouper(key="event_time", freq="10min")]).size()
print()
for (card, start), n in per_10min.items():
print(f"card {card}, window from {start:%H:%M}: {n} events")arrived: 7 events, 1 duplicate
late events: ['e5']
card A, window from 10:00: 2 events
card A, window from 10:10: 2 events
card B, window from 10:00: 2 events
The duplicate e2 (delivered twice) is removed by its id, and the late e5 (it happened at 10:02 but arrived at 10:13) is counted in the 10:00 window where it belongs, because windows use the event time. Counting by arrival time would put it in the wrong window and give a real-time feature a different value from the one computed later for training, a mismatch known as training-serving skew.
Pitfalls
- Overwritten history: operational tables hold only the present. Use snapshots or warehouse history to build training data "as of" past dates.
- Silent schema changes: a partner renames a column or an API adds a field. Validate every delivery against the expected schema.
- Duplicates from retries: at-least-once streams and retried API calls create duplicates. Deduplicate on a stable id.
- Event time vs processing time: always keep both; compute features on event time.
- Terms and credentials: read API terms before storing data; never commit keys.
Practice
- A partner sends a CSV export every Monday. Name three checks to run automatically on each new file before it enters your data lake.
Answer
For example: the column names and types match the expected schema; the row count is within a plausible range of last week's; the dates cover the expected week; no key column has duplicates or missing values; the encoding is UTF-8. Reject or quarantine the file if a check fails.
- Why can an operational
customerstable not tell you which customers lived in Hanoi on 1 January?
Answer
It stores only the current address: updates overwrite the old value. You need a history (warehouse snapshots or a table with valid-from and valid-to dates).
Test yourself
An API returns HTTP 429. What does a well-behaved client do?
- Give up immediately
- Wait (as long as
Retry-Aftersays, or with exponential backoff) and retry - Retry as fast as possible
- Switch to a different API key
What does 'at-least-once delivery' imply for a dataset built from a stream?
- Some events are lost
- Some events can appear more than once, so deduplicate by event id
- Events are always in order
- Each event arrives exactly once
Why should windows for features use event time rather than arrival time?
- Arrival time is not stored
- Late events would otherwise land in the wrong window, and training and serving would compute different values
- Event time is always earlier
- It is faster