Chapter 71: ML Systems at Scale
Building production machine learning systems requires more than just training models. You need infrastructure for feature management, serving predictions at scale, continuous training, experimentation, and monitoring. This chapter covers the key components of ML systems that serve millions of predictions per second.
Feature Stores
A feature store is a centralized repository for storing, managing, and serving ML features. It solves the problem of feature inconsistency between training and serving (training/serving skew).
Online vs Offline Feature Stores
| Aspect | Online Store | Offline Store |
|---|---|---|
| Use Case | Real-time inference | Batch training |
| Latency | Low (1-10ms) | High (seconds to hours) |
| Storage | Redis, DynamoDB, Cassandra | S3, Snowflake, BigQuery, Hive |
| Data Volume | Recent/hot data only | Historical data (months/years) |
| Updates | Real-time stream processing | Batch jobs (hourly/daily) |
Feature Store Architecture
graph TB
subgraph "Feature Creation"
Raw[Raw Data Sources]
Stream[Streaming Data]
Batch[Batch Data]
end
subgraph "Feature Store"
Registry[Feature Registry
Metadata, Lineage, Schema]
Offline[Offline Store
S3/BigQuery]
Online[Online Store
Redis/DynamoDB]
end
subgraph "Consumers"
Training[Model Training]
Serving[Model Serving]
Notebook[Notebooks/Analysis]
end
Raw --> Stream
Raw --> Batch
Stream --> |Real-time pipeline| Online
Batch --> |Batch pipeline| Offline
Offline --> |Materialize hot features| Online
Registry -.-> Offline
Registry -.-> Online
Offline --> Training
Offline --> Notebook
Online --> Serving
Popular Feature Store Solutions
Feast (Open Source)
- Created by Gojek, now Linux Foundation project
- Supports multiple backends (Redis, Snowflake, BigQuery)
- Point-in-time correct feature retrieval for training
- Feature versioning and lineage tracking
Tecton (Commercial)
- Founded by Uber Michelangelo team
- Fully managed feature platform
- Real-time feature transformations
- Built-in monitoring and data quality checks
Feature Store Benefits
- Consistency: Same feature computation for training and serving
- Reusability: Share features across models and teams
- Point-in-time correctness: Prevent data leakage in training
- Monitoring: Track feature drift and data quality
- Discovery: Catalog of available features
Model Serving
Model serving is the process of making trained models available for inference. The architecture differs dramatically based on latency requirements.
Batch vs Real-Time Serving
| Aspect | Batch Serving | Real-Time Serving |
|---|---|---|
| Latency | Minutes to hours | 1-100ms |
| Use Cases | Email recommendations, nightly reports | Fraud detection, search ranking, ads |
| Architecture | Spark/Airflow jobs, write to DB | REST API, gRPC, embedded models |
| Throughput | Very high (millions of predictions) | Limited by request volume |
| Cost | Lower (scheduled compute) | Higher (always-on servers) |
| Freshness | Stale (hours old) | Fresh (real-time features) |
Real-Time Model Serving Architecture
graph LR
Client[Client Application]
LB[Load Balancer]
subgraph "Model Serving Cluster"
MS1[Model Server 1
GPU/CPU]
MS2[Model Server 2
GPU/CPU]
MS3[Model Server 3
GPU/CPU]
end
subgraph "Supporting Services"
FS[Feature Store
Online]
Cache[Prediction Cache
Redis]
Monitor[Monitoring
Prometheus]
end
Client --> LB
LB --> MS1
LB --> MS2
LB --> MS3
MS1 --> FS
MS2 --> FS
MS3 --> FS
MS1 --> Cache
MS2 --> Cache
MS3 --> Cache
MS1 --> Monitor
MS2 --> Monitor
MS3 --> Monitor
Model Serving Frameworks
TensorFlow Serving
- Protocol: gRPC (high performance) and REST
- Model versioning: Serve multiple versions simultaneously
- Batching: Automatic request batching for throughput
- Hot-swapping: Load new models without downtime
NVIDIA Triton
- Framework agnostic: TensorFlow, PyTorch, ONNX, TensorRT
- GPU optimization: Multi-GPU, multi-model on one GPU
- Dynamic batching: Combine requests for efficiency
- Model ensemble: Chain multiple models
Seldon Core / KServe (Kubernetes-native)
- Cloud-native: Deploy models as K8s resources
- Canary deployments: Gradual rollout
- Explainability: Built-in integration
- Multi-framework: Support for many ML frameworks
Optimization Techniques
- Model quantization: Reduce precision (FP32 β INT8) for 4x speedup
- Model pruning: Remove low-importance weights
- Knowledge distillation: Train small model to mimic large model
- Request batching: Process multiple requests together
- Caching: Cache predictions for common inputs
- Model compilation: TensorRT, TVM for hardware-specific optimization
Model Training Pipeline
A robust training pipeline automates the process from raw data to deployed model, ensuring reproducibility and enabling continuous improvement.
Training Pipeline Stages
graph TD
Data[1. Data Collection
Raw logs, events, databases]
Clean[2. Data Cleaning
Deduplication, outlier removal]
Features[3. Feature Engineering
Transformations, aggregations]
Split[4. Data Splitting
Train/Val/Test 70/15/15]
Train[5. Model Training
Hyperparameter tuning]
Eval[6. Model Evaluation
Metrics, validation]
Register[7. Model Registry
Version, metadata]
Deploy[8. Deployment
Canary, A/B test]
Monitor[9. Monitoring
Drift, performance]
Data --> Clean
Clean --> Features
Features --> Split
Split --> Train
Train --> Eval
Eval --> |Metrics meet threshold| Register
Eval --> |Metrics poor| Train
Register --> Deploy
Deploy --> Monitor
Monitor --> |Drift detected| Data
Key Components
1. Data Versioning
- DVC (Data Version Control): Git-like for datasets
- Delta Lake / Iceberg: Versioned data lakes
- Snapshot IDs: Track exact data used for training
2. Experiment Tracking
- MLflow: Track params, metrics, artifacts
- Weights & Biases: Visualization, collaboration
- Neptune.ai: Experiment comparison, team features
3. Hyperparameter Tuning
- Grid search: Exhaustive, expensive
- Random search: Sample parameter space
- Bayesian optimization: Efficient (Optuna, Hyperopt)
- Early stopping: Kill poor runs early
4. Distributed Training
- Data parallelism: Split data across GPUs
- Model parallelism: Split model across GPUs (large models)
- Ray Train / Horovod: Distributed frameworks
Model Evaluation Metrics
| Model Type | Metrics | Business Metric |
|---|---|---|
| Classification | Precision, Recall, F1, AUC-ROC | Fraud caught, false positive rate |
| Regression | RMSE, MAE, RΒ² | Revenue prediction accuracy |
| Ranking | NDCG, MAP, MRR | Click-through rate, engagement |
| Recommendation | Precision@K, Recall@K, Coverage | Conversion rate, user satisfaction |
A/B Testing for ML Models
A/B testing is the gold standard for evaluating model improvements in production. Offline metrics don't capture real user behavior and system interactions.
A/B Test Framework
graph TB
User[User Request]
Assign[Experiment Assignment
User ID hash]
subgraph "Control Group 50%"
ModelA[Model A
Current Production]
LogA[Log: user_id, model_a, metrics]
end
subgraph "Treatment Group 50%"
ModelB[Model B
New Candidate]
LogB[Log: user_id, model_b, metrics]
end
Analysis[Statistical Analysis
T-test, Confidence Interval]
Decision[Launch Decision
Rollout or Rollback]
User --> Assign
Assign --> |50%| ModelA
Assign --> |50%| ModelB
ModelA --> LogA
ModelB --> LogB
LogA --> Analysis
LogB --> Analysis
Analysis --> Decision
Key Concepts
Randomization
- User-level: Hash user_id β group (consistent assignment)
- Request-level: Each request random (higher variance)
- Stratification: Balance groups by segments (country, platform)
Sample Size Calculation
- Minimum detectable effect (MDE): Smallest change worth detecting (e.g., 2% increase)
- Statistical power: 80% probability of detecting real effect
- Significance level: Ξ± = 0.05 (5% false positive rate)
- Formula: n β 16ΟΒ² / δ² (Ο = std dev, Ξ΄ = MDE)
Statistical Significance
- T-test: Compare means of two groups
- P-value: p < 0.05 = statistically significant
- Confidence interval: "95% confident improvement is between 1.2% and 3.8%"
Guardrail Metrics
Primary metric is what you optimize for, but guardrail metrics ensure you don't break the system.
| System | Primary Metric | Guardrail Metrics |
|---|---|---|
| Search | Click-through rate (CTR) | Latency, null result rate, bounce rate |
| Recommendations | Conversion rate | Diversity, coverage, user churn |
| Fraud Detection | Fraud caught (%) | False positive rate, user friction |
| Ads | Revenue per user | User engagement, ad load, complaints |
Common Pitfalls
- Peeking: Checking results early and stopping test biases results
- Multiple testing: Running 20 tests increases false positive rate
- Novelty effect: Users initially like new UI, then revert
- Carryover effect: Treatment affects control group (network effects)
- Sample ratio mismatch: 50/50 split ends up 48/52 (logging bug)
Feedback Loops
Feedback loops occur when a model's predictions influence the data used to retrain it. This can create positive feedback (reinforcing) or negative feedback (correcting).
Positive Feedback Loops (Dangerous)
graph TD
Model[Model predicts
Item A popular]
Show[System shows
Item A to users]
Click[Users click
Item A more]
Data[Training data:
Item A has high CTR]
Retrain[Retrain model
with new data]
Model --> Show
Show --> Click
Click --> Data
Data --> Retrain
Retrain --> Model
style Model fill:#ffcccc
style Retrain fill:#ffcccc
Real-World Examples
Recommendation Systems
Problem: Model recommends popular items β users click them β model learns they're even more popular β reduces diversity.
Solution: Exploration (randomize 10% of recommendations), diversity constraints, debiasing algorithms.
Search Ranking
Problem: Top results get more clicks β model ranks them higher β less opportunity for other results.
Solution: Position bias correction, randomized experiments, click model that accounts for position.
Fraud Detection
Problem: Model only learns from transactions it flagged (other fraud not caught).
Solution: Random sampling of "good" transactions for manual review, adversarial testing.
Hiring Algorithms
Problem: Model trained on past hires β replicates historical biases β perpetuates discrimination.
Solution: Fairness constraints, diverse training data, regular audits.
Breaking Feedback Loops
- Exploration: Ξ΅-greedy (random 10% of time), Thompson sampling
- Counterfactual logging: Log what model would have predicted for all items
- Propensity scoring: Weight training samples by probability they were shown
- Manual curation: Human review of edge cases
- Adversarial testing: Red team tries to game the system
MLOps (ML Operations)
MLOps is the practice of deploying, monitoring, and maintaining ML models in production. It's the ML equivalent of DevOps.
MLOps Maturity Levels
| Level | Description | Characteristics |
|---|---|---|
| Level 0 | Manual | Data scientists manually train, deploy models. No automation. |
| Level 1 | Automated Training | Scheduled retraining pipelines. Still manual deployment. |
| Level 2 | CI/CD for ML | Automated testing, deployment. Model registry. Monitoring. |
| Level 3 | Full MLOps | Auto-retraining on drift. Continuous monitoring. Rollback. |
Model Versioning
What to Version
- Code: Training scripts, preprocessing (Git)
- Data: Training dataset snapshot (DVC, Delta Lake)
- Model artifacts: Weights, architecture (MLflow, model registry)
- Configuration: Hyperparameters, feature definitions
- Environment: Dependencies (requirements.txt, Docker image)
Model Registry
- Metadata: Who trained it, when, performance metrics
- Lineage: Which data/code/features were used
- Stage: Development β Staging β Production β Archived
- Approval: Review process before production
Monitoring ML Models
graph TB
subgraph "Input Monitoring"
InputDist[Input Distribution
Feature drift detection]
DataQuality[Data Quality
Missing values, outliers]
end
subgraph "Model Monitoring"
Predictions[Prediction Distribution
Output drift]
Confidence[Confidence Scores
Uncertainty estimation]
end
subgraph "Performance Monitoring"
Online[Online Metrics
CTR, conversion, revenue]
Offline[Offline Metrics
Precision, recall, RMSE]
Latency[Latency
p50, p99, p999]
end
subgraph "Alerts & Actions"
Alert[Alert on Drift
Slack, PagerDuty]
Retrain[Trigger Retraining
Pipeline]
Rollback[Rollback Model
Previous version]
end
InputDist --> Alert
DataQuality --> Alert
Predictions --> Alert
Online --> Alert
Offline --> Alert
Alert --> Retrain
Alert --> Rollback
Model Drift
Data Drift (Covariate Shift)
Input distribution changes: P(X) changes, but P(Y|X) stays the same.
Example: Recommendation model trained on desktop users, now 80% mobile.
Detection: KL divergence, Kolmogorov-Smirnov test, Population Stability Index (PSI).
Concept Drift
Relationship between features and target changes: P(Y|X) changes.
Example: Fraud patterns evolve, COVID changes user behavior.
Detection: Drop in online metrics (accuracy, AUC), user complaints.
Label Drift
Output distribution changes: P(Y) changes.
Example: Spam detection sees surge in new spam type.
Detection: Prediction distribution shifts significantly.
Retraining Triggers
- Scheduled: Daily/weekly retraining regardless of performance
- Performance-based: Retrain when accuracy drops below threshold
- Drift-based: Retrain when input distribution shifts (PSI > 0.2)
- Data volume: Retrain when N new labeled samples accumulated
- Manual: Data scientist triggers after investigation
Production ML Challenges & Solutions
The gap between training models and running them in production is vast. Here are the real-world challenges you'll face at scale.
Training-Serving Skew
The #1 production ML issue. Features are computed differently in training (batch, historical) versus serving (real-time, live).
The Problem
Training: Compute user's "average purchase amount" from past 30 days using Spark batch job on historical data.
Serving: API needs the feature NOW. Re-implements logic in Python, slightly different aggregation window.
Result: Model sees different feature values in production than training. Accuracy drops from 92% to 78%.
Solution: Feature Store as Source of Truth
- Single code path: Feature computation logic lives in one place
- Offline training: Reads from feature store's historical data (S3/BigQuery)
- Online serving: Reads from feature store's online cache (Redis/DynamoDB)
- Guaranteed consistency: Training and serving see identical features
Model Staleness
ML models degrade over time as the world changes. How often should you retrain?
| Model Type | Retrain Frequency | Staleness Impact |
|---|---|---|
| Recommendation Model | Daily | User preferences shift, new items added. 1-week-old model loses 5-10% accuracy. |
| Fraud Detection | Hourly | Fraudsters adapt quickly. 24-hour-old model misses 30% of new fraud patterns. |
| Ad CTR Model | Every 10 minutes | Real-time bidding requires freshest data. Even 1-hour staleness costs millions. |
| Search Ranking | Weekly | Search patterns change slowly. Daily retraining doesn't improve metrics. |
GPU Serving Economics
GPUs are expensive but can be cheaper than CPUs at high throughput. Here's the math:
GPU Serving (NVIDIA A100)
- Cost: $3/hour (AWS p4d.xlarge)
- Throughput: 1,000 inferences/second (with batching)
- Cost per 1K inferences: $3/hour Γ· 3,600 seconds Γ 1 second = $0.000833 per second = $0.003 per 1K inferences
CPU Serving (Fallback)
- Cost: $0.10/hour (AWS m5.xlarge)
- Throughput: 50 inferences/second (no batching benefit)
- Cost per 1K inferences: $0.10/hour Γ· 3,600 Γ 20 seconds = $0.02 per 1K inferences
Result
At high throughput (>100 QPS), GPUs are 7x cheaper than CPUs. But at low throughput (<10 QPS), CPUs win because GPU sits idle.
Canary Deployment for Models
Never deploy a model to 100% of traffic immediately. Roll out gradually and watch metrics.
// Canary deployment strategy
1. Deploy new model (v2) to 5% of traffic
2. Run for 24 hours, compare metrics:
- Click-through rate (CTR)
- Revenue per user
- Latency (p50, p99)
- Error rate
3. Decision criteria:
- If CTR drops >2%: AUTO-ROLLBACK to v1
- If revenue down >5%: AUTO-ROLLBACK
- If p99 latency >100ms: AUTO-ROLLBACK
- If all metrics stable/better: Ramp to 25%, then 50%, then 100%
4. Full rollout takes 3-5 days for safety
Shadow Mode
Before canary, run new model in shadow mode: it gets 100% of traffic but predictions are logged, not served.
- Production model (v1): Serves actual predictions to users
- Shadow model (v2): Receives same inputs, logs predictions, no user impact
- Comparison: Analyze shadow predictions offline: "If we'd used v2, would metrics improve?"
- Zero risk: If v2 is broken, no user sees it
Key Takeaways
- Feature stores solve training/serving skew by centralizing feature management with online (low-latency) and offline (historical) stores.
- Model serving architecture depends on latency requirements: batch (high throughput, stale) vs real-time (low latency, expensive).
- Training pipelines must be reproducible: version code, data, models, and environment. Track experiments and automate hyperparameter tuning.
- A/B testing is essential for validating model improvements. Use statistical significance, confidence intervals, and guardrail metrics.
- Feedback loops occur when models influence their own training data. Use exploration, debiasing, and counterfactual logging to break them.
- MLOps requires monitoring for data drift, concept drift, and performance degradation. Automate retraining and always have rollback capability.
- Production challenges: Training-serving skew is the #1 issue. Use feature stores, canary deployments, and shadow mode for safe rollouts.
- GPU economics: At high throughput (>100 QPS), GPUs are 7x cheaper than CPUs. At low throughput, CPUs are more cost-effective.