ML System Design · Module 5 of 47 · 11 concepts · about 14 min

Data Collection and Logging

Where the data behind an ML system comes from, what to log so a model can learn from it, how events travel from the app to storage, and the privacy rules that apply from the moment data is collected.

At work: Usually the first engineering work on a new ML feature: if the right events are not logged today, there is nothing to train on in three months.

Where ML data comes from

What it is

ML systems draw on a few kinds of source:

  • Product events: what users see and do in the app. Views, clicks, searches, additions to the basket.
  • Business records: the company's own databases. Orders, payments, refunds, stock.
  • Operational data: what the business's systems and people do. Rider GPS pings, packing times, support tickets.
  • Human labels: people judging examples. Reviewers marking content, annotators tagging images.
  • External data: bought or public. Weather, holidays, maps, traffic.

Why it matters

Each source has its own quality, delay and owner.

  • Product events are plentiful but noisy, and depend on the app logging them correctly.
  • Business records are accurate but may change after the fact (an order is refunded a week later).
  • External data can disappear if a contract ends.
  • A design should name the source of every important feature and label.

In the real world: Kirana Kart's delivery-time model uses order records (distance, items), rider GPS (actual times), store systems (packing queue) and an external weather feed.

Visual example

Sources

Delay is how long after the real event the data is usable.

Kirana Kart's data sources and their character
sourceexamplevolumedelaywatch out for
Product eventsItems shown, clicks, searchesVery highSecondsApp bugs; missing logs
Business recordsOrders, refundsMediumSeconds to daysValues updated later
OperationalRider GPS, packing timesHighSecondsGaps; device clocks
Human labelsFraud reviewsLowDays to weeksDisagreement; cost
ExternalWeather, holidaysLowVariesContracts; outages

Assuming data exists because the feature is visible in the app. A screen showing 'recently viewed' does not mean views are stored with timestamps anyone can train on.

Event logging for ML

What it is

An event log for ML must record enough to rebuild each decision later. For every prediction shown to a user, log:

  • who and when: user ID, session ID, timestamp;
  • what was shown: every item, in its position (the impressions), not only what was clicked;
  • the context: device, page, location, the search query;
  • which model produced it, and its version;
  • a request ID that joins the prediction to everything the user did next.

Why it matters

Training data is built from this log, and anything not logged is lost for ever.

  • Without impressions there are no negative examples.
  • Without position you cannot correct for the fact that top items get clicked more just for being on top (module 7).
  • Without the model version you cannot tell which model caused a change.

In the real world: A team that logged only clicks for a year has to start logging impressions and wait another two months before it can train its first proper ranking model.

{
  "event": "recommendations_shown",
  "request_id": "r-8f2c91",
  "user_id": "u-10233",
  "session_id": "s-77a1",
  "ts": "2026-10-14T19:02:11.481Z",
  "surface": "home_top_picks",
  "model_version": "rank-v42",
  "items": [
    {"product_id": "p-551", "position": 1, "score": 0.31},
    {"product_id": "p-019", "position": 2, "score": 0.27}
  ],
  "context": {"store_id": "ds-118", "device": "android", "hour": 19}
}

Logging clicks only. You learn what people chose, but not what they were offered and passed over, so you cannot learn preferences, only popularity.

Logging the features that were served

What it is

When a model makes a live prediction, also log the exact feature values it used, under the same request ID. Later:

  • join the logged features to the label when it arrives;
  • train the next model on those rows.

This is called log and wait, or feature logging.

Why it matters

It is the most reliable way to make training data match production.

  • The model trains on exactly the values it saw live, including any quirks of the live pipeline.
  • It removes a whole class of bugs where training recomputes a feature slightly differently (training-serving skew, module 11).
  • It also lets you debug a single bad prediction months later.

In the real world: Large ad and feed systems at companies like Meta and Google log served features for every prediction; it is the backbone of their training data.

Expecting to add a new feature and train on it immediately. With log and wait, a new feature only has history from the day you started logging it; plan for the wait, or backfill it carefully.

Event schemas and data contracts

What it is

An event schema says what fields an event has, their types and meanings. A data contract is an agreement between the team producing data and the teams using it:

  • the schema, and which fields are required;
  • what each value means, with units ('amount in paise, not rupees');
  • how fresh the data will be;
  • how changes are announced, and what counts as a breaking change.

