Before You Start
- Required knowledge
- Supervised ML lifecycle, classification metrics, and basic system-design concepts.
- Libraries used
- Python standard library only
- Dataset and source
- A supplied fraud-detection scenario and requirement dictionaries; no training dataset.
- Expected output
- A structured ML system design covering objectives, labels, data, modeling, serving, monitoring, and trade-offs.
Lesson Videos
ML System Design Fundamentals ā Theory & Concepts
Read this before attempting the exercises. ML system design interviews test your ability to design an end-to-end ML system, not just choose or train a model.
The central idea is:
ML System != Model
ML System =
Data
+ Features
+ Model
+ Training
+ Serving
+ Evaluation
+ Monitoring
+ Feedback Loop
A model might have excellent accuracy and still be part of a bad ML system if predictions are too slow, features are stale, infrastructure is unreliable, or the model does not improve the business objective.
1. The End-to-End ML System
A typical production ML system has two major sides:
OFFLINE / TRAINING
Historical Data
ā
Data Pipeline
ā
Feature Engineering
ā
Model Training
ā
Offline Evaluation
ā
Model Registry
ā
Deploy
ā
ONLINE / SERVING
User / Application Request
ā
Feature Computation
ā
Model Serving
ā
Prediction
ā
Product Decision
ā
Logging + Monitoring
ā
Future Training Data
For example, in a recommendation system:
Past clicks / purchases
ā
Training data
ā
Train recommendation model
ā
Deploy model
ā
User opens application
ā
Generate recommendations
ā
User clicks an item
ā
Click is logged
ā
Used in future training
This creates a feedback loop.
2. The ML System Design Framework
A useful interview framework is:
1. Clarify Requirements
2. Define Metrics
3. Understand Data and Labels
4. Design Features
5. Choose the Model
6. Design Training Pipeline
7. Design Serving Architecture
8. Evaluate / A/B Test
9. Monitor
10. Discuss Scaling, Failure Modes, and Tradeoffs
Do not immediately jump to:
"We should use a transformer."
First understand what system you are actually trying to build.
3. Step 1 ā Clarify Requirements
Requirements can broadly be divided into:
Functional Requirements
What should the system actually do?
Questions include:
- āWhat are we predicting?
- āWho or what are we predicting for?
- āWhat input does the system receive?
- āWhat output should it produce?
- āHow will the prediction be used?
For fraud detection:
Input:
Transaction
Output:
Fraud probability
Decision:
Approve / Reject / Send for review
Non-Functional Requirements
These describe how the system should operate.
Important examples:
Latency
Throughput / QPS
Availability
Scale
Cost
Freshness
Storage
Reliability
For example:
Fraud Detection System
Traffic:
10,000 transactions / second
Latency:
p99 < 50 ms
Availability:
99.99%
Prediction:
Fraud probability between 0 and 1
These requirements strongly influence the architecture.
4. Step 2 ā Define Metrics
ML systems usually require multiple kinds of metrics.
Model Metrics
These measure prediction quality.
Examples:
Classification:
Accuracy
Precision
Recall
F1
ROC-AUC
PR-AUC
Ranking:
Recall@K
MRR
NDCG@K
Regression:
MAE
MSE
RMSE
System Metrics
These measure whether the infrastructure works well.
Examples:
Latency
p50 / p95 / p99 latency
Throughput
Requests per second
Error rate
Availability
CPU / GPU utilization
Business Metrics
These measure whether the ML system actually creates value.
Examples:
CTR
Conversion rate
Revenue
Engagement
Fraud loss
User retention
For fraud systems, a useful guardrail is often:
Manual review capacity
Example:
Risk team can investigate only 500 transactions per day
That means the model is not just choosing a binary label. It is also choosing an operating point:
Which top-risk transactions should consume the limited analyst queue?
So in production fraud systems, thresholding is often tied to:
Top-k alerts per day
or
Maximum review rate as a percentage of traffic
So think:
Model Metrics
ā
Is the model good?
System Metrics
ā
Can we serve it reliably?
Business Metrics
ā
Does it actually help the product?
5. Offline vs Online Metrics
Models are normally evaluated offline before deployment.
But offline performance does not guarantee business improvement.
| System | Offline Metrics | Online / Business Metrics |
|---|---|---|
| Recommendation | Recall@K, NDCG@K | CTR, conversion |
| Search | MRR, NDCG@K | CTR, successful searches |
| Fraud Detection | Precision, Recall, PR-AUC | Fraud loss, false declines |
For example:
New recommendation model
NDCG:
0.72 ā 0.78
Looks better offline.
But suppose the new model requires expensive computation:
Latency:
80 ms ā 1500 ms
Users may wait longer and interact less.
Therefore:
Offline metric ā
does NOT necessarily mean
Business metric ā
This is why production systems often use A/B testing.
6. Step 3 ā Understand Data and Labels
Before choosing a model, ask:
Where does the training data come from?
How are labels generated?
How much data exists?
How fresh is the data?
Is the data biased?
Can labels arrive late?
For recommendation:
User impression
ā
User clicked?
ā
Label
For fraud:
Transaction
ā
Chargeback / fraud investigation
ā
Fraud label
Labels may sometimes arrive days or weeks later.
This affects how quickly the model can be retrained.
7. Step 4 ā Feature Engineering at Scale
Features can come from different sources.
User Features
Examples:
Age
Country
Purchase history
Previous clicks
Interests
These are often computed periodically.
Raw events
ā
Batch processing
ā
User features
Item Features
Examples:
Category
Price
Popularity
Text embedding
Image embedding
Context Features
These often need to be computed in real time.
Examples:
Current time
Device
Location
Current query
Current session
Cross Features
These describe relationships between entities.
For example:
User likes sports
+
Item category = sports
or:
Similarity(
user_embedding,
item_embedding
)
8. Training-Serving Consistency
One important production problem is training-serving skew.
Suppose training calculates:
purchase_count =
number of purchases during last 30 days
But production calculates:
purchase_count =
number of purchases during last 7 days
The model was trained using one definition but receives another during inference.
That can hurt model quality.
Ideally:
Training Feature Logic
=
Serving Feature Logic
Feature stores and shared feature pipelines can help maintain this consistency.
9. Avoid Data Leakage
A training feature should represent information that would actually be available when the prediction is made.
Suppose we want to predict whether a customer will repay a loan.
Using:
customer_income
credit_score
past_payment_history
may be reasonable.
But using:
number_of_missed_payments_after_loan
would leak future information.
The model may look extremely accurate during training but fail in production.
The rule is:
If the information would not exist at prediction time, do not use it as an input feature.
10. Step 5 ā Model Selection
Do not automatically choose the most sophisticated model.
Start with a baseline.
Simple Baseline
ā
Measure performance
ā
Identify limitations
ā
Increase complexity if necessary
Examples:
Fraud:
Logistic Regression
ā
Gradient Boosted Trees
ā
Neural Network
Recommendation:
Popularity
ā
Collaborative Filtering
ā
Two-Tower Model
ā
Advanced Ranking Model
The best production model is often the model that gives the best tradeoff between:
Accuracy
Latency
Cost
Interpretability
Maintainability
11. Step 6 ā Training vs Serving
Training and serving have very different requirements.
| Aspect | Training | Serving |
|---|---|---|
| Goal | Learn model parameters | Generate predictions |
| Data | Historical datasets | Current/request-time data |
| Latency | Minutes or hours may be fine | Often milliseconds |
| Compute | Large CPU/GPU clusters | CPU/GPU serving fleet |
| Batch size | Usually large | Usually small |
| Features | Reproducible historical features | Same feature definitions at inference |
Training might look like:
Training Data
ā
Feature Pipeline
ā
Train Model
ā
Evaluate
ā
Quality Gate
ā
Model Registry
At scale, training is often distributed across multiple GPUs or workers:
Training Data
ā
āāāāāāāāāāā¼āāāāāāāāāā
ā ā ā
GPU 1 GPU 2 GPU 3
Batch A Batch B Batch C
ā ā ā
gradients gradients gradients
āāāāāāāāāāā¼āāāāāāāāāā
ā
Combine gradients
ā
Update model
Serving might look like:
Request
ā
Fetch / Compute Features
ā
Load Model
ā
Inference
ā
Prediction
ā
Response
12. Batch vs Online Inference
Not every ML system requires real-time inference.
Batch Inference
Predictions are generated periodically.
Database
ā
Run model every night
ā
Generate predictions
ā
Store predictions
Examples:
Churn prediction
Email targeting
Weekly recommendations
Risk scoring
Advantages:
Simpler
Cheaper
Can process large batches
Less strict latency requirements
Online Inference
Predictions are generated when requests arrive.
Request
ā
Real-time features
ā
Model
ā
Prediction
Examples:
Fraud detection
Search ranking
Ad ranking
Real-time recommendations
These systems usually have strict latency and availability requirements.
13. Common ML System Pattern ā Recommendation
Large recommendation systems often use multiple stages.
Millions of Items
ā
Candidate Generation
ā
~1,000 Candidates
ā
Ranking
ā
~100 Candidates
ā
Re-ranking
ā
~10 Recommendations
Candidate Generation
Goal:
Quickly find potentially relevant items.
Common approaches:
Embedding similarity
Collaborative filtering
Approximate nearest neighbors
Popularity
Ranking
A more expensive model scores fewer candidates.
Features might include:
User features
Item features
User-item interaction features
Context features
Re-ranking
The final stage may apply:
Diversity
Freshness
Business rules
Safety rules
Deduplication
Why not run the expensive ranking model on one million items?
Because:
1,000,000 Ć expensive model
would create excessive latency and compute cost.
14. Common ML System Pattern ā Search
A search system might look like:
User Query
ā
Query Understanding
ā
Retrieval
ā
BM25 + Embedding Search
ā
Candidate Documents
ā
Ranking Model
ā
Personalization / Re-ranking
ā
Search Results
Retrieval emphasizes:
Speed + Recall
Ranking emphasizes:
Precision + Ordering Quality
15. Common ML System Pattern ā Fraud Detection
A simplified architecture:
Transaction
ā
Real-Time Feature Computation
ā
Fraud Model
ā
Fraud Score
ā
Rules / Thresholds
ā
Decision
For example:
score < 0.30
ā approve
0.30 ⤠score < 0.80
ā manual review
score ā„ 0.80
ā reject
The exact thresholds depend on business requirements.
Sometimes the threshold is chosen indirectly from an analyst budget rather than from a fixed probability cutoff.
Example:
Traffic: 2,000,000 transactions / day
Manual review capacity: 500 cases / day
Procedure:
1. Score all transactions
2. Sort by fraud risk
3. Send only the top 500 to review
So the review threshold is really:
the score of the 500th riskiest transaction that day
This is why fraud operating points are often framed as:
recall at a fixed review budget
Fraud systems usually care strongly about:
Recall
Precision
False positive rate
Latency
Fraud loss
16. Step 7 ā A/B Testing
Offline evaluation happens before deployment.
Then we may test the model on real users.
Suppose:
Current Model = A
New Model = B
Traffic might be split:
Users
ā
Random Assignment
ā
+-----------+-----------+
| |
Model A Model B
Control Treatment
| |
CTR = 5.0% CTR = 5.4%
We then determine whether the improvement is statistically meaningful and whether other important metrics became worse.
A/B testing connects:
Offline ML performance
ā
Real user behavior
ā
Business impact
17. Step 8 ā Monitoring
Deployment is not the end of the ML lifecycle.
We need to monitor the system continuously.
System Monitoring
Latency
Throughput
Error rate
CPU / GPU usage
Availability
Data Monitoring
Feature distributions
Missing values
Schema changes
Data drift
Model Monitoring
Prediction distribution
Accuracy
Precision / Recall
Calibration
Model drift
Business Monitoring
CTR
Revenue
Conversion
Fraud loss
Engagement
A model service could be technically healthy:
Latency = 30 ms
Errors = 0.01%
while model quality is deteriorating because the production data has changed.
Therefore both system health and ML health must be monitored.
18. Feedback Loops and Retraining
Production predictions often generate future training data.
Model
ā
Prediction
ā
User sees recommendation
ā
User clicks
ā
Click logged
ā
Training dataset
ā
Retrain model
ā
New model
Retraining might happen:
Hourly
Daily
Weekly
Monthly
or when monitoring detects significant degradation.
The correct frequency depends on how quickly the underlying data changes.
19. Important Failure Modes
A strong ML system design should discuss what can go wrong.
Examples include:
Data pipeline failure
Missing features
Stale features
Training-serving skew
Data drift
Model quality degradation
Model server failure
Latency spikes
Bad model deployment
Feature store unavailable
Cold-start users/items
Feedback-loop bias
For example:
Feature Store unavailable
ā
Cannot fetch user features
ā
Model cannot make normal prediction
A fallback might be:
Use cached features
or
Use default features
or
Use a simpler fallback model
Production ML systems should be designed for failure, not only for the happy path.
20. Scale Changes the Design
Always ask:
What happens if traffic increases by 10Ć or 100Ć?
Suppose:
Current traffic:
1,000 requests/sec
Future traffic:
100,000 requests/sec
You may need:
Load balancing
Horizontal scaling
Caching
Batching
Approximate retrieval
Distributed feature stores
Multiple model servers
Queues
Autoscaling
System design is therefore about both:
ML quality
+
Engineering scalability
21. Tradeoffs Are Central to ML System Design
There is rarely one perfect architecture.
You constantly make tradeoffs.
Accuracy vs Latency
Large model
ā Better accuracy
ā Higher latency
Freshness vs Cost
Features updated every minute
ā Fresher predictions
ā More infrastructure cost
Exact Retrieval vs Approximate Retrieval
Exact nearest neighbors
ā Better exactness
ā Expensive at massive scale
ANN
ā Much faster
ā May miss some neighbors
Complexity vs Maintainability
Complex architecture
ā Potential performance improvement
ā Harder to operate
A good interview answer explains why a particular tradeoff is appropriate for the requirements.
22. A Practical Interview Flow
When given a question such as:
Design a recommendation system for an e-commerce application.
A strong discussion can follow this order:
1. Requirements
ā
2. Scale and Constraints
ā
3. Metrics
ā
4. Data and Labels
ā
5. Features
ā
6. Model
ā
7. High-Level Architecture
ā
8. Training Pipeline
ā
9. Serving
ā
10. A/B Testing
ā
11. Monitoring
ā
12. Failure Modes
ā
13. Scaling + Tradeoffs
Do not spend the entire interview discussing the model.
23. Final Mental Model
When you hear:
Design an ML system
do not think only:
Which model should I use?
Think:
DATA
ā
FEATURES
ā
TRAINING
ā
MODEL
ā
SERVING
ā
PREDICTION
ā
PRODUCT
ā
USER BEHAVIOR
ā
LOGGING
ā
MONITORING
ā
RETRAIN
āŗ
The model is only one component.
The real question is:
How do we build a reliable, scalable system that turns data into useful predictions and continues working as users, data, and traffic change?
24. Interview Checklist
Before finishing an ML system design interview, make sure you have discussed:
- āRequirements ā what are we building?
- āScale ā how many users/items/requests?
- āMetrics ā model, system, and business metrics.
- āData ā where do training examples and labels come from?
- āFeatures ā batch vs real-time features.
- āModel ā baseline first, complexity when justified.
- āTraining ā how is the model trained and updated?
- āServing ā batch or online inference?
- āEvaluation ā offline testing and A/B testing.
- āMonitoring ā data, model, system, and business health.
- āFailure modes ā what happens when components fail?
- āTradeoffs ā accuracy, latency, cost, freshness, and complexity.
Key takeaway: ML system design is not about finding the fanciest model. It is about designing the complete system around the model.
Now you're ready to attempt the exercises. Switch to the Exercise tab and start designing!
Ready to practice?
ML System Design Fundamentals ā Student Lab
Case study: Fraud detection for card-not-present transactions.
This notebook is a structured design doc exercise. Fill in the templates with concise bullets.
Prompt (the interview question)
Design an ML system to detect fraudulent card-not-present transactions in real time.
You must address: requirements, data, modeling, serving, monitoring, and iteration.