ML System Design: Recommendation Systems, Fraud Detection & Search Ranking
Training an accurate machine learning model inside a Jupyter notebook is only a small part of building a successful real-world ML application. Deploying that model to serve millions of users under strict millisecond latency budgets, changing data distributions, infrastructure failures, and adversarial attacks requires Machine Learning System Design.
A production ML system is not simply a trained model connected to an API. It is an end-to-end architecture involving data ingestion, feature engineering, model training, model serving, monitoring, feedback collection, and continuous improvement.
Across modern industry applications, three important system architectures dominate production engineering:
- Recommendation Systems: Predict which products, videos, songs, or other items a user is most likely to find interesting.
- Real-Time Fraud Detection: Identify suspicious transactions before financial damage occurs.
- Search Ranking: Retrieve relevant documents or products and order them according to user intent and relevance.
Understanding their architectural components, feature stores, latency budgets, evaluation metrics, and operational trade-offs is essential for designing scalable AI platforms.
1. Recommendation Systems: The Multi-Stage Funnel
Whether powering video feeds, e-commerce catalogs, or music playlists, a recommendation engine cannot run a computationally expensive deep neural network against 50 million candidate items for every request.
Instead, production recommendation systems use a multi-stage retrieval and ranking funnel that progressively reduces millions of candidates to the top 10–20 items displayed to a user.
1.1 Recommendation System Architecture
Consider an e-commerce platform with 50 million products.
When a user opens the homepage, the system must identify products that match their interests, current activity, and shopping context.
A simplified recommendation funnel looks like this:
50 Million Catalog Items
|
v
1. Candidate Generation
Approx. 1,000 Candidates
Two-Tower Models / ANN Search
|
v
2. Ranking
Approx. 100 Candidates
Deep Learning / GBDT
|
v
3. Re-Ranking
Top 10-20 Recommendations
Diversity / Freshness / Rules
|
v
User Interface
The numbers are illustrative. Real systems may use different candidate counts, stages, and latency budgets depending on their traffic, hardware, and product requirements.
Stage 1: Candidate Generation (Retrieval)
<escape>Candidate generation</escape> identifies a relatively small collection of potentially relevant items from a massive catalog.
For example:
- A user frequently watches Python programming videos.
- The system retrieves videos about Python, data science, and machine learning.
- It may also retrieve trending videos and content from similar users.
Instead of evaluating every item with a complex model, the system uses computationally efficient retrieval techniques.
Common candidate-generation approaches:
A. Collaborative Filtering
Collaborative filtering recommends items based on user-item interaction patterns.
For example:
- User A watches videos 1, 2, and 3.
- User B watches videos 1, 2, and 4.
- User A may be interested in video 4 because similar users watched it.
Two major approaches are:
- User-based collaborative filtering: Find users with similar behavior.
- Item-based collaborative filtering: Find items that are frequently consumed together.
B. Two-Tower Neural Networks
Two-Tower models learn separate vector representations for users and items.
USER INFORMATION
|
v
User Tower Network
|
v
User Embedding
|
| Similarity
|
Item Embedding
^
|
Item Tower Network
^
|
ITEM INFORMATION
The user tower may process:
- User ID
- Age group, where appropriate
- Historical interactions
- User preferences
- Recent activity
The item tower may process:
- Item ID
- Category
- Description
- Price
- Content metadata
Both towers generate embeddings in the same vector space.
The system compares their similarity using a dot product or cosine similarity.
Dot-product scoring:
\[ score(u,i)=e_u^T e_i \]
Cosine similarity:
\[ similarity(u,i)= \frac{e_u\cdot e_i} {\|e_u\|\|e_i\|} \]
Here:
- \(e_u\) = user embedding
- \(e_i\) = item embedding
The system retrieves items with high similarity scores.
C. Approximate Nearest Neighbor (ANN) Search
Searching every item embedding individually can be expensive.
ANN algorithms find approximately nearest vectors without comparing the query against every vector.
Popular technologies and approaches include:
- FAISS
- HNSW
- ScaNN
- Vector databases
ANN retrieval is especially useful when the catalog contains millions of items.
Important: ANN retrieval is optimized for fast candidate discovery. It does not necessarily produce the final best recommendations because it may not consider every contextual feature or business constraint.
Stage 2: Ranking
After retrieval, the system may have approximately 1,000 candidate items.
The ranking model evaluates each candidate using richer information.
For example:
- User's historical preferences
- Item category
- Item popularity
- Time since last interaction
- User-item interaction history
- Device and session context
- Price or availability
The model estimates the probability or expected value of a particular interaction.
Example:
| Product | Predicted click probability |
|---|---|
| Laptop A | 0.92 |
| Headphones B | 0.84 |
| Keyboard C | 0.71 |
| Monitor D | 0.63 |
The system sorts candidates according to the ranking objective.
Common ranking algorithms:
- Gradient Boosting Decision Trees
- XGBoost
- LightGBM
- Deep Neural Networks
- Deep & Cross Networks
- Wide & Deep Models
A ranking model might predict:
\[ P(click\mid user,item,context) \]
For video recommendations, it might also predict:
\[ P(watch\mid user,item,context) \]
A production system may combine several objectives rather than optimizing clicks alone.
For example:
\[ Score = w_1P(click)+ w_2P(conversion)+ w_3P(long\ watch) \]
The weights depend on the product's business goals. A video platform may prioritize meaningful watch time, while an e-commerce platform may prioritize expected purchase value.
Stage 3: Re-Ranking and Business Rules
The ranking model may identify the top 100 items, but displaying the highest-scoring 10 items without additional constraints can create a poor experience.
For example, a user might receive:
- 10 nearly identical products
- Repeated videos from the same creator
- Out-of-stock products
- Old content
- Content that violates platform policies
The re-ranking stage applies additional constraints.
Common techniques include:
Diversity: Avoid recommending nearly identical items.
Freshness: Introduce recently published or newly available items.
Deduplication: Remove repeated products or content.
Business constraints: Consider availability, eligibility, regional restrictions, or campaign rules.
Policy filtering: Exclude content that should not be shown.
The final recommendation list is optimized for both relevance and user experience.
1.2 Recommendation System Evaluation
Recommendation systems need different evaluation metrics at different stages.
| Metric | What it measures |
|---|---|
| Recall@K | Whether relevant items appear in the retrieved top K |
| Precision@K | How many retrieved top-K items are relevant |
| NDCG@K | Quality of ranking while considering position |
| MAP | Mean Average Precision across queries or users |
| CTR | Percentage of impressions resulting in clicks |
| Conversion Rate | Percentage of interactions resulting in a desired conversion |
| Watch Time | Time users spend consuming recommended content |
For example, suppose the system recommends 10 items and 4 are relevant.
\[ Precision@10=\frac{4}{10}=0.4 \]
If 8 items are relevant overall and the system retrieves 4 of them:
\[ Recall@10=\frac{4}{8}=0.5 \]
Offline evaluation vs. online evaluation
Offline evaluation uses historical interaction data to compare models.
Online evaluation measures actual user behavior after deployment, often through controlled A/B experiments.
Offline performance does not guarantee online success. A model may achieve better ranking metrics but still reduce long-term engagement, revenue, or user satisfaction.
1.3 Important Recommendation System Challenges
- Cold Start: New users or new items have little interaction history.
- Popularity Bias: Popular items may dominate recommendations.
- Filter Bubbles: Users repeatedly receive similar content.
- Feedback Loops: Existing recommendations influence the data used to train future models.
- Catalog Changes: New, unavailable, or deleted items require index and feature updates.
- Latency: Retrieval and ranking must fit within the request's response-time budget.
Possible solutions include content-based features, popularity-based fallbacks, exploration strategies, diversity constraints, and periodic or incremental index updates.
2. Real-Time Fraud Detection: Millisecond Decision Systems
Fraud detection systems identify suspicious activities before they cause financial losses.
Consider an online payment platform processing thousands of transactions every second.
For every transaction, the system must decide whether to:
- Approve the transaction.
- Decline the transaction.
- Send it for additional verification or manual review.
The decision must often be made within a very short time.
Unlike recommendation systems, where a slightly slower response may still be acceptable, a fraud detection system must balance detection accuracy, financial risk, and transaction latency.
2.1 Fraud Detection Architecture
A simplified real-time fraud detection architecture:
Customer Payment
|
v
Transaction API
|
v
Event Validation
|
v
Feature Retrieval Layer
/ \
v v
User Features Transaction Features
\ /
\ /
v
Fraud ML Model
|
v
Fraud Risk Score
|
v
Decision Engine
/ | \
v v v
Approve Review Decline
| | |
v v v
Payment / Investigation
|
v
Feedback & Monitoring
The architecture contains several important components.
Stage 1: Transaction Ingestion
The system receives transaction information such as:
- Transaction ID
- Customer ID
- Transaction amount
- Merchant ID
- Timestamp
- Payment method
- Device information
- IP address
- Geographic location
The system validates the transaction and prepares it for feature processing.
Stage 2: Feature Engineering
Raw transaction information is usually insufficient to identify sophisticated fraud.
The system derives behavioral and historical features.
Examples:
| Feature | Description |
|---|---|
| Transaction Amount | Amount involved in the current payment |
| Transactions in 5 Minutes | Recent transaction frequency |
| Average Transaction Amount | Historical spending behavior |
| New Device Flag | Whether the device is unfamiliar |
| Geographic Distance | Distance from recent transaction location |
| Failed Login Count | Number of recent failed login attempts |
| Merchant Risk Score | Historical risk associated with the merchant |
For example:
A customer usually makes transactions between ₹500 and ₹3,000.
Suddenly, a ₹90,000 transaction appears from a new device and an unfamiliar location.
This combination may indicate suspicious activity.
The system should not automatically declare the transaction fraudulent based on one feature. It evaluates multiple signals together.
Stage 3: Feature Store
A feature store manages reusable machine learning features.
It commonly provides two different access patterns.
Offline Feature Store
Used for:
- Model training
- Historical analysis
- Batch feature computation
- Model validation
It can store large historical datasets in systems such as data warehouses or distributed storage platforms.
Online Feature Store
Used for:
- Real-time inference
- Recent user activity
- Low-latency feature retrieval
- Transaction-time decision-making
It typically relies on low-latency storage systems such as Redis, DynamoDB, or other suitable online databases.
Example:
Raw Events
|
v
Feature Pipeline
|
+------+------+
| |
v v
Offline Store Online Store
| |
v v
Model Training Real-Time API
A critical design requirement is training-serving consistency.
If a feature is calculated differently during training and production inference, the model may receive inconsistent inputs.
Feature definitions, timestamps, aggregation windows, missing-value handling, and transformations should be consistent.
Stage 4: Fraud Prediction
The fraud model receives the transaction features and produces a risk score.
For binary classification:
\[ P(Fraud\mid X)=f(X) \]
Where:
- \(X\) = transaction features
- \(f\) = trained ML model
- Output = estimated fraud probability
Example:
| Transaction | Fraud probability |
|---|---|
| Transaction A | 0.02 |
| Transaction B | 0.18 |
| Transaction C | 0.78 |
| Transaction D | 0.96 |
The system then uses a decision policy to determine the next action.
Stage 5: Decision Engine and Thresholds
A model's probability is not itself a business decision.
The system applies thresholds and business rules.
For example:
Fraud Score < 0.20
|
v
APPROVE
0.20 to 0.75
|
v
MANUAL REVIEW /
ADDITIONAL VERIFICATION
Fraud Score > 0.75
|
v
DECLINE
These thresholds are illustrative, not universal.
A real decision policy considers:
- Financial loss from fraud
- Cost of incorrectly declining legitimate transactions
- Review-team capacity
- Customer experience
- Regulatory and contractual requirements
- Model calibration and uncertainty
The optimal threshold depends on the relative cost of different errors.
For example, incorrectly declining a legitimate ₹500 payment and approving a fraudulent ₹90,000 transaction have very different consequences.
A cost-sensitive decision objective can be written as:
\[ Expected\ Cost = C_{FP}\times FP+ C_{FN}\times FN \]
Where:
- \(FP\) = legitimate transactions incorrectly flagged as fraud
- \(FN\) = fraudulent transactions incorrectly approved
- \(C_{FP}\) = cost of a false positive
- \(C_{FN}\) = cost of a false negative
The system should select a decision policy that minimizes expected operational and financial cost while meeting business constraints.
2.2 Fraud Detection Evaluation Metrics
Accuracy is often misleading in fraud detection because fraudulent transactions may represent a very small percentage of all transactions.
Suppose a dataset contains:
- 99,900 legitimate transactions
- 100 fraudulent transactions
A model that predicts every transaction as legitimate achieves 99.9% accuracy but detects zero fraud.
Therefore, more useful metrics include:
| Metric | Importance |
|---|---|
| Precision | How many flagged transactions are actually fraudulent |
| Recall | How many actual fraudulent transactions are detected |
| F1-Score | Balance between precision and recall |
| PR-AUC / Average Precision | Performance across precision-recall trade-offs |
| ROC-AUC | Ability to rank positive cases above negative cases |
| False Positive Rate | How frequently legitimate transactions are incorrectly flagged |
| Fraud Loss Prevented | Estimated financial loss avoided |
| Approval Rate | Percentage of transactions approved |
For fraud detection, operational metrics are equally important.
Examples:
- Fraud loss per transaction volume
- Percentage of legitimate customers incorrectly declined
- Manual review volume
- Average decision latency
- Percentage of transactions requiring additional authentication
2.3 Advanced Fraud Detection Techniques
A. Rule-Based Detection
Rules can identify known suspicious patterns.
Example:
if transaction_amount > 50000 and is_new_device:
flag_for_review = True
Rules are easy to understand and can respond quickly to known threats.
However, they are difficult to maintain at scale and may miss complex patterns.
B. Supervised Learning
If historical transactions have reliable fraud labels, classification algorithms can learn suspicious behavior.
Common choices include:
- Logistic Regression
- Random Forest
- XGBoost
- LightGBM
- Neural Networks
C. Anomaly Detection
Anomaly detection identifies unusual behavior that differs from normal patterns.
Useful algorithms include:
- Isolation Forest
- Local Outlier Factor
- One-Class SVM
- Autoencoders
Anomaly scores are not automatically fraud probabilities. They identify unusual patterns that may require investigation.
D. Graph-Based Fraud Detection
Fraud rings often involve connected accounts, devices, phone numbers, cards, or merchants.
A graph can represent these relationships:
Account A
/ \
/ \
Device X Card 1
| |
| |
Account B Account C
\ /
\ /
Merchant Z
Graph-based methods can help identify suspicious groups that individual transaction-level models may miss.
2.4 Important Fraud Detection Challenges
- Class Imbalance: Fraud cases are usually rare.
- Concept Drift: Fraud patterns change over time.
- Adversarial Behavior: Fraudsters deliberately modify their strategies.
- Delayed Labels: A transaction may only be confirmed as fraudulent days or weeks later.
- False Positives: Legitimate customers may be blocked.
- Data Leakage: Features may accidentally include information unavailable at transaction time.
- Latency: Slow feature retrieval or model inference can delay payments.
A robust system combines machine learning, business rules, human investigation, and continuous monitoring.
3. Search Ranking: From Query to Relevant Results
Search ranking systems determine which documents, products, webpages, or other results should appear first after a user submits a query.
For example, when someone searches:
"Best laptop for machine learning under ₹80,000"
The search engine must:
- Understand the query.
- Retrieve potentially relevant products.
- Calculate relevance scores.
- Rank results.
- Return the most useful results.
Searching and ranking are separate tasks.
A search engine does not need to run an expensive ranking model against every document in its entire index.
It first retrieves a manageable candidate set.
3.1 Search Ranking Architecture
User Search Query
|
v
Query Processing
|
v
Candidate Retrieval
|
v
Thousands of Results
|
v
Feature Extraction
|
v
Ranking Model
|
v
Top Ranked Results
|
v
Re-Ranking / Rules
|
v
Search Page
|
v
User Interaction Data
Stage 1: Query Understanding
The system processes the search query to understand what the user wants.
For example:
"Best laptop for machine learning under ₹80,000"
The system may identify:
- Product type: Laptop
- Use case: Machine learning
- Budget: ₹80,000
- Intent: Product discovery and comparison
Query understanding may include:
- Tokenization
- Spell correction
- Synonym expansion
- Entity recognition
- Intent classification
- Semantic embedding generation
Modern systems may use transformer-based language models to understand semantic relationships between query terms.
Stage 2: Candidate Retrieval
The retrieval layer identifies potentially relevant documents or products.
Common retrieval approaches include:
A. Inverted Index
An inverted index maps terms to the documents that contain them.
Example:
Term: Python
|
+---- Document 1
|
+---- Document 4
|
+---- Document 8
This allows a search engine to find matching documents without scanning every document individually.
B. BM25
BM25 is a widely used lexical information retrieval scoring function.
A simplified form is:
\[ BM25(D,Q)= \sum_{q\in Q} IDF(q) \frac{f(q,D)(k_1+1)} {f(q,D)+k_1(1-b+b\frac{|D|}{avgdl})} \]
Where:
- \(D\) = document
- \(Q\) = search query
- \(f(q,D)\) = frequency of query term in document
- \(|D|\) = document length
- \(avgdl\) = average document length
- \(k_1,b\) = tuning parameters
- \(IDF(q)\) = inverse document frequency
BM25 rewards relevant term matches while accounting for term frequency and document length.
C. Semantic Search
Lexical search may fail when the query and document use different words with similar meanings.
For example:
Query: "Affordable machine learning laptop"
Document: "Budget-friendly computer for AI development"
A semantic retrieval model converts queries and documents into vector embeddings.
The system compares their similarity to retrieve semantically related results.
A production search engine may combine lexical and semantic retrieval using hybrid search.
Stage 3: Ranking
The retrieval layer may return thousands of candidate documents.
The ranking model estimates which candidates are most relevant to the query.
Common ranking features include:
| Feature | Description |
|---|---|
| Query-Document Similarity | How closely the document matches the query |
| BM25 Score | Lexical relevance score |
| Title Match | Whether important query terms appear in the title |
| Freshness | How recently the content was published or updated |
| Popularity | Historical user engagement |
| Quality Score | Reliability and usefulness of the result |
| User Context | Relevant personalization signals |
| Location | Geographic relevance, where appropriate |
The ranking model combines these signals.
For example:
\[ RankingScore = w_1(QueryMatch)+ w_2(ContentQuality)+ w_3(Freshness)+ w_4(Context) \]
The weights or scoring function are learned or configured according to the search objective.
Common ranking algorithms:
- Logistic Regression
- Gradient Boosting Decision Trees
- LambdaMART
- XGBoost Ranking
- LightGBM Ranking
- Neural Ranking Models
- Transformer-based Cross-Encoders
Stage 4: Re-Ranking
After the main ranking stage, a final layer may apply additional constraints.
Examples:
- Remove duplicate results.
- Apply content safety policies.
- Promote useful or authoritative sources.
- Ensure diversity across domains or categories.
- Apply product availability filters.
- Respect regional restrictions.
For a shopping search, the system might avoid displaying ten nearly identical products from the same seller.
For a web search, it might avoid showing multiple copies of the same article.
3.2 Search Ranking Evaluation Metrics
Search ranking is primarily concerned with relevance and result ordering.
Important metrics include:
Mean Reciprocal Rank (MRR)
MRR measures how highly the first relevant result appears.
\[ MRR=\frac{1}{N}\sum_{i=1}^{N}\frac{1}{rank_i} \]
Where \(rank_i\) is the position of the first relevant result for query \(i\).
Normalized Discounted Cumulative Gain (NDCG)
NDCG evaluates ranking quality while considering graded relevance and result position.
\[ DCG@K= \sum_{i=1}^{K} \frac{2^{rel_i}-1}{\log_2(i+1)} \]
\[ NDCG@K=\frac{DCG@K}{IDCG@K} \]
Where:
- \(rel_i\) = relevance grade at position \(i\)
- \(IDCG\) = ideal DCG for the query
NDCG gives greater importance to relevant results appearing near the top.
Other useful metrics include:
- Precision@K
- Recall@K
- MAP
- CTR
- Conversion Rate
- Query Success Rate
- Search Abandonment Rate
Clicks should not be treated as perfect relevance labels. Users may click a result because it is positioned prominently, not necessarily because it is the most useful result.
3.3 Important Search Ranking Challenges
- Ambiguous Queries: A search term can have multiple meanings.
- Vocabulary Mismatch: Users and documents may use different words.
- Freshness: New information must be indexed quickly.
- Personalization: Results may need to reflect relevant user preferences.
- Popularity Bias: Popular results can dominate useful but less popular content.
- Spam and Manipulation: Search results may be deliberately optimized to deceive ranking systems.
- Latency: Query processing, retrieval, and ranking must fit within a strict response-time budget.
Hybrid retrieval, semantic embeddings, quality signals, spam detection, and carefully designed ranking objectives can help address these challenges.
4. Feature Stores: Connecting Training and Production
A feature store is a shared infrastructure layer that manages machine learning features for training and serving.
Without a consistent feature-management strategy, different teams may calculate the same feature differently.
For example, a fraud model may use the average transaction amount over the previous 24 hours.
If the training pipeline calculates the average using one timestamp rule and the production API uses another, the model receives inconsistent inputs.
This problem is known as training-serving skew.
4.1 Offline vs. Online Feature Stores
| Component | Offline Feature Store | Online Feature Store |
|---|---|---|
| Primary Purpose | Model training and analysis | Real-time inference |
| Data Access | Large historical datasets | Low-latency feature lookup |
| Typical Storage | Data warehouse, data lake | Redis, DynamoDB, online databases |
| Data Volume | Large | Optimized for serving |
| Query Pattern | Batch processing | Individual or small-batch requests |
A typical architecture:
Event Sources
|
v
Data Processing
|
v
Feature Pipeline
|
+----+----+
| |
v v
Offline Store Online Store
| |
v v
Model Training Model Serving
| |
+----+----+
|
v
Monitoring
Examples of feature store platforms include:
- Feast
- Tecton
- Hopsworks
A feature store is not mandatory for every ML application. Smaller systems may use well-managed database tables and shared transformation code. The important requirement is consistency, governance, and reliable feature availability.
4.2 Point-in-Time Correctness
Historical training data must reflect only information that would have been available at the prediction timestamp.
Suppose a transaction occurred at 10:00 AM.
A feature such as "number of transactions in the previous hour" must not include transactions that occurred after 10:00 AM.
Using future information creates temporal data leakage.
Feature pipelines should use event timestamps, availability timestamps, and point-in-time joins where appropriate.
5. Model Serving: Bringing ML Models into Production
A trained model becomes useful only when an application can access its predictions reliably.
Model serving exposes the model through an interface such as a REST API, gRPC endpoint, or streaming inference service.
A simplified architecture:
User / Application
|
v
API Gateway
|
v
Authentication Layer
|
v
Model Service
|
v
Feature Retrieval
|
v
Model Inference
|
v
Prediction Response
5.1 Common Model Serving Approaches
A. Real-Time Online Inference
The model receives a request and returns a prediction immediately.
Examples:
- Fraud scoring during payment.
- Product recommendation on a homepage.
- Search result ranking.
B. Batch Inference
The system generates predictions for many records in advance.
Examples:
- Daily customer churn scores.
- Overnight product recommendations.
- Weekly customer segmentation.
Batch inference is useful when predictions do not need to be calculated for every request in real time.
C. Streaming Inference
The system continuously processes incoming events and updates predictions or features.
Examples:
- Real-time transaction monitoring.
- Live user activity analysis.
- Network anomaly detection.
Technologies such as Apache Kafka, Apache Flink, and Spark Structured Streaming may support event-driven and streaming architectures.
5.2 Latency Budgets
A model's inference time is only one part of the total response time.
Consider a hypothetical online prediction request:
| Component | Latency Budget |
|---|---|
| API Gateway | 5 ms |
| Feature Retrieval | 10 ms |
| Feature Processing | 5 ms |
| Model Inference | 10 ms |
| Post-processing | 5 ms |
| Total | 35 ms |
These are illustrative values.
The actual latency depends on hardware, network topology, traffic, model size, feature-store performance, and service architecture.
A critical distinction is between:
- Average latency: Typical response time.
- p95 latency: 95% of requests complete within this time.
- p99 latency: 99% of requests complete within this time.
Production systems often monitor tail latency because a small percentage of very slow requests can seriously affect user experience.
5.3 Model Serving Optimization
Common techniques include:
- Model quantization
- Knowledge distillation
- Model pruning
- Batch inference
- GPU acceleration
- Caching
- Asynchronous processing
- Horizontal scaling
- Efficient feature retrieval
Not every technique improves every workload. For example, batching may increase throughput but introduce additional waiting time for individual requests.
6. ML System Monitoring: Detecting Production Problems
Deploying a model is not the end of the ML lifecycle.
A model that performs well today may become unreliable when user behavior, economic conditions, products, or fraud strategies change.
Production monitoring should cover infrastructure, data, model behavior, and business outcomes.
6.1 Data Drift
Data drift occurs when the distribution of incoming features changes.
Example:
A recommendation model was trained when most users watched long-form videos.
Later, user behavior shifts toward short-form content.
The model may no longer represent current behavior accurately.
6.2 Concept Drift
Concept drift occurs when the relationship between input features and the target changes.
For example, fraudsters may discover new ways to bypass existing detection rules.
The same transaction characteristics may no longer indicate the same risk.
6.3 Prediction Drift
Prediction drift occurs when the distribution of model outputs changes.
For example, a fraud model that previously assigned high-risk scores to 2% of transactions may begin assigning high-risk scores to 15%.
This may indicate changing transaction behavior, data problems, or model instability.
6.4 Monitoring Checklist
| Monitoring Area | What to Monitor |
|---|---|
| Data Quality | Missing values, invalid records, schema changes |
| Feature Drift | Changes in feature distributions |
| Prediction Drift | Changes in model output distributions |
| Model Performance | Precision, recall, NDCG, or other relevant metrics |
| Infrastructure | CPU, GPU, memory, throughput |
| Latency | Average, p95, p99 response time |
| Reliability | Error rate, timeouts, service availability |
| Business Outcomes | Revenue, fraud losses, engagement, conversion |
Tools such as Evidently, WhyLabs, Prometheus, and Grafana can support different parts of production monitoring.
Important: Drift does not automatically mean that a model has become inaccurate. It is a signal that should trigger investigation, validation, or additional monitoring.
7. A/B Testing: Measuring Real-World Model Impact
Offline metrics help compare models, but they cannot fully predict how users will respond to a new model.
A/B testing evaluates model changes through controlled experiments.
Suppose an e-commerce platform wants to compare two recommendation systems:
- Model A: Existing recommendation engine.
- Model B: Newly trained recommendation engine.
The platform randomly assigns eligible users to two groups.
Eligible Users
|
v
Random Assignment
/ \
v v
Group A Group B
| |
v v
Model A Model B
| |
v v
User Actions and Outcomes
| |
+----+----+
|
v
Statistical Analysis
|
v
Final Decision
Possible measurements include:
- Click-through rate
- Conversion rate
- Average order value
- Revenue per user
- Watch time
- Retention
- User satisfaction
A model should not be declared successful based only on an increase in clicks if it also causes a decrease in long-term satisfaction or business value.
Experiments should define a primary metric, guardrail metrics, an appropriate randomization unit, and a sufficient sample size before launch.
8. Comparing the Three ML System Architectures
Although recommendation, fraud detection, and search ranking all use machine learning, their engineering priorities are different.
| Dimension | Recommendation | Fraud Detection | Search Ranking |
|---|---|---|---|
| Main Goal | Personalize suggestions | Detect suspicious activity | Return relevant results |
| Input | User, item, context | Transaction and behavior | Query and documents |
| First Stage | Candidate retrieval | Feature extraction | Candidate retrieval |
| Model | Two-Tower, GBDT, DNN | Classification, anomaly detection | BM25, LambdaMART, neural ranking |
| Output | Ranked recommendations | Risk score and action | Ranked search results |
| Key Metrics | Recall@K, NDCG, CTR | Precision, Recall, PR-AUC, fraud loss | NDCG, MRR, MAP |
| Major Challenge | Cold start and feedback loops | Adversarial drift and false positives | Query understanding and relevance |
| Typical Serving | Online and batch | Primarily real-time | Online |
8.1 Which Architecture Requires What?
Recommendation Systems
Prioritize:
- Fast candidate retrieval
- Efficient vector search
- Personalized ranking
- Diversity and freshness
- Feedback-loop management
Fraud Detection Systems
Prioritize:
- Low-latency feature access
- Reliable transaction processing
- Cost-sensitive decisions
- Explainability and auditability
- Adversarial monitoring
Search Ranking Systems
Prioritize:
- Query understanding
- High-recall retrieval
- Accurate ranking
- Fresh indexing
- Relevance and diversity
9. Practical ML System Design: An Interview Framework
Machine learning system design interviews evaluate much more than algorithm knowledge.
They test whether an engineer can translate a business problem into a scalable, reliable, and measurable architecture.
A useful framework is:
Step 1: Clarify the Problem
Understand:
- What problem are we solving?
- Who are the users?
- What is the expected output?
- What is the business objective?
- What are the latency and availability requirements?
Step 2: Define Success Metrics
Choose offline and online metrics.
Examples:
- Recommendation: Recall@K and NDCG@K.
- Fraud: Precision, recall, fraud loss, and false decline rate.
- Search: NDCG, MRR, and query success rate.
Step 3: Estimate Scale
Determine:
- Daily active users
- Requests per second
- Dataset size
- Number of items or documents
- Average feature size
- Peak traffic
- Retention requirements
Step 4: Design Data Architecture
Identify:
- Data sources
- Event ingestion
- Data validation
- Feature engineering
- Offline storage
- Online feature access
Step 5: Select the ML Approach
Choose algorithms based on the problem, available data, latency, interpretability, and operational constraints.
Step 6: Design Model Serving
Decide between:
- Real-time inference
- Batch inference
- Streaming inference
Also define caching, scaling, fallbacks, timeouts, and model versioning.
Step 7: Design Monitoring
Track:
- Data quality
- Model performance
- Drift
- Latency
- Reliability
- Business outcomes
Step 8: Plan Retraining and Rollback
Define when the model should be retrained, how new versions will be evaluated, and how to return to a previous stable version if production performance degrades.
10. Common ML System Design Mistakes
Even a technically strong ML model can fail because of poor system architecture.
1. Optimizing Only Model Accuracy
A model with excellent offline accuracy may have unacceptable latency or poor real-world business impact.
2. Ignoring Data Leakage
Training features must only use information available at the prediction time.
3. Using the Same Architecture for Every Problem
Recommendation, fraud detection, and search ranking have different objectives and serving requirements.
4. Ignoring Tail Latency
A low average response time does not guarantee that p95 or p99 latency is acceptable.
5. Forgetting Fallback Mechanisms
If the feature store or model service becomes unavailable, the application needs a safe fallback strategy.
Examples:
- Recommendation: Show popular or recently viewed items.
- Fraud: Apply a risk-appropriate fallback policy or request additional authentication.
- Search: Fall back to lexical retrieval if semantic ranking is unavailable.
Fraud fallbacks require particular care: automatically approving every transaction during an outage can create unacceptable financial risk.
6. Ignoring Model Drift
Production data changes. A model must be continuously monitored and periodically evaluated.
7. Treating Clicks as Perfect Labels
Clicks, purchases, and other interactions are influenced by position, presentation, and exposure. Training data must account for these biases where possible.
8. Deploying Without Rollback
Every production model release should have versioning, validation, and a rollback strategy.
11. Best Practices for Production ML System Design
- Separate candidate retrieval from expensive ranking.
- Keep feature definitions consistent between training and inference.
- Use point-in-time-correct training data.
- Design latency budgets for the complete request, not just model inference.
- Monitor p95 and p99 latency.
- Evaluate models using metrics that reflect business objectives.
- Use A/B testing or controlled experiments before broad deployment.
- Monitor data drift, prediction drift, and model quality.
- Implement safe fallbacks and rollback procedures.
- Protect feature stores, APIs, and model endpoints with appropriate access controls.
- Version datasets, features, models, and experiments.
- Account for privacy, security, explainability, and regulatory requirements.
Conclusion
Machine learning system design is the engineering discipline that transforms trained models into reliable production applications.
Recommendation systems use multi-stage retrieval and ranking to personalize content at scale. Fraud detection systems combine real-time features, risk models, and decision policies to prevent financial losses. Search ranking systems combine lexical and semantic retrieval with sophisticated ranking models to deliver relevant results.
Although their architectures differ, they share common engineering foundations:
- Reliable data pipelines
- Consistent feature management
- Scalable model serving
- Strict latency and reliability requirements
- Continuous monitoring
- Experimentation and feedback loops
The most important lesson is that a successful production ML system is not defined only by how accurately its model predicts. It is defined by how effectively the entire system delivers useful, timely, reliable, and measurable outcomes.
Understanding these architectures is an essential step toward becoming a machine learning engineer capable of building real-world AI systems.
Frequently Asked Questions (FAQs)
1. What is ML System Design?
ML System Design is the process of designing end-to-end machine learning applications, including data pipelines, feature engineering, model training, deployment, serving, monitoring, and retraining.
2. What is a multi-stage recommendation system?
It is an architecture that first retrieves a small set of candidates from a large catalog, ranks them using a more sophisticated model, and then re-ranks them using additional constraints.
3. What is the difference between a feature store and a database?
A database stores and retrieves general application data. A feature store manages machine learning features with additional support for feature definitions, historical training data, online serving, and training-serving consistency.
4. Why is real-time fraud detection difficult?
Fraud detection must process transactions quickly while handling rare positive cases, changing fraud patterns, adversarial behavior, delayed labels, and the financial cost of incorrect decisions.
5. What is the difference between candidate retrieval and ranking?
Candidate retrieval quickly identifies potentially relevant items from a large collection. Ranking uses richer features and more computationally expensive models to order those candidates.
6. What is model drift?
Model drift is a broad term for changes that can make a deployed model less reliable. Data drift changes the input distribution, while concept drift changes the relationship between inputs and target outcomes.
7. What is A/B testing in machine learning?
A/B testing compares two system or model versions using separate user groups to measure their real-world impact on predefined metrics.
8. Which tools are used for production ML systems?
Common tools include Python, Scikit-learn, PyTorch, TensorFlow, Kafka, Spark, Redis, FAISS, MLflow, Feast, Docker, Kubernetes, Prometheus, and Grafana. The appropriate stack depends on the system's requirements.
9. Is high model accuracy enough for production deployment?
No. A production model must also meet requirements for latency, reliability, scalability, data quality, security, monitoring, and business performance.
10. What should I study after learning ML System Design?
A useful next topic is MLOps: Model Deployment, Versioning, Monitoring & CI/CD, which explains how production ML systems are built, released, maintained, and improved over time.