Skip to content

ML System Design and Feature Stores

Advanced 55 min read Part 16 of 18

How production ML systems work: lifecycle, batch/online/streaming serving, feature stores and point-in-time joins, skew, rollout, drift, two-stage recommenders.

Summary#

A machine learning (ML) system is far more than a model. The model is a small box in the middle of a large machine that:

  • collects data and turns it into features, the numeric inputs a model consumes;
  • produces labels, the outcomes the model learns to predict;
  • trains models offline on historical data;
  • serves predictions online, in batches or from streams, under latency and cost budgets;
  • watches live behaviour, because the world drifts and models silently go stale.

The same ideas recur in almost every ML design:

  • Offline vs online. Training is a throughput-bound batch job over months of history. Inference is a latency-bound request path, often under 50–100 ms. They run on different infrastructure but must see the same features computed the same way.
  • Feature stores solve that "same features" problem. An offline store (a warehouse or lake) holds the full history for training. An online store (Redis, DynamoDB, Cassandra) holds the latest value per entity for millisecond lookups. Point-in-time joins guarantee that training only ever sees feature values that existed at the moment of each label, so no future information leaks in.
  • Training-serving skew is the most common silent failure: the model sees one distribution in training and another in production, because of different code, stale data or time leakage.
  • Models are versioned artefacts in a registry and roll out like risky code: shadow first, then canary, then an A/B test that measures business metrics, with instant rollback.
  • Monitoring watches data drift, prediction drift and delayed ground truth, not just latency and errors.
  • Large-catalogue ranking problems use a two-stage (often multi-stage) design. Cheap candidate generation, typically embedding retrieval with approximate nearest-neighbour search, narrows millions of items to hundreds or thousands. An expensive ranker then scores those few precisely.

In interviews, an ML design is judged on problem framing (what exactly to predict and why), data and labels, features, model choice, serving architecture, evaluation offline and online, and monitoring. The model architecture itself matters least.

Why It Exists#

Building a model in a notebook is easy. Running one that makes millions of good decisions per day, keeps making them as users change, and can be debugged when it doesn't, is a distributed systems problem. Several gaps make it hard:

  • The data gap. Notebooks train on a CSV snapshot. Production needs fresh features from event streams, databases and logs, joined correctly and computed identically in two very different environments.
  • The latency gap. A model that takes 2 seconds and a large GPU per prediction is useless on a feed that must render in 200 ms for 100,000 requests per second.
  • The time gap. Models learn from the past and act in the future. User tastes, fraud tactics, prices and catalogues change, so a model that was accurate in March can be quietly wrong by June.
  • The feedback gap. Ground truth often arrives late (did the loan default? did the user churn?) or is shaped by the model itself, since users only click what was shown.
  • The organisational gap. Data scientists, data engineers and product engineers each own a piece. Without shared platforms, every team rebuilds pipelines, features and deployment by hand.

In "Hidden Technical Debt in Machine Learning Systems" (NeurIPS 2015), D. Sculley and colleagues at Google described this vividly. In a mature ML system, the model code is a small fraction of the total. Most of the effort is in data collection, feature extraction, verification, serving infrastructure, configuration and monitoring. That surrounding machinery also builds up debts that ordinary software doesn't: entangled features, hidden feedback loops and undeclared consumers of model outputs.

ML system design exists to build that surrounding machinery deliberately, as reusable platform components (feature stores, training pipelines, model registries, serving layers, monitoring) rather than one-off scripts.

How It Works#

Every production ML system, from a fraud detector to TikTok-style recommendations, is a loop. Data flows in, becomes features and labels, trains a model, and the model's predictions change user behaviour, which generates the next round of data.

The rest of this section walks the loop stage by stage, then covers the two architectures that come up most: feature stores and two-stage recommenders. It ends with a framework for answering ML design interviews.

The ML lifecycle: data, features, training, serving, monitoring#

1. Problem framing. Most failed ML projects fail here, not in the model. Turn a business goal into a precise prediction task:

  • Business objective. Increase watch time, reduce chargebacks, cut delivery-time estimation error.
  • ML objective. A quantity a model can predict from data available at decision time: "probability this user watches this video for over 50% of its length", "probability this transaction is disputed within 90 days", "minutes until the order arrives".
  • Task type. Binary classification (click or not), multi-class (which category), regression (how many minutes), ranking (order these items), retrieval (find similar items), or generation.
  • Decision. How the prediction is used: shown to a user, used as a threshold to block a payment, used as one input to an auction. The decision determines which errors cost the most. A fraud model trades false positives (good customers blocked) against false negatives (fraud let through), and those have very different prices.
  • The baseline. What happens today without ML: a rule, a popularity list, a human. ML must beat that by enough to justify its operational cost. Google's "Rules of Machine Learning" (Martin Zinkevich) advises shipping a simple heuristic first, then a simple model, and complicating things only when metrics demand it.

2. Data and labels.

  • Data sources. Interaction logs (impressions, clicks, watch time, purchases), entity data (user profiles, item metadata), context (time, device, location) and sometimes third-party data.
  • Labels come from three places:
    • Implicit feedback, such as clicks and dwell time. It's plentiful but noisy and biased by what was shown.
    • Explicit feedback, such as ratings, reports and chargebacks. It's sparse but meaningful.
    • Human annotation, which is expensive and slow, and is used for content moderation, search relevance and training data for classifiers.
  • Label delay. Some outcomes arrive in milliseconds (click). Some take days (purchase after browsing) or months (loan default). A long label delay limits how quickly you can retrain and how quickly monitoring can notice accuracy loss.
  • Bias in logged data. Users can only click what the current system showed them. Training only on those impressions teaches the next model the previous model's blind spots (selection bias and position bias). Countermeasures include logging the position and the probability that an item was shown, a small exploration slice of random or diversified results, and debiasing techniques such as inverse propensity weighting.
  • Data quality must be checked automatically: schema, null rates, value ranges, row counts, duplicate events. A silently broken upstream pipeline that fills a feature with zeros is one of the most common incidents in ML production.

3. Features. A feature is a function from raw data to a number or vector the model can use. Common families:

  • Entity attributes. Account age, item category, price.
  • Aggregates over windows. A user's clicks in the last 1 hour, 1 day and 30 days; a merchant's chargeback rate over 90 days. These are the backbone of most tabular models.
  • Cross features. User-category affinity: how often this user engages with this item's category.
  • Context. Hour of day, device, country, network type.
  • Embeddings. Dense vectors learned from behaviour or content (text, images), summarising an entity in, say, 64–256 dimensions.
  • Real-time signals. Items viewed in this session, the last search query, the number of card attempts in the last 5 minutes.

Each feature has a freshness requirement (how stale it may be), a computation mode (batch, streaming or on-demand at request time) and a cost. Feature engineering is usually where the biggest accuracy gains come from in tabular problems.

4. Training.

  • Dataset construction. Join labels to the feature values as they were when each prediction would have been made (the point-in-time join, below). Split by time, not randomly: train on weeks 1–8, validate on week 9, test on week 10. Random splits leak the future into training and inflate offline metrics.
  • Model choice.
    • Start with what the data supports. Gradient-boosted decision trees (XGBoost, LightGBM, CatBoost) are the strong default for tabular features.
    • Deep networks shine with sparse IDs (large embedding tables), sequences, text and images.
    • Logistic regression is still a fine first baseline and is easy to calibrate and explain.
  • Training infrastructure. Data-parallel training on GPU or CPU clusters, orchestrated by a pipeline tool (Airflow, Kubeflow Pipelines, Metaflow, cloud services such as SageMaker or Vertex AI). Experiment tracking (MLflow, Weights & Biases) records the code version, data snapshot, hyperparameters and metrics for every run.
  • Offline evaluation uses metrics matched to the task:
    • AUC or log loss for classification;
    • RMSE or MAE for regression;
    • precision and recall at an operating threshold for decisions;
    • recall@K, NDCG or MAP for ranking.
    • Also evaluate on slices (new users, small countries, rare categories), because an average can hide a regression on an important minority.
  • Retraining cadence. It ranges from one-off (a stable problem) to scheduled (daily, weekly) to continuous or online learning (ads and feeds that change by the hour). Shorter cadences cost more but limit staleness.