Why it matters

ML pipelines break silently when upstream data changes.

  • An app release renames a field and the feature quietly becomes empty.
  • A team changes 'amount' from rupees to paise and every price feature is 100 times too big.
  • Contracts, checked automatically, turn these into loud failures at the source.

In the real world: Companies increasingly check events against a schema registry as they are produced, rejecting malformed events instead of letting them reach training data.

Letting each app team log events however they like. Six months later 'add_to_cart', 'addToCart' and 'cart_add' all exist, with different fields, and nobody knows which is right.

Batch and streaming data

What it is

Data reaches ML systems in two ways:

  • Batch (data at rest): collected over a period and processed together, such as yesterday's orders loaded into the warehouse each night.
  • Streaming (data in motion): each event processed as it arrives, within seconds, through a message system such as Apache Kafka or Amazon Kinesis.

Why it matters

Most systems need both.

  • Training uses batch data: large, complete, easy to process.
  • Live features need streaming: 'items added in the last ten minutes' cannot wait for a nightly job.
  • Streaming is more complex and costly to run, so use it only where freshness changes predictions (module 10).

In the real world: Kirana Kart sends every app event to Kafka. One consumer writes them to storage for training; another updates live features such as 'payments by this card in the last hour'.

Visual example

Event path

One stream feeds both live features and training data.

How one event travels at Kirana Kart

  1. AppLogs the event with a request ID
  2. CollectorChecks the schema; rejects bad events
  3. Stream (Kafka)Keeps events in order for every reader
  4. two readers, in parallel
    Live consumersecondsUpdates real-time features
    Storage consumerforeverWrites raw events to cheap storage
  5. WarehousedailyCleaned tables joined with labels, for training

Building everything on streaming because it sounds modern. If a feature changes daily, a daily batch job is simpler, cheaper and easier to fix.

Practise it: Design a Real-Time Anomaly Detection System, Design a Real-Time Fraud Detection System, Design an ML Feature Store

Warehouses, lakes and lakehouses

What it is

Three places data is kept for analysis and training:

  • Data warehouse (BigQuery, Snowflake, Redshift): cleaned tables with fixed columns, queried with SQL. Fast, tidy, more expensive per byte.
  • Data lake (files in S3 or Google Cloud Storage): anything, in raw form, cheaply. Flexible, but can turn into a swamp nobody understands.
  • Lakehouse (Delta Lake, Apache Iceberg, Apache Hudi): table features such as updates, versions and schemas on top of cheap lake files.

Why it matters

Training needs both raw history and clean tables.

  • Raw events in the lake let you rebuild features you did not think of yet.
  • Clean tables in the warehouse or lakehouse make daily training jobs simple and fast.
  • Table formats with time travel (reading the table as it was on a date) make training sets reproducible.

In the real world: Many ML teams store raw events in a lake for a year or more, and build training tables in a lakehouse format so any past training run can be reproduced from the table version it used.

Keeping only cleaned, summarised data. When you need a new feature computed from raw events, the raw events are gone.

ETL and ELT

What it is

Two orders for preparing data:

  • ETL (extract, transform, load): clean and reshape data before storing it in the warehouse.
  • ELT (extract, load, transform): store the raw data first, then transform it inside the warehouse with SQL (often with a tool such as dbt).

Why it matters

ELT has become the common default because storage is cheap and warehouses are powerful.

  • Keeping raw data means a transformation bug can be fixed and re-run.
  • Transformations written as versioned SQL can be reviewed and tested like code.
  • ETL still suits sensitive data that must be cleaned (for example, personal details removed) before it is stored.

In the real world: A typical modern stack loads raw app events and database copies into the warehouse every hour and builds feature tables from them with scheduled, version-controlled SQL.

Transforming in place with no record of how. When a feature looks wrong, nobody can tell which step changed it. Keep transformations in version control.

Privacy from the moment of collection

What it is

Privacy rules apply as soon as data is collected, not only when it is used:

  • Consent and purpose: data collected for delivery may not automatically be usable for advertising.
  • Minimisation: collect only what the feature needs.
  • Personal data: names, phone numbers, exact locations need protection: removal, masking or encryption.
  • Retention: delete data when it is no longer needed, and when users ask.

Laws such as India's Digital Personal Data Protection Act and Europe's GDPR set these duties.

