S30 Logo
S30 AI Labwww.thes30.com
Back
#61

ML System Design Fundamentals

ExpertšŸ—ļø System DesignW13 D1

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.

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.

SystemOffline MetricsOnline / Business Metrics
RecommendationRecall@K, NDCG@KCTR, conversion
SearchMRR, NDCG@KCTR, successful searches
Fraud DetectionPrecision, Recall, PR-AUCFraud 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.

AspectTrainingServing
GoalLearn model parametersGenerate predictions
DataHistorical datasetsCurrent/request-time data
LatencyMinutes or hours may be fineOften milliseconds
ComputeLarge CPU/GPU clustersCPU/GPU serving fleet
Batch sizeUsually largeUsually small
FeaturesReproducible historical featuresSame 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:

  1. ā—Requirements — what are we building?
  2. ā—Scale — how many users/items/requests?
  3. ā—Metrics — model, system, and business metrics.
  4. ā—Data — where do training examples and labels come from?
  5. ā—Features — batch vs real-time features.
  6. ā—Model — baseline first, complexity when justified.
  7. ā—Training — how is the model trained and updated?
  8. ā—Serving — batch or online inference?
  9. ā—Evaluation — offline testing and A/B testing.
  10. ā—Monitoring — data, model, system, and business health.
  11. ā—Failure modes — what happens when components fail?
  12. ā—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?

Python 3 — Notebook
0/8 solvedSubstack Notes
1
Dataset & Setup

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.

0 — Problem framing

1 — Requirements (SLOs + constraints)

Loading editor...
2
1 — Requirements (SLOs + constraints)

1 — Requirements (SLOs + constraints)

Loading editor...
3
2 — Metrics (business + model + guardrails)

2 — Metrics (business + model + guardrails)

Loading editor...
4
3 — Data + labeling plan

3 — Data + labeling plan

Loading editor...
5
4 — Modeling plan (baselines → iterations)

4 — Modeling plan (baselines → iterations)

Loading editor...
6
5 — Serving architecture (online + batch)

5 — Serving architecture (online + batch)

Loading editor...
7
6 — Monitoring + iteration loop

6 — Monitoring + iteration loop

Loading editor...
8
7 — Final: tradeoffs (2 required)
1

7 — Final: tradeoffs (2 required)

Loading editor...

Need help? Share feedback