5. Serving. The trained artefact is packaged with its preprocessing, registered, and deployed to one of three serving modes (next sections). The serving system fetches features, runs the model, applies business rules, and logs the prediction with the exact feature values used. That prediction log is the raw material for monitoring, debugging and the next training set.

6. Monitoring and iteration. Production metrics close the loop: system health (latency, errors, throughput), data health (feature distributions, missing values), model health (prediction distribution, calibration, accuracy once labels arrive) and business outcomes. When something drifts, retrain. When a new idea appears, run an experiment. The loop never ends.

Offline training vs online inference#

The two halves of an ML system have opposite shapes:

AspectOffline trainingOnline inference
GoalFit the best model on historyAnswer one request fast and cheaply
InputMillions to billions of labelled rowsOne entity, or a few hundred candidates
Bound byThroughput: hours of GPU or CPULatency: p99 often under 50–100 ms
Data sourceOffline store, lake, warehouseOnline store, request context, streams
Failure costA late job, rerun tomorrowA broken page or a blocked payment now
ScalingMore workers, bigger batchesMore replicas, caching, smaller models
Typical toolsSpark, Ray, PyTorch, XGBoost, AirflowTriton, TF Serving, TorchServe, KServe, ONNX Runtime

Why they must still agree. The model learned a function of features as computed in training. If inference computes "purchases in the last 7 days" with a different window boundary, time zone, deduplication rule or default value, the model receives inputs it never saw, and its predictions are quietly wrong. Most of ML platform engineering is about guaranteeing this agreement: shared feature definitions, logged features, and validation that compares the two.

What happens on the request path. A typical online prediction, such as scoring a transaction for fraud:

  1. Request arrives with context: user ID, card ID, merchant, amount, device fingerprint.
  2. Feature fetch. Look up precomputed features by entity key from the online store: user aggregates, merchant risk, device history. That's typically one batched round trip of 1–5 ms to Redis or DynamoDB.
  3. On-demand features computed from the request itself: amount relative to the user's average, distance from the last transaction.
  4. Model inference. A gradient-boosted tree runs in well under a millisecond on CPU. A deep model may need 5–20 ms, or a GPU.
  5. Post-processing. Calibration, thresholds and business rules ("always allow under $1 for trusted merchants"), then the decision.
  6. Logging. Write the request, the features, the model version and the score to a log stream, asynchronously so it doesn't add latency.

The budget is often around 50 ms end to end, so every hop is designed to be a single parallel lookup.

Batch, online and streaming serving#

There are three ways to get predictions to where they're used. Choosing between them is usually the first serving decision in an ML design.

Batch inference precomputes predictions for all known entities on a schedule.

  • How it works. A Spark or Ray job loads the model, scores every user (or every user-item pair in a candidate set), and writes the results to a table or key-value store. At request time the app does a simple lookup.
  • Strengths. Cheap per prediction, since batch hardware runs at high utilisation. Trivial at request time: a 1 ms key lookup. Easy to inspect: you can look at tomorrow's predictions before shipping them. Heavy models are fine.
  • Weaknesses. Predictions are as stale as the last run. They can't use request-time context (the current query, the session so far). They waste work on entities that never show up, often the majority of users on a given day. New users and items get nothing until the next run (cold start).
  • Fits. Daily email recommendations, churn scores for a retention team, a "because you watched" row refreshed nightly, demand forecasts for inventory, lead scoring.

Online (real-time) inference scores inside the request.

  • How it works. A model server (behind a load balancer, autoscaled) receives the request, fetches features from the online store, runs the model and responds.
  • Strengths. Uses the freshest context: current session, query, location, cart. Covers new users and items immediately. Computes only what's needed.
  • Weaknesses. Latency and availability now sit in the product's critical path. The feature fetch must be fast and reliable. Capacity must handle peak traffic. Costs scale with request volume.
  • Fits. Search ranking, feed ranking, fraud checks at payment time, ETA prediction, ad click-through prediction, dynamic pricing.

Streaming inference scores events as they flow through a stream processor.

  • How it works. A Flink, Kafka Streams or Spark Structured Streaming job consumes events, maintains windowed state (features), calls the model (embedded in the job or over RPC) and emits scores to a topic or store (Apache Flink and Stream Processing).
  • Strengths. Near-real-time (seconds) without being in a user's request path. Natural for event-driven decisions, and the computed features can also feed the online store.
  • Weaknesses. Stream processing is operationally heavy: state, checkpoints, late events, reprocessing. Latency is seconds, not milliseconds.
  • Fits. Real-time anomaly detection on metrics, account-takeover detection on login streams, content moderation queues, updating "trending" scores, and keeping online features fresh for later requests.

Hybrids are the norm. A feed might precompute candidates and user embeddings in batch, update session features in a stream, and rank online. A fraud system might score every transaction online, while a streaming job flags patterns across many transactions and a nightly batch job retrains and rescores merchants.

Model serving infrastructure.

  • Model servers. NVIDIA Triton Inference Server (multi-framework, GPU-optimised, dynamic batching), TensorFlow Serving, TorchServe, ONNX Runtime embedded in an app, and Kubernetes-native layers such as KServe, Seldon or Ray Serve. Managed options include SageMaker endpoints and Vertex AI endpoints.
  • Dynamic batching. GPUs are efficient on batches. A server that waits a few milliseconds to group concurrent requests can multiply throughput at a small latency cost, the same idea LLM servers push much further (Designing LLM and AI-Powered Systems).
  • Model optimisation for latency and cost:
    • Quantisation (FP32 → FP16/INT8);
    • Distillation, training a small "student" to mimic a large "teacher";
    • Pruning;
    • compiling to optimised runtimes (TensorRT, ONNX).
  • CPU vs GPU. Tree models and small networks serve well on CPU. Large embedding models, transformers and vision models need GPUs. GPU utilisation drives cost, so batching and right-sizing matter.
  • Caching predictions. If the same input recurs (an item's content embedding, a popular query's ranking), cache the result with a TTL. Many systems cache user and item embeddings and compute only the cheap final scoring online (Caching Fundamentals).
  • Fallbacks. If the model server or the feature store is slow, serve a cached prediction, a simpler model or a popularity list, never an error page. A recommendation that's 10% worse is far better than an empty feed (Resilience Patterns: Timeouts, Retries and Circuit Breakers).

Worked capacity example.

  • The load. A ranking service gets 20,000 requests/s at peak. Each request scores 500 candidates, and one request's batch of 500 takes about 2 ms on a GPU.
  • Per GPU. A GPU is underused at that batch size, so dynamic batching groups four concurrent requests (2,000 rows) into one pass that takes about 4 ms instead of 8. That's roughly 1,000 requests/s per GPU, for a few milliseconds of added queueing.
  • The fleet. Peak needs about 20 GPUs. With 30–40% headroom for failover and spikes, provision about 26–28.
  • Feature fetches. Each request needs user features plus 500 item feature rows. At 20,000 requests/s that's 10 million item lookups per second. That's why item features are usually cached in the ranking service's memory or bundled with candidates, rather than fetched per request from a remote store.

Feature stores: offline store, online store and point-in-time correctness#

A feature store is a data system dedicated to features. It gives teams one place to define a feature once, compute it in batch or streaming, store its history for training and its latest value for serving, and serve it consistently to both.

Problems it solves:

  • Duplicate work. Without one, every team computes "user's 30-day spend" in its own pipeline, slightly differently.
  • Skew. Training reads features computed in SQL in the warehouse, while serving recomputes them in Java in the request path. The two versions drift.
  • Leakage. Building training sets by joining "current" feature values to old labels leaks the future.
  • Latency. Serving needs millisecond lookups. Warehouses answer in seconds.
  • Discovery and governance. Which features exist, who owns them, what they mean, which models use them, and whether they contain personal data.