Why it matters

Fixing privacy later is expensive or impossible.

  • A model trained on data that should not have been used may have to be thrown away.
  • A user's request for deletion must reach every copy, including training sets.
  • Designing it in from the start (separate keys, masked fields, retention jobs) costs little.

In the real world: Many companies replace user identifiers with random tokens in training data and keep the mapping in one tightly controlled place, so deletion requests can be honoured everywhere.

Copying production data, personal details included, into notebooks and training buckets 'just for now'. Those copies are rarely found again until an audit.

Before any data exists

What it is

New products often have no history. Ways to start anyway:

  • Rules and heuristics first, while logging begins.
  • Public or bought data to pre-train (product images, maps, weather).
  • Human labelling of a small, well-chosen set.
  • Transfer from a related product or market: a model trained in one city, adapted to another.
  • Exploration: deliberately show varied options and learn from the responses.

Why it matters

Waiting for perfect data stalls projects.

  • A rule plus good logging produces training data as a by-product.
  • Starting small and well-labelled often beats starting large and noisy.
  • The cold-start problem returns for every new user and new product, so the solutions are worth designing in (module 13).

In the real world: When Kirana Kart opens in a new city, the delivery-time model uses the nearest similar city's model plus a correction for distance, until four weeks of local orders exist.

Training on the rule's own decisions as if they were ground truth. If the rule blocks certain orders, you never learn whether they were really fraud; keep a small random sample unblocked, or reviewed, to see.

Interview questions: data collection and logging

What it is

The questions interviewers ask about data collection and logging, from the first screening call to the senior round. Cover the answer, say yours aloud, then compare.

Why it matters

Reading an idea and explaining it are different skills.

  • Each answer below is the two or three sentences an interviewer is listening for.
  • The reasoning behind each one is in the cards above. If an answer surprises you, go back to that card.

In the real world: Ask almost any ML design interviewer what separates good candidates and they mention logging impressions and the model version unprompted.

Q: What would you log for a recommendation system?

Every request with a request ID, user, session, timestamp and context; every item shown with its position and score; the model version; and every later action joined by request ID. Impressions are essential, since they are the negatives.

Q: What is feature logging, or log and wait?

Logging the exact feature values used for each live prediction, then joining them to the label when it arrives. Training then uses the values production really saw, which prevents training-serving skew.

Q: Batch or streaming data?

Batch for training and slowly changing features; streaming only where fresh data changes predictions, such as recent activity for fraud. Streaming is more complex, so use it deliberately.

Q: What is a data contract?

An agreement between the producer and users of data on schema, meaning, units, freshness and how changes are announced, checked automatically so upstream changes fail loudly rather than silently.

Q: Warehouse or lake?

Both, usually. Raw events in cheap lake storage for rebuilding features; clean, versioned tables in a warehouse or lakehouse for training and analysis.

Q: How do you handle privacy in ML data?

Collect only what is needed for a stated purpose, mask or tokenise personal identifiers, set retention limits, and make sure deletion requests reach training data too.

Practise it: Design Feature Monitoring, Diagnose Training-Serving Skew

Exercise: design an event log

What it is

A short build that uses this module's ideas. Write it yourself before looking anything up; the checks at the end tell you whether it works.

Why it matters

An idea you have only read fades in a week.

  • Building it once, even in fifty lines, is what makes it yours.
  • Interviewers can tell the difference between someone who has read about a loop and someone who has debugged one.

In the real world: Data engineers on ML teams spend much of their time on exactly this: event schemas and the queries that turn them into training tables.

Your task. Write the event schema and logging plan for one ML feature, so that training data can be built from it without any further data work.

Steps

  1. Pick a feature: home recommendations, search results or delivery estimates.
  2. Write the JSON schema for the 'prediction shown' event, including request ID, context, items with positions and model version.
  3. Write schemas for the follow-up events (click, add to basket, purchase) and show how each joins back by request ID.
  4. Write the SQL that builds one training row per shown item, with a label of 1 if it was added to the basket within the session.
  5. Mark every personal field and say how it is protected.
  6. Estimate the bytes a day this log will take.

You are done when

  • The training query produces both positive and negative rows.
  • Every row can be traced to the model version that produced it.
  • No personal field is stored unprotected.

Stretch. Add served-feature logging to the 'prediction shown' event and show how the training query changes.