The two stores:

  • Offline store. Holds every historical value of every feature, with timestamps. It's built on columnar, cheap, scan-friendly storage: Parquet or Delta/Iceberg tables in a lake, or a warehouse such as BigQuery, Snowflake or Redshift (Data Pipelines, Warehouses and Lakes). Its job is large scans and point-in-time joins for training and batch scoring. Size runs from terabytes to petabytes. Latency of seconds to minutes is fine.
  • Online store. Holds only the latest value per entity key (user_id → feature vector), on a low-latency key-value store such as Redis, DynamoDB, Cassandra or Bigtable. Its job is batched lookups in 1–10 ms at p99, at very high QPS (Redis in Practice, Amazon DynamoDB in Practice). It's sized for the working set: for example, 200 M users × 2 KB ≈ 400 GB, plus replication.
  • Materialisation. This is the process that copies the latest values from the offline computation into the online store on a schedule, while streaming pipelines write fresh values directly. Each feature has a TTL: if the value is older than, say, 2 days, the store returns "missing" rather than misleadingly stale data, and the model must handle missing values.

Three kinds of feature computation:

KindComputedFreshnessExample
BatchScheduled SQL or Spark over the warehouseHours to a day90-day purchase count, merchant chargeback rate
StreamingFlink or Spark Streaming over events, windowedSecondsCard attempts in the last 10 minutes, clicks this session
On-demandIn the serving path, from request data plus stored featuresInstantAmount ÷ user's average amount, distance to last login

Point-in-time correctness. This is the subtle part. A training example is a label event: "transaction T at 14:02 on 3 March was later marked as fraud". The features attached to it must be the values that were known at 14:02 on 3 March. That rules out today's values, and it rules out values computed from data that arrived after 14:02.

Join naively against the current feature table and the model learns from the future. Take "number of chargebacks on this card": today it includes the very chargeback being predicted. Offline accuracy looks spectacular, then production accuracy collapses. This is data leakage, and it's the single most common reason an ML model "worked offline but not online".

The join is an as-of join: for each label row, and for each feature view, take the most recent feature row whose event timestamp is at or before the label's timestamp, and within the feature's TTL. Feature stores implement this in SQL (window functions or ASOF JOIN where the engine supports it) or in Spark, often with partitioning by entity and time to keep it scalable. The implementation section shows a SQL version.

Two timestamps matter for each feature row:

  • Event time, when the underlying event happened;
  • Ingestion or availability time, when the value was actually available to the serving system.

If the 1-day aggregate for 3 March only lands in the online store at 02:00 on 4 March, then a strictly correct training set for a 3 March 23:00 prediction must use the 2 March aggregate. Careful feature stores track this availability lag so training mirrors what serving could really see.

Backfills. When a new feature is defined, you need its history to train with it. The feature store recomputes the transformation over past data, a backfill, and writes timestamped history to the offline store. Streaming features need a batch equivalent for backfill, ideally the same code run in batch mode (the "Kappa" idea of replaying the log, or a framework that compiles one definition to both engines; see Batch vs Stream Processing).

Feast and Tecton.

  • Feast is an open-source feature store, originally created at Gojek with Google Cloud. It's deliberately lightweight: you declare entities (user, driver), data sources (warehouse tables, Kafka topics) and feature views (groups of features with a TTL) in Python. get_historical_features performs point-in-time joins against the offline store (BigQuery, Snowflake, Redshift, Spark, files). materialize loads the latest values into the online store (Redis, DynamoDB, Bigtable, and others). get_online_features serves lookups. Feast mostly orchestrates storage and retrieval; heavy transformations typically run in your own pipelines.
  • Tecton is a commercial feature platform founded by engineers who built Uber's Michelangelo ML platform. It manages the transformations too: batch, streaming and on-demand feature definitions, compiled to pipelines it runs, with monitoring, backfills and a managed online store.
  • Other options: Hopsworks; the cloud stores (SageMaker Feature Store, Vertex AI Feature Store, Databricks Feature Store); or a homegrown "warehouse plus Redis plus shared library" setup, which many companies run successfully at moderate scale.

Training-serving skew#

Training-serving skew is any difference between the data a model was trained on and the data it receives in production. It's dangerous because nothing crashes: the model just makes worse predictions, and the only symptom is a business metric that underperforms offline expectations.

Sources of skew:

  • Code skew. The same feature is implemented twice, in SQL for training and in service code for serving. The two differ in edge cases: time zones, null handling, rounding, deduplication, bot filtering, window boundaries (last 7 calendar days vs last 168 hours).
  • Data or time skew. Training sees values computed with complete, late-arriving data. Serving sees values computed in real time before all events arrived. Or training used values that wouldn't have been available yet (the leakage above).
  • Freshness skew. Training assumed a feature updated every minute, but the online pipeline lags by an hour during peak.
  • Distribution skew. The training sample differs from production traffic: it was sampled from a different time period, excluded new users, or was biased by the old model's choices.
  • Preprocessing skew. A tokeniser, vocabulary, normalisation constant or category mapping was updated in one place but not the other.
  • Feedback skew. The model changes what users see, so production traffic shifts away from the training distribution as soon as the model launches.

Defences, in order of effectiveness:

  1. Log features at serving time, and train on the logs. Record the exact feature vector the model saw for each prediction, then join outcomes to those logged vectors. This eliminates code and freshness skew for future training, because training uses serving's own numbers. Many large-scale ranking systems work this way. The cost is storage, and the fact that a newly added feature has no logged history until it has been logging for a while (or until it's backfilled, reintroducing some skew risk).
  2. One definition, two executions. Define each feature once in a feature store or shared library and compile it for both batch and online.
  3. Point-in-time joins with availability timestamps for anything built offline.
  4. Skew monitoring. Sample production requests, recompute their features through the offline pipeline, and compare value by value. Alert when the mismatch rate or distribution distance crosses a threshold.
  5. Package preprocessing with the model. Ship tokenisers, vocabularies and normalisers inside the model artefact so they can't drift apart.
  6. Shadow-test new models on live traffic before they make decisions (see rollout, below).

Model registry and versioning#

A model registry is the system of record for trained models, playing the role an artefact repository plays for code. Each model version records:

  • The artefact itself: weights and serialised graph, plus the preprocessing it needs.
  • Lineage: the training code commit, the training data snapshot or query and time range, the feature definitions and versions, the hyperparameters, and the random seeds.
  • Evaluation results: overall metrics, per-slice metrics, calibration plots, comparison to the current production model.
  • Signature: the expected input features (names, types, shapes) and outputs, so serving can reject a model that expects a feature the online store doesn't provide.
  • Stage and approvals: candidate, staging, production, archived, and who approved each promotion.
  • Operational metadata: size, latency on reference hardware, and required runtime versions.

Why it matters:

  • Reproducibility. "Which model scored this loan application last April, and why?" is a regulatory question in credit and insurance. The registry plus prediction logs answers it.
  • Rollback. If the new model misbehaves, re-pointing the serving alias to the previous version takes seconds, because the old artefact and its exact dependencies are still there.
  • Gates. Promotion can be automated with checks: offline metrics no worse than production on every key slice, latency within budget, signature compatible, fairness checks passed.
  • Governance. Model cards (intended use, limitations), owners, and which product surfaces use which model.

Tools. The MLflow Model Registry, the SageMaker and Vertex AI registries, Weights & Biases artefacts, or a homegrown registry using object storage for artefacts plus a metadata database (Object Storage and Blob Storage).

Versioning everything. A model's behaviour depends on code + data + features + configuration, so all four need versions:

  • Code in git;
  • Data through immutable snapshots, table versions (Delta Lake and Iceberg time travel) or tools such as DVC;
  • Features through versioned definitions, so a semantic change creates spend_30d_v2 instead of silently changing spend_30d;
  • Configuration through thresholds and business rules in reviewed config.

Serving resolves an alias ("fraud-model@production") to a concrete version, so deploys and rollbacks are pointer flips.

Shadow, canary and A/B model rollout#

A new model is risky code that can't be fully verified offline. Offline metrics are computed on logged data shaped by the old model, and they don't capture interactions with the live product. So models roll out in stages:

Shadow deployment. The new model receives a copy of production requests and makes predictions, but its outputs are only logged, never used.

  • What it validates: the model loads, handles real inputs (missing features, odd values), meets latency at production load, and produces sane score distributions. You can also compare its decisions with the current model's: "it would have blocked 3× more transactions" is something you want to know before it blocks them.
  • What it can't validate: user response, because users never see its output.
  • Cost: roughly double the inference compute during the shadow period (CI/CD and Deployment Strategies).

Canary. A small slice of real traffic (1–5%) is served by the new model, watching guardrail metrics: error rate, latency, crash rate, and obvious business guardrails such as revenue, complaints and block rate. It catches operational disasters early with limited blast radius. It isn't a statistically powered experiment.

A/B test (online experiment). Users are randomly assigned to the control model or the treatment model, usually by hashing a stable user ID so each user stays in one group. The test measures the business metric the model exists to move (watch time, conversion, fraud losses) plus guardrails.

  • Why online tests are the final word. Offline metrics (AUC, NDCG) often correlate weakly with business outcomes. A model with better AUC can lose an A/B test, because offline evaluation can't see how users react to a changed experience.
  • Statistics. Decide the metric, the minimum detectable effect and the sample size before starting. Run for whole weeks to cover weekly cycles. Avoid peeking and stopping early on a lucky day, unless you use sequential testing methods designed for it. Watch for novelty effects. The Design an A/B Testing and Experimentation Platform case study covers assignment, logging and analysis in depth.
  • Interleaving, for ranking. Instead of splitting users, blend results from both rankers into one list for each user and see which ranker's items get clicked. Interleaving needs far less traffic to detect a preference than a user-split A/B test, and is often used to pre-screen ranking candidates before a full A/B test.
  • Multi-armed bandits shift traffic toward the better variant during the test. That's useful when the cost of showing a worse variant is high or there are many variants, at the price of less clean measurement.

Rollback must be instant and must not depend on retraining: keep the previous version deployed and warm, and flip the alias. Also keep non-ML fallbacks (rules, popularity) for when every model is unavailable.

Drift and model monitoring#

Ordinary services fail loudly. Models usually degrade quietly. Monitoring has four layers:

  1. System health. Latency percentiles, error rates, throughput, GPU and CPU utilisation, feature store lookup latency and miss rate (Observability: Logs, Metrics and Traces).
  2. Data quality and data drift. Changes in the input features' distributions compared with training or a recent baseline. Watch for new categorical values, rising null rates, shifted means, a feature that suddenly becomes constant (a broken upstream pipeline), or schema changes.
  3. Prediction drift. Changes in the output distribution: the share of transactions flagged, the average predicted click rate, the mix of recommended categories. It's available immediately, without labels, which makes it the fastest model-level signal.
  4. Performance (concept drift). Accuracy against ground truth once labels arrive: AUC, calibration (predicted 5% vs observed 5%), precision at the operating threshold, business KPIs. It's the most meaningful signal and the slowest, gated by label delay.

Kinds of drift:

  • Covariate shift (data drift). The input distribution changes, but the relationship between inputs and outcome stays the same: more mobile users, a new country launch.
  • Concept drift. The relationship itself changes: fraudsters adapt, a pandemic changes what "normal" spending looks like, a new competitor changes price sensitivity. Retraining on recent data is the main fix.
  • Label shift (prior shift). The base rate changes: the fraud rate doubles during a holiday season.
  • Upstream changes. These aren't drift at all, but bugs: a renamed field, a unit change (seconds to milliseconds), a logging change. They show up as sudden, step-shaped drift and are the most common cause of alerts.

Detecting drift statistically. Compare a recent window with a reference window, per feature:

  • Population Stability Index (PSI) over binned values. A common rule of thumb reads below 0.1 as stable, 0.1–0.25 as moderate shift, and above 0.25 as significant.
  • Kolmogorov–Smirnov tests for continuous features.
  • Chi-squared tests or Jensen–Shannon distance for categorical features.

With hundreds of features, some will drift by chance or harmlessly. So prioritise by feature importance, and alert on drift in important features or in predictions, not on every wiggle. The Deep Dive below covers the arithmetic.

Responses.

  • Scheduled retraining handles slow drift.
  • Triggered retraining fires when drift or performance metrics cross thresholds.
  • Rollback applies if a new model caused the change.
  • Feature quarantine means falling back to defaults if an upstream feature is broken.
  • Human review queues handle high-stakes decisions while the model is suspect.

Feedback loops need special care: a recommender that only shows popular items makes them more popular. Monitor diversity and coverage, and keep an exploration slice.

Two-stage recommenders: candidate generation, ranking and embeddings#

Recommendation, search ranking, ads and feeds share one problem shape. Millions or billions of items, one user, and a few hundred milliseconds to pick the best 10–50. Scoring every item with a rich model is impossible: 100 million items × 1 µs each is 100 seconds per request. So systems use a funnel: cheap stages narrow the set, expensive stages refine it.

Stage 1: candidate generation (retrieval). The goal is high recall cheaply. Several candidate sources run in parallel, each returning a few hundred items:

  • Embedding retrieval. A model maps users and items into the same vector space, so that "user likes item" corresponds to a high dot product (or cosine similarity). Item vectors are precomputed and loaded into an approximate nearest-neighbour (ANN) index such as HNSW, IVF or ScaNN. At request time, compute the user vector and fetch the top few hundred neighbours in a few milliseconds (Vector Databases and Similarity Search).
  • Collaborative signals. "Users who engaged with X also engaged with Y" (item-to-item co-occurrence), or the user's follow graph.
  • Content-based sources. Items similar in text, image or category to what the user engaged with. These matter for cold-start items that have no engagement yet.
  • Heuristics. Trending items, fresh items, popular items in the user's region, editorial picks.

Several sources keep the set diverse and robust: if one breaks, the others still fill the page.

Embeddings in more depth. An embedding is a dense vector, typically 32–256 floats, that represents an entity so that similar entities sit close together.

  • Learning them. Embeddings are learned from interactions (matrix factorisation; the two-tower models below; word2vec-style training on sequences of items in sessions, as Airbnb described for listings in "Real-time Personalization using Embeddings for Search Ranking at Airbnb", Grbovic and Cheng, KDD 2018) or from content (text and image encoders).
  • The two-tower model has a user tower (user features and recent history → vector) and an item tower (item features → vector), trained so engaged pairs score higher than random or in-batch negative pairs. The towers interact only through the final dot product, so item vectors can be precomputed and indexed, and only the user tower runs per request. That separation is exactly what makes ANN retrieval possible.
  • Cost of the separation. The model can't express fine-grained interactions between specific user and item features, which is why a ranker follows.
  • Freshness. Item embeddings for new items are computed when the item is created (from content features) and inserted into the index, which must support incremental updates. User vectors can be computed per request from recent activity, so the user's latest clicks move their vector immediately.

Stage 2: ranking. Score the few hundred to few thousand candidates precisely.

  • The ranker is a heavier model (gradient-boosted trees, or deep networks like Wide & Deep (Cheng et al., 2016) or DCN-style cross networks) using rich cross features: user-item affinity, the user's history with this creator, item freshness, context, and the retrieval scores themselves.
  • Multi-task output. Modern rankers predict several outcomes at once (click, like, share, long watch, hide, report) and combine them with a weighted formula that encodes product goals. Changing those weights is a product decision, tested with A/B experiments.
  • Light and heavy rankers. Large systems add a light ranker between retrieval and the heavy ranker, so the heavy model only sees a few hundred items.

Stage 3: re-ranking and policy. Adjust the final list for things a pointwise score can't see:

  • Diversity: don't show five videos from the same creator in a row;
  • Freshness and fatigue: don't repeat what was just shown;
  • Business and policy rules: content policy, sponsored slots, regional restrictions;
  • Exploration: a few items chosen to learn about new content or new interests.

Two published examples:

  • YouTube's two-stage design was described in "Deep Neural Networks for YouTube Recommendations" (Covington, Adams and Sargin, RecSys 2016). A candidate-generation network narrows millions of videos to hundreds, then a ranking network scores them with richer features, trained to predict expected watch time rather than clicks, so clickbait doesn't win.

  • Twitter's For You timeline, described when Twitter open-sourced the code in March 2023, runs the same funnel:

    • candidate sourcing pulls about 1,500 candidate tweets from a pool of hundreds of millions, on average roughly half from accounts the user follows and half from outside their network, using graph and embedding sources;
    • a neural ranker of roughly 48 million parameters scores them;
    • heuristics and filters then balance and clean the timeline.

    Twitter reported the pipeline running about 5 billion times a day, completing in under 1.5 seconds on average (Design a Recommendation System (Twitter For You)).

Latency budget for a 200 ms feed request:

StageTypical budget
Fetch user features and compute user embedding10–20 ms
Candidate sources in parallel, including ANN20–40 ms
Merge, dedupe, filter (Bloom filter of seen items)5–10 ms
Feature hydration for candidates10–30 ms
Light ranker over thousands10–20 ms
Heavy ranker over hundreds (GPU, batched)20–50 ms
Re-ranking, assembly, response10–20 ms

Parallelism and caching are what make the budget work. Candidate sources run concurrently. Item features are cached in memory near the ranker. "Already seen" checks use a per-user Bloom filter (Probabilistic Data Structures for Big Data).

Cold start.

  • New users get popularity and context-based recommendations, onboarding choices (pick topics), and fast adaptation: session features plus a user tower that uses recent clicks, not only a long-term ID embedding.
  • New items get content-based embeddings and a guaranteed share of exploration impressions so the system can learn about them.

The ML system design interview framework#

ML design interviews (at Meta, Google, Amazon, TikTok, Netflix and many others, often as a separate loop for ML engineers) follow a recognisable structure. A good answer spends most of its time on framing, data, features and evaluation, and treats model architecture as one step among several.

StepTime (45 min)What to cover
1. Clarify and frame5–7 minBusiness goal, users, scale, the exact prediction target, how the output is used, constraints (latency, freshness, privacy)
2. Metrics3–5 minOffline metrics (AUC, NDCG, recall@K), online metrics (CTR, watch time, revenue), guardrails (latency, diversity, complaints)
3. Data and labels5–7 minSources, label definition, label delay, positive and negative sampling, biases, data volume
4. Features5–7 minUser, item, context, cross and real-time features; embeddings; freshness and computation mode
5. Model5–7 minBaseline first, then the real model; for ranking, the multi-stage funnel; loss function and training setup
6. Serving architecture7–10 minBatch, online or streaming; feature store; candidate retrieval and ANN; latency budget; caching; fallbacks
7. Evaluation and rollout3–5 minTime-based splits, offline evaluation, shadow, canary, A/B test design
8. Monitoring and iteration3–5 minDrift, delayed labels, retraining cadence, feedback loops, fairness, failure modes

How the framework maps to a prompt. Take "Design a system to recommend videos on a home feed".

  1. Framing. The target is probability of a meaningful watch, more than 50% completion or 30 seconds. Raw clicks reward clickbait.
  2. Metrics. Offline: recall@500 for retrieval, NDCG@20 for ranking. Online: watch time per session and day-7 retention, with guardrails on diversity, report rate and latency.
  3. Data and labels. Impression logs joined with watch events, labelled within a 24-hour window, with negatives from shown-but-not-watched impressions plus sampled negatives for retrieval.
  4. Features. User history and embeddings, item metadata and content embeddings, creator stats, context, and session features from a streaming pipeline.
  5. Model. A two-tower retrieval model with ANN, plus a multi-task heavy ranker.
  6. Serving. Online ranking, a feature store with a Redis online tier, precomputed item embeddings refreshed as items are created, and a popularity fallback.
  7. Evaluation and rollout. Time-split evaluation, shadow, canary, then a two-week A/B test.
  8. Monitoring. Prediction drift, calibration, coverage of new creators, and a daily retrain plus fresh embeddings.

What separates levels. Mid-level candidates produce a correct pipeline. Senior candidates justify every choice with the data and the product goal, and spot leakage, skew and bias risks unprompted. Staff candidates also discuss platform concerns:

  • feature reuse across teams;
  • experimentation velocity;
  • the cost of GPU serving;
  • long-term effects such as feedback loops and creator ecosystem health;
  • how to organise the system so many teams can iterate safely.

See Interview Expectations by Level and How to Prepare.

When to Use It#

Use a full ML system (learned models, feature pipelines, online serving, monitoring) when:

  • The decision is made many times, and small improvements compound. Ranking a feed served billions of times a day, pricing millions of rides, or screening every payment. A 1% gain is worth a platform.
  • Rules can't keep up. The signal is spread across hundreds of weak features and their interactions (fraud, relevance, ETA), or the patterns change faster than humans can rewrite rules.
  • You have the data and labels. Enough historical outcomes (often hundreds of thousands to millions of labelled examples for tabular problems) and a way to keep collecting them.
  • Personalisation matters. Different users should see different results, and the catalogue is too big to curate by hand.
  • Fresh context changes the answer. Session behaviour, location or the last few events materially change the best prediction, which justifies online or streaming serving.

Use a feature store specifically when:

  • several models or teams reuse the same features;
  • you need both training history and low-latency serving for the same features;
  • point-in-time correctness has bitten you (or will: fraud, credit, ads);
  • you need streaming features with backfills, governance or lineage.

Use a two-stage recommender when the item catalogue is too large to score fully per request: tens of thousands of items and up.

When NOT to Use It#

Pick something else instead when:

  • A rule or heuristic is good enough. "Most popular in your country", "sort by recency" or "block cards with more than 10 attempts in 5 minutes" may capture most of the value at a fraction of the cost. Ship the heuristic first and use it as the baseline.
  • There's no reliable label. If you can't define and observe success, you can't train or evaluate. Fix instrumentation first.
  • The decision is rare or very high-stakes and must be explainable. A handful of decisions a day, or legal requirements for clear reasons, may call for rules, scorecards or humans, perhaps assisted by a simple interpretable model.
  • One model, one team, batch scoring. A daily churn score written to a table doesn't need a feature store, an online store or a serving fleet. A scheduled job and a warehouse table are fine.
  • Small catalogues. If you have 200 products, score them all with one model, with no retrieval stage or ANN index.
  • Real-time isn't needed. Don't build streaming features or online inference if predictions only change daily and nobody looks at them more often. Batch inference is cheaper and simpler.
  • A pretrained model or API already solves it. Text classification, translation or summarisation may be better served by an LLM or vendor API than by a custom training pipeline (Designing LLM and AI-Powered Systems).

How to Implement It#

A practical build order for a team's first production ML system:

  1. Frame the problem and baseline it. Write down the prediction target, the decision it drives, the offline and online metrics, and the current non-ML baseline. Agree on the latency and freshness budget.
  2. Instrument and log. Make sure impressions, actions, outcomes and the context of each decision are logged with stable IDs and accurate timestamps. Log what was shown, not just what was clicked.
  3. Build the training set with point-in-time joins. Define features with event and availability timestamps. Build labels with an explicit label window. Join them as-of. Split by time.
  4. Train a simple model, then a better one. Start with logistic regression or gradient-boosted trees, compare against the baseline on slices, and register the artefact with lineage and metrics.
  5. Pick the serving mode and put features online. Batch, if staleness is acceptable. Otherwise, materialise features to an online store, deploy a model server with autoscaling and fallbacks, and log served features and predictions.
  6. Roll out and monitor. Shadow, canary, then A/B test. Dashboards and alerts for latency, feature freshness, data drift, prediction drift and delayed accuracy. Schedule retraining and automate the promotion gates.

The point-in-time join is the piece most often done wrong. A compact SQL version for a fraud training set:

-- Attach to each label the latest feature row that was AVAILABLE
-- at or before the label time, and no older than the feature TTL.
WITH matched AS (
  SELECT
    l.card_id,
    l.label_time,
    l.is_fraud,
    f.attempts_10m,
    f.spend_30d,
    ROW_NUMBER() OVER (
      PARTITION BY l.card_id, l.label_time
      ORDER BY f.available_at DESC
    ) AS rn
  FROM labels l
  LEFT JOIN card_features f
    ON  f.card_id = l.card_id
    AND f.available_at <= l.label_time                      -- no future values
    AND f.available_at >  l.label_time - INTERVAL '2 days'  -- feature TTL
)
SELECT
  card_id,
  label_time,
  is_fraud,
  COALESCE(attempts_10m, 0) AS attempts_10m,  -- same default as serving
  spend_30d                                   -- NULL means missing, as online
FROM matched
WHERE rn = 1;

Three details matter:

  • Join on available_at, not just the event time. This mirrors what serving could see.
  • The TTL bound mirrors the online store's expiry.
  • Defaults for missing values must match the serving code exactly.

Engines with native as-of joins (DuckDB, ClickHouse, Snowflake, kdb+, Spark through libraries) do this more efficiently, and feature stores generate equivalent queries for you.

TechnologyFits when
FeastOpen-source feature store over your existing warehouse and Redis or DynamoDB; you run the transforms yourself
Tecton, Hopsworks, Databricks / SageMaker / Vertex AI feature storesManaged feature platform with batch, streaming and on-demand transforms, backfills and monitoring
Redis, DynamoDB, Cassandra, BigtableOnline feature store: millisecond key lookups at high QPS
BigQuery, Snowflake, Redshift, Delta Lake / Iceberg on object storageOffline store: timestamped history, point-in-time joins, training scans
Kafka + Flink or Spark Structured StreamingStreaming features (windowed counts, session signals) and streaming inference
Spark, Ray, DaskLarge-scale feature backfills, batch inference, distributed training data prep
XGBoost, LightGBM, CatBoostTabular problems: fraud, risk, ETA, churn; fast CPU inference
PyTorch, TensorFlowDeep models: embeddings, two-tower retrieval, multi-task rankers, sequences
NVIDIA Triton, TorchServe, TF Serving, KServe, Ray Serve, ONNX RuntimeOnline model serving with batching, GPU support, versioned deployments
Faiss, ScaNN, HNSW libraries, Milvus, Pinecone, OpenSearch k-NNANN retrieval for embeddings in candidate generation
MLflow, Weights & Biases, SageMaker / Vertex AI registriesExperiment tracking and the model registry with lineage and stages
Airflow, Kubeflow Pipelines, Metaflow, DagsterOrchestrating feature, training, evaluation and deployment pipelines
Evidently, WhyLabs, cloud model monitorsData and prediction drift, data quality and performance monitoring

Trade-offs#

OptionProsConsPick when
Batch inferenceCheapest per prediction; trivial lookup at request time; heavy models OK; predictions inspectable before useStale; no request context; wasted work on inactive entities; cold startPredictions change slowly; daily emails, churn scores, nightly candidate lists
Online inferenceFresh context; covers new users and items; computes only what's neededIn the critical path; latency and availability burden; cost scales with trafficSearch, feed ranking, fraud at payment, pricing, ETA
Streaming inferenceSeconds-fresh decisions off the request path; feeds online featuresStateful stream ops, late data, reprocessing complexityEvent-driven detection, moderation queues, trending, fresh features
Feature store (Feast-style, orchestration)Point-in-time joins, consistent serving, reuse, light to adoptYou still own transformation pipelines; another system to runSeveral models share features; warehouse plus Redis already exist
Feature platform (Tecton-style, managed transforms)Batch, stream and on-demand from one definition; backfills; monitoringCost, vendor lock-in, learning curveMany teams, many real-time features, little platform staff
No feature store (shared library + warehouse + cache)Simplest; no new infrastructureSkew risk grows with teams; ad hoc point-in-time logicOne or two models, small team, early stage
Logged features for trainingEliminates code and freshness skewNew features lack history; storage costHigh-traffic ranking with frequent retraining
Gradient-boosted treesStrong on tabular data, fast CPU inference, robustWeak with raw IDs, text, images, sequencesFraud, risk, ETA, churn, the first serious model
Deep modelsLearn embeddings and interactions; handle sparse IDs and contentNeed more data, GPUs, tuning; harder to debugLarge-scale recommendations, search, content understanding
Two-stage retrieval + rankingScales to huge catalogues within latency budgetsRecall ceiling set by retrieval; more systems to tuneCatalogues from tens of thousands to billions of items
Score everything with one modelSimple, no recall lossInfeasible beyond small cataloguesA few hundred items, or offline batch
Frequent retrainingTracks drift and new itemsCompute cost; more rollout risk; more monitoringAds, feeds, fraud: fast-changing domains

Common Pitfalls#

  • Leakage in the training set. Joining current feature values to past labels, random splits on time-dependent data, or features derived from the label itself ("number of refunds" when predicting refunds). The symptom is offline metrics that are too good to be true.
  • Two implementations of every feature. Separate SQL and service code drift apart. Use one definition or train on logged features.
  • Optimising the wrong target. Clicks reward clickbait. Short-term revenue can hurt retention. Choose labels and multi-objective weights that reflect long-term value, and back them with guardrail metrics.
  • Trusting offline metrics alone. A better AUC doesn't guarantee a better product. Always A/B test meaningful launches.
  • Ignoring label delay. You evaluate a fraud model on last week's transactions before their chargebacks have arrived, and it looks perfect.
  • No fallback. The feature store or model server times out and the page breaks. Serve a cached or popularity result instead.
  • Feature fetch fan-out. Fetching hundreds of item features per request from a remote store, one key at a time. Batch, co-locate, and cache item features in the ranker.
  • Silent upstream breakage. A pipeline starts writing zeros or nulls. Add data quality checks and alert on sudden distribution steps.
  • Feedback loops and popularity bias. The model learns only from what it showed, so diversity and new-item coverage decay. Keep exploration and monitor coverage.
  • Unversioned data and features. You can't reproduce or explain a model when the training data or feature semantics changed underneath it.
  • Over-building. A real-time feature platform and GPU fleet for a model that's scored once a day for 10,000 users.

Real-World Examples#

  • Uber Michelangelo. Uber's internal ML platform, described publicly in 2017, covered the whole lifecycle: data management with a shared feature store, training, evaluation, deployment, and online and offline prediction with monitoring. Its feature store let teams share and reuse curated features, for example in Uber Eats delivery-time estimation. Engineers from that team later founded Tecton.
  • Feast at Gojek. Feast was created at Gojek together with Google Cloud to serve features consistently to both training and online models, and became one of the most widely used open-source feature stores.
  • YouTube recommendations. Covington, Adams and Sargin's 2016 paper is the canonical description of two-stage retrieval and ranking at scale. It also showed the value of optimising for expected watch time rather than click-through.
  • Twitter For You (2023). The open-sourced pipeline: candidate sourcing of about 1,500 tweets from in-network and out-of-network sources (graph and embedding based), a neural heavy ranker of roughly 48 M parameters, then heuristics and filters. It runs billions of times daily, in about 1.5 seconds on average.
  • Facebook ad click prediction. "Practical Lessons from Predicting Clicks on Ads at Facebook" (He et al., 2014) combined boosted decision trees, used as feature transformers, with logistic regression. Among other things, it found that data freshness mattered: models retrained more frequently predicted better. That's an early, clear case for fast retraining pipelines.
  • Netflix. Gomez-Uribe and Hunt's 2015 article "The Netflix Recommender System: Algorithms, Business Value, and Innovation" described a homepage built from many personalised rows, each ranked by algorithms. It reported that recommendations influence the large majority (about 80%) of hours streamed, and stressed online A/B testing as the final arbiter of algorithm changes.
  • Airbnb listing embeddings. Grbovic and Cheng (KDD 2018) learned listing embeddings from booking-session sequences and used them for real-time personalisation in search ranking, using in-session signals to adapt results as the user browsed.

Case studies that use this pattern#

In the Interview#

Common follow-ups:

  • How do you make sure training and serving features match? One feature definition executed in both paths, point-in-time joins using availability timestamps, logging served features and training on them, and a skew monitor that recomputes sampled online features offline and compares them.
  • Your offline AUC improved but the A/B test was flat. Why? Offline data is biased by the old model's impressions, the metric may not match the business goal, gains may sit in irrelevant regions of the score distribution (AUC ignores the operating point), or there may be leakage. Check calibration, slice results, the label definition, and whether the change affects the top positions users actually see.
  • How do you handle a new item with no engagement? Content-based embeddings from its text and media, insertion into the ANN index at creation, a guaranteed exploration budget of impressions, and fast feedback through streaming features so engagement updates its ranking within minutes.
  • The model's precision dropped this week. What do you check? Upstream data quality first (nulls, schema, units), then feature drift on important features, then prediction drift, then whether labels are complete yet, then concept drift (a new fraud pattern). Roll back if a recent model or feature change lines up with the drop.
  • How would you serve 50,000 ranking requests per second within 100 ms? Parallel candidate sources with ANN, in-memory item feature caches near the ranker, a light ranker to cut candidates, a GPU heavy ranker with dynamic batching, precomputed user embeddings, timeouts with fallbacks per source, and capacity planned at 50–70% utilisation.
Deep Dive: Point-in-time joins, windowed features and freshness at scaleShow

The as-of join as an algorithm. Let L be the label table and F the feature table, both keyed by entity and timestamp. The naive SQL above uses a range join plus a window function. That's correct, but on billions of rows it can explode: every label matches every feature row in the TTL window before the ranking discards most of them.

Scalable implementations use a sort-merge strategy instead:

  1. Partition both tables by entity ID (hash) so each worker sees all rows for its entities.
  2. Sort each partition by (entity, timestamp).
  3. Merge-scan both sorted streams together. Walk them in timestamp order, keep the "latest feature row seen so far" per entity, and emit it when a label row arrives (if it's within the TTL).

That's O((|L| + |F|) log n) for the sort and linear for the scan, with no blow-up. Engines with native ASOF JOIN do exactly this. Spark implementations union the two tables with a type marker, sort within partitions, and carry the last value forward with a window function such as last(value, ignoreNulls).

Two practical problems:

  • Skewed entities. A merchant with 50 million transactions puts one enormous partition on one worker. Mitigations: salt hot keys across sub-partitions by time range, or join per time bucket.
  • Many feature views. A training set with 30 feature views is 30 as-of joins. Feature stores run them as separate merges keyed on the label table and then combine columns, rather than one giant join.

Windowed aggregates without recomputing the world.

  • The problem. A feature like "transactions in the last 30 days" must be correct at every label timestamp in training, and fresh at every request in serving. Recomputing a 30-day sum from raw events for each request is far too slow.
  • The tiling trick. The standard technique is pre-aggregated tiles. Store partial aggregates per entity per fixed bucket (per minute, per hour, per day). Answer "last 30 days" by summing the relevant tiles plus a partial head and tail.
    • Tile sizes trade precision for cost. 30 daily tiles plus 24 hourly tiles for the most recent day gives near-exact windows with about 54 reads, or a single read if the tiles are pre-merged into the online value.
    • Not every aggregate tiles. Sums, counts, min and max combine exactly. Averages combine as (sum, count) pairs. Distinct counts combine approximately with HyperLogLog sketches. Percentiles combine approximately with t-digest or similar sketches.
  • Where the tiles live. A streaming job (Flink) maintains the latest tiles in its keyed state and writes the current window value to the online store. The same tiles are written to the offline store with timestamps, so training reconstructs the window as of any moment. Backfills compute historical tiles with the batch engine, using the same tile logic.

Late events and watermarks.

  • Out-of-order arrival. Mobile clients go offline, and partitions lag. A stream processor uses watermarks, a moving estimate of "event time up to which we've seen everything", to decide when a window is complete. Events later than the allowed lateness are dropped or sent to a correction path (Apache Flink and Stream Processing).
  • Effect on training. Serving computed the feature before late events arrived, while a batch backfill computes it after. A strict feature store reproduces the serving view (availability time), or trains on logged features, so the model learns from the numbers it will actually get.

Freshness budgets in numbers. Suppose a fraud model uses three features:

  • attempts_10m comes from a streaming pipeline with end-to-end lag of p50 2 s and p99 15 s.
  • spend_30d is updated hourly.
  • merchant_risk is updated daily.

At serving, the online store holds each with an updated_at. The model is trained knowing these lags, so it treats a 10-minute count that's 15 seconds behind as normal.

If the streaming job stalls for 20 minutes, attempts_10m becomes misleading, worse than missing, because "0 attempts" looks like safe behaviour. So serving should check freshness and substitute "missing" (or a default the model was trained to handle) when a value exceeds its freshness SLO. Monitor freshness per feature like any other SLI.

Online store sizing and access patterns.

  • Lookup shape. Most feature lookups are multi-get by entity key: one user, or 500 items. Store features for an entity as one row or hash (a single key holding a packed vector), not one key per feature. That way 50 features cost one lookup.
  • Worked example. 300 M users × 100 features × 8 bytes ≈ 240 GB raw, about 0.5–0.7 TB with key overhead and replication. That's a modest Redis Cluster or DynamoDB table.
  • Item features for ranking are hot and comparatively few (10 M items × 2 KB = 20 GB), so ranker hosts often keep them in local memory, refreshed from the store every few minutes. That removes millions of remote lookups per second.
Deep Dive: The mathematics of retrieval and rankingShow

Training a two-tower retriever.

  • The scoring function. Let u = f(user) and v = g(item) be the two tower outputs, and let the score be s(u, v) = u · v (often after L2-normalising, which makes it cosine similarity, scaled by a temperature).
  • Training objective. For each positive pair (user, engaged item), maximise its score relative to negatives with a softmax loss: L = −log( exp(s⁺) / (exp(s⁺) + Σ exp(s⁻)) ).
  • In-batch negatives. Computing the softmax over the full catalogue is too expensive. Common practice uses in-batch negatives: the other items in the same training batch serve as negatives for each user. With batch size B, each example gets B − 1 negatives for free.
  • The bias, and its correction. In-batch negatives are sampled roughly in proportion to item popularity, since popular items appear in more batches. That over-penalises popular items. "Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations" (Yi et al., Google, RecSys 2019) corrects it by subtracting log(sampling probability) from each logit, the logQ correction, estimating item frequencies in a streaming fashion.
  • Hard negatives. Items the model currently scores high but the user didn't engage with sharpen the boundary. Too many hard negatives, especially false negatives the user would have liked, hurt.

Approximate nearest-neighbour search and the recall ceiling.

  • Retrieval sets a recall ceiling. If the relevant item isn't among the retrieved candidates, no ranker can recover it.
  • Two sources of loss multiply. The model's recall@K (are relevant items near the user vector?) and the ANN index's recall relative to exact search (does the index find the true nearest neighbours?). HNSW at typical settings reaches 95–99% recall of exact top-K in milliseconds, and more probes or higher ef buy recall with latency.
  • Worked example. If the model's recall@500 is 60% and the index recall is 97%, the effective candidate recall is about 58%. Adding a second, uncorrelated source (co-engagement) often lifts union recall more than tuning either alone, which is why multi-source retrieval is standard.

Ranking metrics.

  • AUC is the probability that a random positive scores above a random negative. It's threshold-free, insensitive to calibration, and blind to position.
  • Log loss rewards calibrated probabilities. Use it when the scores feed downstream arithmetic (auctions, expected value).
  • NDCG@K discounts each relevant result by its position: DCG = Σ rel_i / log₂(i + 1), normalised by the ideal ordering's DCG. Worked example: a relevant item at rank 1 contributes 1.0, at rank 3 contributes 0.5, at rank 10 about 0.29. That matches the intuition that the top of the list matters most.
  • Recall@K suits retrieval stages. MAP and MRR suit search with a few relevant results.

Calibration and negative downsampling.

  • Downsampling. Click data is extremely imbalanced (CTR of about 1–5%), so training often keeps all positives and a fraction w of negatives. A model trained this way predicts inflated probabilities p.
  • Recalibration. He et al. (Facebook, 2014) gave the correction q = p / (p + (1 − p) / w).
    • Worked example: with w = 0.1 and a model output p = 0.2, q = 0.2 / (0.2 + 0.8 / 0.1) = 0.2 / 8.2 ≈ 0.024.
  • Why it matters in ads. The expected value of showing an ad is roughly bid × P(click), so a 2× calibration error is a 2× pricing error. Calibration is monitored continuously: predicted CTR vs observed CTR per slice. Platt scaling or isotonic regression on recent data fixes drift in calibration.

Multi-task ranking and the value formula.

  • The value formula. A heavy ranker predicts several probabilities per candidate (click, like, share, long-watch, negative feedback), and the final score is a weighted combination. For example: score = P(long watch) + 0.5·P(share) + 0.2·P(like) − 3·P(hide).
  • Who sets the weights. They encode product values and are tuned through experiments, not gradient descent.
  • Modelling. A shared bottom network with task-specific heads, or mixture-of-experts variants such as MMoE, which let tasks share some representations without negatively interfering.
  • Why multi-task beats a single click model. It resists clickbait: a click-only model rewards misleading thumbnails, while a model that also predicts long watch and hide does not.

Position bias and unbiased learning.

  • The bias. Items at the top get more clicks partly because they're at the top, so naive training data confuses relevance with position.
  • Mitigations:
    • include position as a training feature and set it to a fixed value at serving time;
    • weight examples by inverse examination propensity, estimated from randomised experiments;
    • learn a separate shallow "position tower" whose output is dropped at serving.
  • Off-policy evaluation. Weighting logged rewards by the ratio of new to old policy probabilities lets teams estimate a new policy's value from logs before an A/B test. It's high-variance, but useful for screening.
Deep Dive: Drift statistics, label delay and experiment arithmeticShow

Population Stability Index (PSI).

  • The formula. Bin a feature using the reference distribution's quantiles (say 10 bins). For each bin with reference share r_i and current share c_i: PSI = Σ (c_i − r_i) · ln(c_i / r_i).
  • Worked example. A bin moving from 10% to 15% contributes 0.05 × ln(1.5) ≈ 0.020. A bin moving from 10% to 5% contributes (−0.05) × ln(0.5) ≈ 0.035. Shifts that size across several bins quickly reach the 0.1 "moderate" level.
  • Interpreting it. PSI is symmetric-ish and easy to explain. Like any distance, it flags change, not harm, so pair it with feature importance and performance metrics.
  • Practical details. Add a small epsilon for empty bins. Use the same binning over time. Watch categorical features for brand-new values, which binning hides unless an "other" bin is tracked.

The KS test and why p-values mislead at scale.

  • The test. The Kolmogorov–Smirnov statistic is the maximum gap between two cumulative distributions.
  • The problem. With millions of rows, any tiny difference is "statistically significant". Production monitors therefore threshold on the effect size (the KS statistic itself, PSI, Jensen–Shannon distance) rather than the p-value, and compare against the natural day-to-day variation of each feature.

Label delay and early accuracy proxies.

  • The delay. Chargebacks can take 30–90 days. Waiting that long to notice a broken fraud model is unacceptable.
  • Early signals:
    • prediction drift, available immediately;
    • early labels such as same-day manual reviews, customer complaints and 3-D Secure failures;
    • label maturation curves. If 40% of eventual fraud is usually reported within 7 days, compare the 7-day-matured fraud rate against its historical 7-day value, not against the final rate.
  • Survivorship in labels. Blocked transactions never get labels, because you never learn whether they were really fraud. Holding out a small random sample of low-risk blocks, or using review outcomes, keeps the label set unbiased.

A/B test sample size.

  • Rule of thumb. For 80% power at a 5% significance level, the sample per variant is roughly n ≈ 16 σ² / δ², where σ² is the metric's variance and δ is the absolute effect you want to detect.
  • Worked example. Baseline CTR is 5%, so σ² = p(1 − p) ≈ 0.0475. Detecting a 1% relative lift means δ = 0.0005. Then n ≈ 16 × 0.0475 / 0.00000025 ≈ 3 million users per arm. To detect a 5% relative lift, n drops by 25×, to about 120,000 per arm.
  • The implication for ML teams. Small model improvements need large traffic or variance reduction to measure.

Variance reduction. CUPED, from "Improving the Sensitivity of Online Controlled Experiments by Utilizing Pre-Experiment Data" (Deng, Xu, Kohavi and Walker, WSDM 2013), adjusts each user's metric by their pre-experiment value. The adjusted metric is Y − θ(X − mean(X)), where θ is the regression coefficient of Y on X. That removes the variance explained by pre-existing differences between users. With a strongly correlated pre-period metric, required sample sizes can drop substantially. Interleaving for rankers achieves sensitivity gains in a different way: each user compares both rankers directly, which removes between-user variance.

Pitfalls in model experiments:

  • Network effects and interference. In marketplaces and social products, treatment users affect control users: a better ride-dispatch model takes drivers from the control group. Use cluster or geo randomisation, or switchback designs that alternate by time window.
  • Novelty and learning effects. Users react to change itself. Run long enough and look at the trend over time.
  • Sample ratio mismatch. If a 50/50 split comes out 50.6/49.4 on millions of users, assignment or logging is broken. Check it before reading any metric.
  • Multiple comparisons. Testing 20 metrics at 5% significance yields about one false win by chance. Pre-register the primary metric.

Feedback loops, formally. A deployed model changes the data distribution it will be retrained on. That's sometimes called a performative setting, and the simplest consequence is a rich-get-richer dynamic: popular items get shown, gather engagement, and become more popular. Controls:

  • an exploration share, such as ε-greedy or Thompson sampling over a slice of slots;
  • propensity logging, so future training can de-bias;
  • diversity constraints in re-ranking;
  • tracking catalogue coverage (the share of items getting any impressions) as a health metric alongside accuracy.

Key Takeaways#

  • The model is the smallest part of an ML system. Most of the work is data collection, labels, feature pipelines, serving, rollout and monitoring, and that's where most failures happen.
  • Frame first. Define the exact prediction target with its label window, the decision it drives, the non-ML baseline and both offline and online metrics, before choosing any model.
  • Pick the serving mode from freshness and context needs. Batch for slow-changing predictions, online for request-time context within tens of milliseconds, streaming for seconds-fresh event-driven decisions. Hybrids are normal.
  • A feature store pairs an offline store with an online store. The offline store holds timestamped history for training; the online store holds the latest values for millisecond serving. Point-in-time joins on availability timestamps keep the future out of training data.
  • Training-serving skew is the classic silent failure. Prevent it with one feature definition, logged serving features, packaged preprocessing and skew monitors.
  • Treat models as versioned artefacts. Keep their lineage in a registry, and roll them out like risky code: shadow, canary, then a properly powered A/B test, with instant rollback and non-ML fallbacks.
  • Monitor the whole stack. Watch system health, data quality, prediction drift and delayed accuracy. Alert on effect sizes in important features, and plan retraining around label delay and drift speed.
  • Large catalogues need a funnel. Multi-source candidate generation (two-tower embeddings with ANN, graph and heuristic sources) feeds light and heavy multi-task rankers and a re-ranking stage for diversity and policy.
  • In interviews, depth beats model trivia. Spend your time on framing, data, features, serving and evaluation, and volunteer leakage, skew, cold start and feedback loops before you're asked.