Machine Learning Engineer Interview Questions: Coding, ML & System Design

Categories:
Written by:Sara Nobrega
From recommendation systems to regression and model evaluation, tackle real machine learning interview questions from Meta, Uber, Google, and more.
Machine learning engineers work across the whole machine learning lifecycle. They prepare data, engineer features, develop models, evaluate them, deploy them, run the production pipelines around them, and monitor what happens after launch. A single role can touch all of those steps in the same week.
Interviews follow the same spread. One loop can include a Python problem, a statistics question, a dataset-construction task, a model evaluation discussion, and a system design prompt. That mix of coding, machine learning, data, statistics, and system design is why preparation for this role feels wider than preparation for a pure data science role.
The questions below progress from beginner concepts to intermediate and advanced production scenarios.
Real StrataScratch interview questions appear throughout, so you can read the concept, see how a company asked it, and solve the problem yourself in the code editor. We cover 44 questions in total and link to deeper guides on dataset construction, system design, and LLMs where a topic needs more room.
What to Expect in a Machine Learning Engineer Interview
Interview format varies a lot by company, team, and seniority. A startup might run one long technical conversation. A large company might run 4 to 6 separate rounds. The areas below are the ones that come up most often.

Coding Rounds: Python, SQL, and Data Manipulation
Expect Python and SQL problems, usually centered on data manipulation: joins, aggregations, window logic, string handling, and time-based calculations. Some companies add algorithms and data structures where the role is closer to software engineering.
Machine Learning: Models, Training, and Evaluation
You should be able to explain how models learn, what features are, how training works, how to evaluate a model, and how to spot overfitting. Interviewers care about reasoning, so a definition without a trade-off rarely scores well.
Data: Building Training Sets From Raw Production Data
Many ML engineer interviews ask you to construct a training dataset from raw tables.
That means choosing feature windows, defining labels, avoiding leakage, joining tables at the right grain, and validating the result before any model is trained.
We introduce these ideas in this guide. For the full walkthrough, including a churn dataset built step by step in SQL, see How To Pass Data Interviews for Machine Learning Engineer Roles.
Statistics: Probability, Experiments, and Model Evaluation
Probability, distributions, hypothesis testing, and experimentation show up both as direct questions and inside model evaluation. For more practice, see our Probability and Statistics Interview Questions.
ML System Design: End-to-End Production Systems
Senior and production-oriented roles often include a design round: build a recommendation system, a fraud detector, or a monitoring setup, and explain the data, features, model, serving, and monitoring choices.
AI and LLMs: Embeddings, RAG, and Applications
Some modern ML engineer roles also test embeddings, retrieval-augmented generation (RAG), and AI application knowledge. Others never mention them. Check the job description before deciding how much time to spend here.
Beginner Machine Learning Engineer Interview Questions
These ten questions cover the core concepts every interviewer assumes you know. Each theory answer follows the same order: define, explain, give an example, and state the trade-off.
![[[alt:"Beginner Machine Learning Engineer Interview Questions"]]](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Foaglaatp%2Fproduction%2F76f8704d5ecdad3400004c6fc1a457178d97055d-2048x914.jpg&w=3840&q=75)
The Difficulty label on each question is our own tier for preparation. The platform rates its questions separately, and the practice table near the end shows those ratings.
1. What Is Machine Learning?
Difficulty: Beginner
Type: Theory
Machine learning is a way of building systems that learn patterns from data and use them to make predictions or decisions on new data, without a programmer writing explicit rules for every case.
A Salesforce question that asks for exactly this explanation in plain language.
Machine Learning Concept
Last Updated: February 2019
Explain Machine Learning concept to non-technical people.
Five terms carry the whole answer.
- Training data is the set of examples the model learns from. Features are the input columns describing each example.
- Labels are the known outcomes, present in supervised learning.
- The model is the function with adjustable parameters that maps features to an output.
- Predictions are the model's outputs on data it has not seen.

A spam filter shows all five and the training data is a set of past emails. The features are things like sender domain and word counts and the label is spam or not spam. The model learns which feature patterns go with each label, and its predictions are scores for new emails.
The trade-off is that the model only knows what the data shows. If the training emails never included a new type of phishing message, the model has no reason to flag it, and a simple rule might do better until enough examples exist.
2. What Is the Difference Between Supervised and Unsupervised Learning?
Difficulty: Beginner
Type: Theory
Supervised learning trains on data that has labels, so the model learns a mapping from features to a known outcome. Unsupervised learning trains on data with no predefined labels, so the model looks for structure on its own.
This SAP question asks for the difference and examples of both.
Supervised and Unsupervised Machine Learning
Last Updated: January 2021
What is the difference between supervised and unsupervised machine learning and give examples of both?
Supervised learning splits into two families.
Classification predicts a category, such as whether an email is spam. Regression predicts a number, such as a house price. Common algorithms include logistic regression, decision trees, and support vector machines.
Unsupervised learning has no target column. Clustering groups similar rows, such as customers with similar purchase patterns. Dimensionality reduction, such as PCA, compresses many columns into fewer ones while keeping most of the variation.

In practice, a retailer might use supervised learning to predict which customers will cancel (labels come from past cancellations) and unsupervised learning to segment customers before a marketing campaign (no labels exist).
The trade-off is labeling cost against evaluation difficulty. Supervised learning needs labeled data, which can be slow or expensive to collect. Unsupervised learning skips labeling, but you cannot measure accuracy against a ground truth, so judging whether a clustering is useful takes business judgment.
3. What Is the Difference Between Regression and Classification?
Difficulty: Beginner
Type: Theory
Regression predicts a continuous numeric value. Classification predicts a category or class.

Belvedere Trading asked candidates to explain regression to an 8-year-old. The interviewer wants to see whether you can reduce the idea to its core: use past examples to predict a number.
Regression Definition
Last Updated: April 2021
Find the words to explain Regression to an 8 years old.
Axa asked for the same distinction in a Classification vs Regression Task question.
Regression and Classification Problems
Last Updated: January 2020
What is the difference between regression and classification problems, and how can you convert a regression problem into a classification problem?
Take delivery time. Predicting "32 minutes" is regression. Predicting "late or on time" is classification. Both come from the same data, and the choice depends on what the business does with the answer.

The trade-off sits in that choice. Turning a number into buckets simplifies the problem and loses information: a 5-minute delay and a 55-minute delay both become "late". One naming trap is worth knowing. Logistic regression is a classification algorithm despite its name.
4. What Is Overfitting?
Difficulty: Beginner
Type: Theory
Overfitting happens when a model learns the training data too closely, including its noise, and performs worse on new data than its training results suggest.
The signal is a gap: training performance keeps improving while validation performance flattens or drops. That gap measures how poorly the model generalizes. Model complexity drives it: a very flexible model has enough capacity to memorize individual training rows.

Pearson asked how to make sure you are not overfitting while training a model.
Overfitting While Training Model
Last Updated: February 2021
How to make sure you are not overfitting while training a model?
Five fixes cover most answers:
- Collect more training data.
- Add regularization, which penalizes large weights.
- Use cross-validation to get a more reliable estimate.
- Choose a simpler model or limit its depth.
- Use early stopping, which halts training when validation error stops improving.
Say a decision tree with no depth limit scores 100% on training data and noticeably lower on validation data. Limiting the depth will lower the training score and usually raise the validation score.
Each fix has a cost. Regularization adds bias. Early stopping needs a held-out validation set. More data takes time and money. A good answer names which fix you would try first and why.
Example interview question: Your decision tree achieves 100% accuracy on the training set but only 75% on the validation set. What would you try first to reduce overfitting, and why?
Good answer: I would first limit the tree's maximum depth because an unrestricted tree can memorize noise in the training data. I would use cross-validation to select an appropriate depth and check whether validation performance improves. This is a good first step because it directly addresses model complexity without requiring additional data.
5. What Is Underfitting?
Difficulty: Beginner
Type: Theory
Underfitting happens when a model is too simple to capture the pattern in the data, so it performs poorly on both the training set and new data.
Compare it with overfitting by reading the two error rates together:

A linear model fit to a clearly curved relationship underfits. It misses the pattern on training data and on every other sample.

The usual fixes are the opposite of the overfitting fixes: add informative features, use a more flexible model, reduce regularization, or train longer. The trade-off is that every step toward flexibility moves you closer to overfitting, so you check validation errors after each change.
6. What Are the Training, Validation, and Test Sets?
Difficulty: Beginner
Type: Theory
The training set fits the model's parameters, the validation set guides decisions such as hyperparameters and model choice, and the test set gives a final, unbiased estimate of performance.
Allstate asked about the purpose of hold-out procedures such as train/test split and cross-validation.
Model Evaluation Procedures
Last Updated: January 2020
What is the purpose of model evaluation procedures that "hold out" data, like train/test split and cross-validation?
A common split is 70/15/15 or 60/20/20, depending on dataset size.

Say you try 50 hyperparameter settings and pick the one with the best validation score. That choice already uses the validation set, so its score is slightly optimistic. The test set stays untouched until you have a final candidate.
The warning interviewers listen for: never evaluate against the test set repeatedly while developing. Each look turns it into another validation set, and the final number stops being an honest estimate.
The trade-off is data. Holding out 30% of a small dataset leaves less to train on, which is where cross-validation helps. For time-dependent data, split by time instead of randomly, so the model never trains on the future.
7. What Is Cross-Validation?
Difficulty: Beginner
Type: Theory
Cross-validation estimates how well a model generalizes by training and validating it several times on different splits of the same data and averaging the results.
IBM asked what cross-validation is and what advantage it gives.
Cross-Validation
Last Updated: January 2021
What is cross-validation? What advantage does it give?
There are several cross-validation methods, including k-fold, stratified k-fold, group k-fold, leave-one-out, and time-series cross-validation. Each addresses different data characteristics. Standard k-fold is one of the most commonly used and taught methods because it provides a good balance between computational efficiency and reliable performance estimation.
In k-fold cross-validation, you split the data into k equal folds.

You train on k-1 folds, validate on the remaining one, and repeat until every fold has served as the validation set. The average score is the estimate. With 5 folds, every row is used for validation exactly once and for training 4 times, which gives a more stable estimate than one split, especially on small datasets.
It is not always appropriate:
- Time series: Random folds put future rows in the training set. Use forward-chaining splits, where each fold trains on the past and validates on the next period.
- Grouped data: If one user has many rows, a random split puts that user in both training and validation. Use group k-fold.
- Imbalanced labels: Use stratified folds so each fold keeps the class ratio.
The cost is compute: k-fold trains the model k times. For a large dataset or an expensive model, a single well-designed hold-out split is often enough.
8. What Is a Confusion Matrix?
Difficulty: Beginner
Type: Theory
A confusion matrix is a table that compares a classifier's predictions with the actual labels, splitting results into true positives (TP), false positives (FP), false negatives (FN), and true negatives (TN).
AXA asked why a confusion matrix is useful for evaluating a classifier.
Confusion Matrix
Last Updated: January 2020
Why is a confusion matrix useful for evaluating the performance of a classifier?

The matrix matters because one accuracy number hides which mistakes the model makes. Take 10,000 transactions, 100 of them fraud. A model flags 120 and catches 80 of the 100.
That gives TP = 80, FP = 40, FN = 20, TN = 9,860.

Accuracy is (80 + 9,860) / 10,000 = 99.4%.
Precision is 80 / 120 = 66.7%. Recall is 80 / 100 = 80%. The 99.4% looks excellent, while a third of the flags are wrong and a fifth of the fraud gets through.
Those two error types cost different amounts. A false negative is fraud that gets paid. A false positive is a blocked customer and a review. Interviewers want you to say which one costs more in the scenario they gave you. A common mistake we see candidates make here is stopping at the four cells without connecting them to cost.
Those two error types have different business costs. A false negative means missed fraud, while a false positive means a legitimate transaction is flagged.
Suppose each missed fraud costs €500 and each false positive costs €20. Our 20 false negatives would cost €10,000, compared with €800 for the 40 false positives.
In this scenario, reducing false negatives matters more. We could lower the classification threshold to catch more fraud, even if it increases false positives. The key is to connect each error type to its business cost before deciding which metric to prioritize.
9. What Is the Difference Between Precision and Recall?
Difficulty: Beginner
Type: Theory
Precision is the share of predicted positives that are truly positive. Recall is the share of actual positives that the model finds.

Intuit asked for the formulas directly.
Precision and Recall
Last Updated: October 2021
Provide formulas for precision and recall.
The right priority depends on the business problem. For a fraud model that blocks card payments, false positives anger customers, so teams often push precision up. For a screening model that routes patients to a follow-up test, a missed case is far worse than an extra test, so recall comes first.

A classification model often outputs a probability between 0 and 1. The decision threshold determines when that probability is high enough to classify a case as positive. For example, with a threshold of 0.5, a transaction with a fraud probability of 0.7 is flagged as fraud.
Lowering the threshold catches more potential fraud (higher recall), but can increase false positives and reduce precision. Raising it generally does the opposite. The best threshold depends on the business cost of each error.
The trade-off lives in the decision threshold. Lowering it catches more positives (higher recall) and flags more wrong cases (lower precision). In an interview, state the cost of each error before you name a metric.
10. What Is Feature Engineering?
Difficulty: Beginner
Type: Theory
Feature engineering is the process of transforming raw data into inputs that help a model learn the pattern you care about.
Box asked what feature engineering is and what its goal is.
Feature Engineering
Last Updated: January 2020
What is feature engineering, and what is the goal of feature engineering?
Four techniques cover most of what interviewers expect:
- Aggregation: orders in the last 30 days, average order value, total support tickets.
- Encoding: turning categories such as country or plan type into numbers, for example with one-hot encoding.
- Time-based features: day of week, hour, days since last login.
- Interaction features: combinations such as price multiplied by quantity, or sessions per active day.

For a churn model, "days since last session" usually says more than "total sessions ever", because it measures recency. You only know that if you understand both the data and the business. That is why interviewers ask you to justify each feature.
The trade-off: every feature must also be computed in production, at prediction time, from data that exists at that moment. A feature that is hard to compute live, or that uses future information, can make a model worse in production than the offline metrics promised. We come back to that in the advanced section.
Intermediate Machine Learning Engineer Interview Questions
This section combines ML theory with data and implementation problems.
Theory questions keep the define, explain, example, trade-off order.
Data problems follow entity, prediction point, feature window, label window, and validation.
Coding questions follow the practical format: clarify, explain the approach, code, test, and discuss complexity.

11. What Is Data Leakage?
Difficulty: Intermediate
Type: Data Problem
Data leakage occurs when information that would not be available at prediction time is accidentally included in model training, causing evaluation results to look better than the model will perform in production.
Take a churn model. The prediction date is January 31, 2025.
The feature window is the 90 days before that date, from November 2, 2024, to January 31, 2025. This is the period from which we collect customer activity data to make the prediction.
The label window is the following 30 days, from February 1 to March 2, 2025. This is the period in which we observe whether the customer actually churned.
The feature window is the 90 days before it, from November 2, 2024 to January 31, 2025. The label window is the next 30 days, from February 1 to March 2, 2025. The label says whether the user churned in that window.

Any activity after January 31 cannot be a feature. A column such as support_tickets_total computed over all of February would count tickets the model could not have seen on January 31. A plan_status column that the billing system updated after the user cancelled leaks the answer directly.
Leakage also happens in preprocessing. If you fit a scaler or an imputer on the full dataset before splitting, statistics from the validation rows reach the training step. Fit on training data only, then apply to the rest.
Leakage inflates offline metrics, making the model appear better than it actually is. For example, an AUC (Area Under the ROC Curve) of 0.99 on a difficult classification problem should raise suspicion. AUC measures how well a model distinguishes positive from negative cases, with 0.5 indicating random performance and 1.0 perfect discrimination.
The trade-off is between using more predictive features and ensuring realistic evaluation. Excluding information unavailable at prediction time may lower your reported scores, but makes them more representative of how the model will perform in production.
12. How Would You Build a Labeled Training Dataset?
Difficulty: Intermediate
Type: Data Problem
Build it in this order:
Entity → Prediction point → Feature window → Label window → Validation

1. Entity
What does one row represent? Define the unit of observation, such as a user, customer, or transaction. For churn prediction, each row represents one eligible user at a specific prediction point.
2. Prediction Point
When is the prediction made? Choose the exact date or timestamp at which the model would make its prediction. This establishes the boundary between information available to the model and future outcomes it must predict.
3. Feature Window
What information can the model use? Define the historical period used to calculate input features, such as the number of sessions or purchases in the previous 90 days. Only information available at or before the prediction point can be included to prevent data leakage.
4. Label Window
What outcome are we predicting? Define the future period in which the target outcome is measured, such as the 30 days following the prediction point. For churn, assign a label of 1 if the user has no sessions during that period, and 0 otherwise.
5. Validation
Is the dataset reliable? Check that the dataset has the expected number of rows, no unintended duplicates, reasonable feature ranges, and acceptable null rates. Examine the label distribution and verify that no features contain information from the future, which would artificially inflate model performance.
Decide what one row represents, fix the date the prediction is made, summarize behavior before that date as features, and use a future period after it to define the outcome. On a timeline, the feature window ends at the prediction point and the label window starts right after it.
For churn, the entity is a user, so there is one row per user. The prediction point is a fixed date. The feature window summarizes behavior before that date, such as sessions and orders in the previous 90 days. The label window looks forward, and the label is 1 if the user had no session in the next 30 days.
Two decisions come before any SQL. First, define the label precisely. Churn can mean no login, no purchase, or a cancelled subscription, and each gives a different dataset. Second, state the grain, so you can check later that the row count equals the number of eligible users.
Validation closes the loop: row count, label balance, null rates, and feature ranges. A churn question from Robinhood covers how to define and predict churn.
Churn
Last Updated: January 2021
What is churn? How can we predict if a person is churning?
13. How Do You Handle Missing Data?
Difficulty: Intermediate
Type: Theory
You have four main options: remove the rows, impute the values, add a missing-value indicator, or use a model that handles missing values natively. The right one depends on why the data is missing.
IBM asked this directly in an interview question:
Dealing with Missing Values
Last Updated: March 2021
How do you deal with missing values?
- Remove rows or columns: Reasonable when few rows are affected and the loss is random.
- Impute: Fill with the mean, median, mode, or a model-based estimate. Use the mean for numerical data without strong outliers, the median for skewed distributions or data with outliers, and the mode for categorical variables. Model-based imputation uses other features to estimate missing values and can capture more complex relationships, but adds complexity and computational cost.
- Add an indicator: A separate
is_missingcolumn lets the model use the fact that a value was missing. - Use model-specific handling: Gradient boosting libraries such as XGBoost learn a default direction for missing values. Linear models need values filled in first.

Statisticians separate three causes: missing completely at random, missing depending on other observed columns, and missing depending on the unobserved value itself. Say income is blank more often for high earners. Mean imputation then pulls those users toward the middle and biases the model.
The trade-off: dropping rows throws away data and can bias the sample, imputation shrinks variance, and indicators add columns. Whatever you choose, fit the imputer on training data only, or you create leakage.
14. How Do You Handle Imbalanced Datasets?
Difficulty: Intermediate
Type: Theory
Handle imbalance with four tools: resampling, class weights, threshold adjustment, and metrics that reflect the rare class.
HubSpot asked how to solve imbalanced data issues.
Imbalanced Data Issues
Last Updated: February 2020
How do you solve imbalanced data issues in Machine learning?
Accuracy misleads here. If 1% of transactions are fraud, a model that always predicts "not fraud" is 99% accurate and catches nothing.
- Resampling: Oversample the minority class (including synthetic methods such as SMOTE) or undersample the majority class.
- Class weights: Tell the loss function that a missed fraud case costs more than a false alarm. No data is added or removed.
- Threshold adjustment: Train normally, then move the decision threshold to hit a target recall or precision.
- Better metrics: Use precision, recall, F1, and PR-AUC instead of accuracy.

The trade-offs are specific.
Resample only the training split. If you oversample before splitting, copies of the same row land in both training and validation and the metrics inflate. Resampling also distorts predicted probabilities, so recalibrate them if the business reads the score as a probability.
Class weights avoid the duplicate-row problem, which is why we often try them first. They shift predicted probabilities too, so recalibrate with either approach if the score is read as a probability.
15. How Do You Choose the Right Evaluation Metric?
Difficulty: Intermediate
Type: Theory
Choose the metric from the consequences of errors in the business problem. The model type narrows the list, and the cost of each mistake picks from it.

Google asked what the F1 score is and how to calculate it.
Calculating F1 Score
Last Updated: February 2023
What is the F1 score, and how to calculate it?
F1 is the harmonic mean of precision and recall:
With the fraud example from question 8 (precision 66.7%, recall 80%), F1 is about 0.73.

The trade-off: F1 weights precision and recall equally, which may not reflect real business costs.
ROC-AUC (Area Under the Receiver Operating Characteristic Curve) measures how well a model distinguishes between positive and negative classes across classification thresholds. PR-AUC (Area Under the Precision-Recall Curve) measures the trade-off between precision and recall and is often more informative for heavily imbalanced datasets, where ROC-AUC can appear strong despite poor detection of the minority class.
For regression, RMSE (Root Mean Squared Error) penalizes large prediction errors more heavily, while MAE (Mean Absolute Error) treats errors proportionally to their size. For an ETA model where a 30-minute error is especially costly, RMSE may be more appropriate than MAE.
16. What Is Regularization?
Difficulty: Intermediate
Type: Theory
Regularization adds a penalty on model complexity to the training loss, which discourages large weights and reduces overfitting.
Pearson asked what regularization is and which problem it solves.
Regularization
Last Updated: January 2021
What is regularization? Which problem does regularization try to solve?
Two common types of regularization are:
- L1 (lasso): penalizes the sum of absolute weights. It can push weights exactly to zero, so it also performs feature selection.
- L2 (ridge): penalizes the sum of squared weights. It shrinks all weights toward zero without removing any.

Both modify the model's loss function:
Here, λ (lambda) controls how strongly complexity is penalized. It is a hyperparameter chosen through validation or cross-validation, rather than calculated directly from the training data. A larger λ means stronger regularization, typically increasing bias and reducing variance.
For example, with 500 features and 2,000 rows, L1 can help select a smaller subset of relevant features, reducing the risk of overfitting.
The trade-offs: L1 is unstable when features are highly correlated, since it may keep one of them arbitrarily. L2 keeps everything, which is harder to interpret. Both need scaled features, or the penalty falls unevenly across columns. Elastic net mixes the two penalties.
17. What Is the Bias-Variance Trade-Off?
Difficulty: Intermediate
Type: Theory
Bias is an error from a model being too simple to capture the pattern.
Variance is error from a model being too sensitive to the particular training sample. Lowering one usually raises the other.
AXA asked why you should care about it.
Bias-Variance Trade-off
Last Updated: January 2020
With regard to machine learning models, why should I care the about bias-variance trade-off?
High bias means underfitting, and high variance means overfitting. Total expected error splits into bias squared, variance, and irreducible noise. As model complexity grows, bias falls and variance rises, and validation error is lowest somewhere in between.

Learning curves tell you which side you are on. If training and validation errors are both high and close, you have a bias problem, and more data will not help. If training error is low and validation error is much higher, you have a variance problem, and more data or regularization will help.
Ensembles show the trade-off in practice. Bagging, as in random forests, mainly reduces variance. Boosting mainly reduces bias. Knowing which is which is a quick way to show depth.
18. How Do You Choose Between Different Machine Learning Models?
Difficulty: Intermediate
Type: Theory
You choose a model by weighing the data, the accuracy you need, and the constraints of the system that will run it. No single model is best.
N26 asked whether an additional feature improves a gradient boosted model or logistic regression more.
GBM or Logistic Regression
Last Updated: February 2019
Do you think an additional feature improves GBM or Logistic Regression more?
The factors we use:
- Data size: Small datasets favor simpler models. Deep models need a lot of data.
- Feature types: Tabular data with mixed types often suits gradient boosted trees. Images, text, and audio usually need neural networks.
- Accuracy needs: Check how much a complex model gains over a simple one on validation data.
- Interpretability: Regulated or customer-facing decisions may need a model you can explain.
- Training time and inference latency: A model that scores in 5 ms and one that takes 200 ms fit different products.
- Scalability: Consider how training and serving costs grow as data and traffic grow.

Say we need a churn model for a retention team. Tabular data, 50,000 rows, and the team wants to know why users are flagged. We would start with logistic regression as a baseline, then try gradient boosting and keep it only if the lift justifies the loss of simplicity.
On the N26 question, gradient boosting captures non-linear effects and interactions on its own, so a raw extra feature often adds less to it than to logistic regression, where you must supply the non-linearity yourself. A genuinely new signal helps both.
19. Random Forest vs XGBoost: When Would You Use Each?
Difficulty: Intermediate
Type: Theory
A random forest trains many deep trees independently on random samples of the data and averages them. A gradient boosted model such as XGBoost trains shallow trees one after another, with each tree correcting the errors of the previous ones.
Capital One asked for these differences:
Xgboost vs Random Forest
Last Updated: February 2021
What is the difference between a random forest and a gradient boosted tree?

We reach for a random forest as a strong first baseline when we have little time to tune or when labels are noisy. We reach for gradient boosting when we want the best accuracy on tabular data and can afford to tune with early stopping.

Neither choice is final until you check the inference cost. A forest with hundreds of deep trees can be larger and slower to serve than a small boosted model, so compare model size, latency, and accuracy.
20. How Would You Establish a Baseline Model?
Difficulty: Intermediate
Type: Coding and ML Problem
A baseline is the simplest reasonable prediction method, and any proposed model must beat it to justify its complexity. Start simple before proposing anything sophisticated.
Good baselines depend on the task. For classification, predict the majority class or fit a logistic regression. For regression, predict the mean. For forecasting, predict the last observed value, which is called a naive forecast. Without a baseline, a metric like "RMSE of 4.2" has no meaning.

This Uber question builds a naive forecast and measures it with RMSE.
Naive Forecasting
Last Updated: December 2020
Some forecasting methods are extremely simple and surprisingly effective. Naïve forecast is one of them; we simply set all forecasts to be the value of the last observation. Our goal is to develop a naïve forecast for a new metric called "distance per dollar" defined as the (distance_to_travel/monetary_cost) in our dataset and measure its accuracy.
Our dataset includes both successful and failed requests. For this task, include all rows regardless of request status when aggregating values.
To develop this forecast, sum "distance to travel" and "monetary cost" values at a monthly level before calculating "distance per dollar". This value becomes your actual value for the current month. The next step is to populate the forecasted value for each month. This can be achieved simply by getting the previous month's value in a separate column. Now, we have actual and forecasted values. This is your naïve forecast. Let’s evaluate our model by calculating an error matrix called root mean squared error (RMSE). RMSE is defined as sqrt(mean(square(actual - forecast)). Report out the RMSE rounded to the 2nd decimal spot.
Data View
The uber_request_logs table has one row per ride request, with the request date, status, distance, and cost. We build a monthly series from it.
Here is the dataset preview.
Grain (what one output row means): the final answer is a single RMSE value, computed from one row per month.
What the Interviewer Is Testing
This question checks whether you can build a time series, shift it to create a forecast, and evaluate it with a standard error metric. It also tests whether you aggregate in the right order. The metric is distance per dollar, so we sum distance and sum cost for each month first, then divide. Averaging row-level ratios gives a different number from the one the question defines.
Clarify and Plan the Approach
Before coding, we would confirm three things. All rows count, including failed requests. The forecast for a month is the previous month's value. RMSE is the square root of the mean squared difference between actual and forecast. The plan has five steps: extract the month, sum distance and cost by month, compute distance per dollar, shift by one month, and compute RMSE on the months that have a forecast.
Edge Cases and Validation
The first month has no previous month, so it has no forecast and must be excluded from the RMSE. A month with zero cost would divide by zero. To validate, check that the number of scored months is one less than the number of months, that RMSE is non-negative, and that two months of data reproduce a hand calculation. Complexity is linear in the number of rows for the aggregation, plus a sort over the months.

Why This Matters for an ML Engineer
If a trained model cannot beat this RMSE, it adds cost and risk for no gain. Baselines are also the first thing a reviewer asks for in a model proposal.
Solution
1) Build the monthly series and distance per dollar
We convert the request date to a month, sum distance and cost for each month, and divide the sums.
import pandas as pd
import numpy as np
from datetime import datetime
uber_request_logs['month_year'] = pd.to_datetime(uber_request_logs['request_date']).dt.to_period('M')
avg_monthly_dist_per_dollar = uber_request_logs.groupby('month_year')[
['distance_to_travel', 'monetary_cost']].sum().reset_index()
avg_monthly_dist_per_dollar['monthly_dist_per_dollar'] = avg_monthly_dist_per_dollar['distance_to_travel'] / avg_monthly_dist_per_dollar['monetary_cost']2) Shift to create the naive forecast and compute RMSE (final solution)
- The dataset has already been loaded as a pandas.DataFrame.
- print() functions and the last line of code will be displayed in the output.
- In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.
Run the code above to see the output.
21. How Would You Validate a Machine Learning Dataset Before Training?
Difficulty: Intermediate
Type: Data Problem
Validate the dataset against the grain you intended, the label you defined, and the data the model will see in production, before any model sees it.

A common mistake we see candidates make is checking only for nulls and calling the data clean. A table can have zero nulls and still contain duplicated entities or a label that leaked into a feature.
For worked Pandas validation checks on a real churn dataset, see our ML Engineer data interview guide.
22. How Do You Prevent Duplicate Rows When Joining Training Data?
Difficulty: Intermediate
Type: Data Problem
Duplicate rows come from joining tables at different grains. Aggregate every child table to the entity's grain before you join it.
Table grain is what one row in a table represents. A users table has one row per user. An orders table has many rows per user. A support_tickets table also has many rows per user. A one-to-many join repeats the user row once per match.
Join users to both orders and tickets directly, and a user with 3 orders and 2 tickets becomes 6 rows. Sums and counts for that user inflate, and the user is overrepresented in training.
The fix has three parts:
- Aggregate each many-side table to one row per entity first, for example total orders and total spend per user.
- Join the aggregated tables to the entity table, usually with left joins so users with no activity stay in with zeros.
- Deduplicate only if duplicates exist in the source, and say why.

Validate after every join. The row count should still equal the number of distinct entities. Our Premium vs Freemium question from Microsoft is a multi-table join exercise (users, accounts, download facts) where you check the grain of each table before summing.
Premium vs Freemium
Last Updated: November 2020
Find the total number of downloads for paying and non-paying users by date. Include only records where non-paying customers have more downloads than paying customers. The output should be sorted by earliest date first and contain 3 columns date, non-paying downloads, paying downloads. Hint: In Oracle you should use "date" when referring to date column (reserved keyword).
23. Practical Python Interview Question: Words With Two Vowels
Difficulty: Intermediate
Type: Practical
This Google question asks for all words that contain exactly two vowels in either of two word lists.
Words With Two Vowels
Last Updated: January 2019
Find all words which contain exactly two vowels in any list in the table.
Data View
The google_word_lists table has two columns, words1 and words2. Each cell holds several words in one comma-separated string.
Here is the dataset preview.
Grain (what one output row means): one row per distinct word that has exactly two vowels.
What the Interviewer Is Testing
The problem tests string manipulation, splitting list-like fields into rows, deduplication, filtering, and Python fundamentals. The logic is simple. Most of the work is reshaping data, because each cell holds a list stored as text.
Clarify and Plan the Approach
We would ask four questions. Does "two vowels" mean two vowel characters or two different vowels? Is the match case-insensitive? Should a word that appears in both columns be returned once? Are there spaces after the commas? We assume vowel characters, case-insensitive, each word once, and clean data.

The plan: split both columns on commas and explode each into one word per row, combine the two lists, drop duplicates, count vowels in each word, and keep words with a count of 2.
Edge Cases and Validation
Uppercase letters need lowercasing before counting. A word such as "bee" has two vowel characters and qualifies under our assumption, while "audio" has four and does not.
If the lists could contain spaces, strip them first. To validate, take three or four words by hand, count their vowels, and confirm they appear or are excluded correctly. Complexity is linear in the total number of characters.
Why This Matters for an ML Engineer
Text columns that store lists are common in raw production data. Exploding, deduplicating, and counting are the same moves you use when building token counts or categorical features.
Solution
1) Split and explode both columns into one list of distinct words
import pandas as pd
import numpy as np
w1 = google_word_lists.assign(w1=google_word_lists['words1'].str.split(',')).explode('w1')
w1 = w1['w1'].tolist()
w2 = google_word_lists.assign(w2=google_word_lists['words2'].str.split(',')).explode('w2')
w2 = w2['w2'].tolist()
words = w1 + w2
df = pd.DataFrame(words, columns=['word']).drop_duplicates(subset='word')2) Count vowels and keep words with exactly two (final solution)
- The dataset has already been loaded as a pandas.DataFrame.
- print() functions and the last line of code will be displayed in the output.
- In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.
Run the code above to see the output.
24. Practical Recommendation Question
Difficulty: Intermediate
Type: Practical
This Meta question asks for pages a user does not follow but at least one friend does. It is the smallest version of a recommendation system.
Recommendation System
Last Updated: December 2021
You are given the list of Facebook friends and the list of Facebook pages that users follow. Your task is to create a new recommendation system for Facebook. For each Facebook user, find pages that this user doesn't follow but at least one of their friends does. Output the user ID and the ID of the page that should be recommended to this user.
Data View
users_friends links each user to their friends. users_pages lists the pages each user follows.
Here are the two datasets.
Grain (what one output row means): one row per user and recommended page.
What the Interviewer Is Testing
The question tests relationships between entities, candidate generation, filtering, and recommendation logic. The friends' pages are the candidates. Removing pages the user already follows is the filter. In the system design section, the same pattern shows up as candidate generation followed by ranking.
Clarify and Plan the Approach
First, check which side of users_friends is the user. Then the plan: join each user's friends to the pages those friends follow, join the result back to the user's own follows with a left join, keep rows where no match was found, and drop duplicates.
Edge Cases and Validation
A page followed by several friends produces several identical rows, so deduplication is required. Users with no friends or whose friends follow nothing get no recommendations, which is correct. Both tables in the first merge have a user_id column, so pandas renames them user_id_x (the user) and user_id_y (the friend). The final column therefore needs a rename. To validate, pick one user and confirm that no recommended page appears in that user's own follows.
Why This Matters for an ML Engineer
A rule-based candidate generator like this one is also the baseline a learned recommender has to beat. We build the full system on top of it in question 35.

Solution
1) Join each user's friends to the pages those friends follow
friends_pages = users_friends.merge(users_pages, left_on='friend_id', right_on='user_id')
friends_pages = friends_pages[['user_id_x', 'page_id']]2) Remove pages the user already follows and deduplicate (final solution)
- The dataset has already been loaded as a pandas.DataFrame.
- print() functions and the last line of code will be displayed in the output.
- In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.
Run the code above to see the output.
Advanced Machine Learning Engineer Interview Questions
The questions in this section shift from individual algorithms to production ML engineering. Interviewers expect more depth here, so each answer is split into subsections: what the concept is, how it fails, how to handle it, and where the trade-offs sit. The best answers also admit what they would check first and what they would not build.
25. What Is a Training-Serving Skew?
Difficulty: Advanced
Type: Theory
Training-serving skew is a difference between how features are computed, or what data the model sees, during training and during production serving. It makes a model that looks good offline perform worse after deployment.
Where Skew Comes From
Most skew starts with two separate code paths. A data scientist computes avg_order_value over 30 days in a warehouse query that excludes refunds. A backend engineer reimplements it in the serving service and includes refunds. Same feature name, different values.

Other sources:
- Time handling: Training used an end-of-day snapshot, while serving reads the latest value mid-day.
- Defaults and nulls: Training fills missing values with the median, the service sends zero.
- Library and version differences: in encoders, tokenizers, or scalers.
- Joins: A table that changes between training and serving returns different rows.
How to Prevent It

- Shared transformations: Write the feature logic once and use the same code or library for training and serving.
- Feature stores: Centralize feature definitions so offline and online values come from one definition.
- Validation: Log the exact feature values used at serving time and compare their distributions with the training data. Population stability index and Kolmogorov-Smirnov tests are common choices.
- Versioning: Version the feature definitions, the transformation code, and the model together, so you know which versions belong to each other.
Trade-Offs
Shared code limits technology choices, since a batch-only tool cannot serve in real time. A feature store adds infrastructure that a small team may not need. Point-in-time correct training joins, which stop training from seeing values that arrived later, cost compute and engineering time.
Interview Follow-Up
"How would you detect a skew with no labels?" Log serving features, compare them with training distributions, and alert when they move. Replaying logged requests through the training pipeline and diffing the outputs works too.
26. What Is a Feature Store?
Difficulty: Advanced
Type: Theory
A feature store is a system that stores, serves, and manages feature definitions and values, so training and production inference use the same features.

Databricks asked how to design one that serves both offline training and real-time inference.
Feature Store: Offline/Online Consistency
Last Updated: June 2026
Design a feature store that serves both offline model training and real-time inference. How do you keep the features a model sees at inference time consistent with what it saw in training?
How to Design a Feature Store
A feature store needs two storage layers connected by consistent feature definitions:
- Offline store: Keeps historical feature values for model training. Use point-in-time joins to ensure the model only sees information available at each prediction date.
- Online store: Keeps the latest feature values for fast lookups during real-time inference, often using a low-latency database such as Redis.
- Shared feature pipeline: Computes features using consistent definitions and updates both stores, typically through batch or streaming jobs.
- Consistency checks: Compare offline and online feature values for the same entities and timestamps to detect training-serving skew.
For example, a churn model might calculate days_since_last_login. During training, it retrieves historical values from the offline store. In production, it retrieves the latest value from the online store. Both use the same feature definition, preventing differences in how the feature is calculated.
What a Feature Store Does
It centralizes feature definitions, so the logic for days_since_last_login lives in one place.
It keeps an offline store with historical values for building training sets and an online store with the latest values for low-latency lookup at prediction time. Teams reuse features and skip rebuilding them, and consistency between training and serving follows from the single definition.
Offline and Online Features

A materialization job keeps the online store current from the same definitions.
When You Don't Need One
Many ML systems run well without a feature store. One model with a handful of features, scored in a nightly batch, rarely needs one. A shared SQL view or a shared library gives you consistency at a fraction of the cost.
Failure Modes
Stale online features cause skew in a different way: the store holds yesterday's value while training assumed fresh ones. Backfilling history for a new feature can be expensive. Point-in-time bugs, such as joining a feature value that arrived after the label date, bring leakage back in.
27. What Is the Difference Between Batch and Online Inference?
Difficulty: Advanced
Type: Theory
Batch inference scores many records on a schedule and stores the results. Online inference scores a single request in real time as it arrives.
Waymo asked when each is the right choice and what breaks if you pick the wrong one.
Real-Time vs. Batch Scoring
Last Updated: March 2026
Compare real-time scoring and batch scoring for serving model predictions. When is each the right choice, and what breaks if you pick the wrong one?
Comparison

Choosing Between Them
Ask what the prediction is used for and how fast the input changes. If a decision happens on a schedule, such as a weekly campaign list, a batch is simpler and cheaper. If the decision happens inside the user's request and depends on what the user just did, you need online.

What Breaks When You Choose Wrong
Batch fraud scoring means a stolen card can be used many times before the next job runs. Online scoring for weekly churn means paying for an always-on service, monitoring its latency, and keeping an online feature store, with no benefit. Neither mistake shows up in offline metrics, so you have to catch it at design time.
Hybrid Designs
Many systems precompute slow, heavy features in batch and combine them with a few real-time features at request time. That keeps online latency low while still reacting to recent behavior.
28. How Do You Deploy a Machine Learning Model?
Difficulty: Advanced
Type: Theory
Deployment moves a validated model through a controlled lifecycle:
Model → validation → model registry → deployment → serving → monitoring.
Each step has a gate, and each deployed version can be rolled back.

The Lifecycle
1. Model: Train and save the model.
First, train a model using historical data. Once training is complete, save the model artifact, including its learned parameters and any preprocessing components required to make predictions. For example, an XGBoost classifier might be trained to predict whether a customer will churn.
2. Validation: Check whether the model is ready for production.
Evaluate the model on unseen data using appropriate metrics, such as precision, recall, F1-score, or RMSE. Compare its performance against a baseline or the currently deployed model. Also check for data leakage, unexpected predictions, and whether the model meets business requirements. Only models that pass the validation criteria should proceed.
3. Model Registry: Store and track approved versions.
Register the validated model in a central system, such as MLflow Model Registry or Azure ML. The registry tracks model versions, artifacts, performance metrics, and metadata. This makes it possible to identify which model is deployed, reproduce previous experiments, and restore an earlier version if necessary.
4. Deployment: Move the model into a production environment.
Package the model with its dependencies and configure the infrastructure required to run it. For example, deploy the model as a containerized application on a cloud service or managed inference endpoint. Before directing production traffic to it, verify that the deployment loads correctly and accepts valid inputs.
5. Serving: Make predictions available to applications.
Once deployed, the model starts processing new data. In real-time serving, an application sends an HTTP request to an API endpoint and receives a prediction. In batch serving, the model processes many records on a schedule and stores the predictions for later use. Deployment makes the model available; serving is the actual process of generating predictions.
6. Monitoring: Check whether the model continues to perform correctly.
Track technical metrics such as latency, error rates, and resource usage, alongside ML metrics such as prediction distributions, data drift, and model accuracy when ground-truth labels become available. If performance deteriorates, the team can investigate, retrain, or roll back to a previous stable version.
Databricks asked how to design a model registry that tracks what is serving and supports rollback.
Model Registry & Rollback
Last Updated: September 2026
Design a model registry that tracks what's currently serving in production and supports rolling back a bad deployment. What metadata does a registry entry need to make rollback safe and fast?
After training, the model is validated against a holdout set and against the currently serving model. If it passes, it is registered, deployed to a serving environment, and monitored. A new version enters production only after it clears the validation gate.
What the Registry Stores
A registry entry should hold enough to reproduce and revert a model:
- the model version and its artifact location
- the training data snapshot or query, and the code commit
- the feature definitions and schema it expects
- offline metrics and who approved it
- its current stage, and which version it replaced
- The last item makes rollback fast: you know exactly which version to restore.
How to Design a Model Registry That Supports Rollback
A model registry needs to track not only model versions but also which version is currently serving production traffic.
- Register models: Store each version with its artifacts, training data reference, code commit, feature schema, performance metrics, and approval status.
- Track deployments: Maintain a record linking each production endpoint to its deployed model versions and traffic allocation. For example, version 12 serves 100% of traffic, while version 11 remains available as a fallback.
- Control releases: Validate new versions before deployment, then gradually shift traffic using canary deployments while monitoring performance.
- Support rollback: If version 12 fails, redirect traffic to the healthy deployment running version 11, verify recovery, and update the deployment records.
This design provides traceability, identifies exactly which model is serving, and enables controlled rollback without retraining.

Release Controls
Versioning gives every model an identity. Rollback restores the previous version when metrics drop. Canary deployment sends a small share of traffic to the new version first. Shadow deployment runs the new model on live traffic without acting on its output. Question 33 covers how to sequence them.
Trade-Offs
More gates mean safer releases and slower iteration. A team shipping a model weekly needs automated gates. A team shipping twice a year can afford manual review. Match the process to the cost of a bad release.
29. How Do You Monitor a Machine Learning Model in Production?
Difficulty: Advanced
Type: Theory
You monitor a production model at three layers: system health, model behavior, and business outcomes. A model can pass every system check and still make wrong predictions, so each layer catches failures the other two miss.
Scale AI asked how to monitor a model when ground-truth labels take weeks to arrive.
Monitoring Without Fast Labels
Last Updated: August 2026
You're monitoring a production model, but ground-truth labels for its predictions take weeks to arrive. Design a monitoring approach that can catch a problem before you have labels to confirm it.
Explanation

System metrics are the same ones any production service has: latency at p50 and p99, throughput, error rate, availability, and resource use. A healthy service can still return bad predictions, and these metrics will not show it.
ML metrics cover what the model sees and says. Track feature distributions against the training baseline, null rates and out-of-range values, the distribution of predictions, drift scores, and calibration. Performance metrics such as precision, recall, or RMSE join the list once labels arrive.
Business metrics are conversion, revenue, fraud prevented, and engagement. They move slowly and are hard to attribute, because many things besides the model change them. Treat them as the final check on whether the model still helps the product.
When labels arrive late
Performance metrics need labels, so with delayed labels you rely on signals that need none.
Track input feature distributions against the baseline.
Track the prediction distribution: if the average fraud score doubles overnight, something changed even though you cannot yet say whether the model is wrong. Watch label-free proxies such as the share of requests with missing features.
When labels do arrive, backfill the performance metrics and compare them with the proxies. That comparison shows which proxies are worth alerting on.

Alerting
Compare against a stable baseline over a rolling window instead of one day. Segment by key cohorts, since an overall metric can hide a failing region or device type. Page someone only for signals that have preceded real incidents, and send the rest to a dashboard.
Example
Say a fraud model gets chargeback labels 30 to 60 days after each transaction. After a mobile app release, the share of requests with a missing device_id rises from 1% to 14%, and the average fraud score drops by a third. No labels exist yet, so accuracy cannot be computed.
The null-rate alert and the score-distribution alert both fire on day 1. The team finds that the new app version stopped sending the device field and ships a fix. Six weeks later, the matured chargeback cohort confirms that recall on mobile traffic fell during those days. Without the label-free alerts, the first sign would have been that report.
Trade-Offs
More monitored signals means more false alarms. Pick a small set tied to decisions, and write down what you will do when each alert fires. An alert with no owner and no runbook gets ignored.
Label-free proxies are cheap and fast, and they are indirect: a shifted feature does not prove the model got worse. Segment-level monitoring catches hidden failures, and it multiplies the number of alerts and needs enough traffic per segment for stable estimates. Logging every request also costs storage and can include personal data, so decide what to keep and for how long.
30. What Is the Difference Between Data Drift and Concept Drift?
Difficulty: Advanced
Type: Theory
Data drift is a change in the distribution of the model's inputs. Concept drift is a change in the relationship between the inputs and the target. In both cases the model was trained on a world that no longer exists, and the two need different fixes.
Netflix asked about a recommendation model whose offline metrics were unchanged six months after training while click-through slid for a month.
Detecting Drift in a Recommendation Model
Last Updated: September 2026
A recommendation model's offline metrics are unchanged since training six months ago, but click-through has slid for a month. What kinds of drift could explain it, and how would you detect each?

Why the offline metrics stayed flat
The offline test set is frozen. It reflects behavior from six months ago, so the model keeps scoring well on it while real users change. Flat offline metrics say nothing about current performance. That is the first point to make in the answer.

How to detect each type
For data drift, compare recent feature distributions against the training baseline using the population stability index (PSI), Kolmogorov-Smirnov (KS) tests, or summary statistics, and check the prediction distribution too.
A common rule of thumb treats PSI above 0.25 as a major shift.
For concept drift, evaluate the model on recently labeled data, or train a challenger on fresh data and compare the two. Label drift, where the share of positives changes, is a third case. It mostly breaks calibration and decision thresholds.
Example
Take the Netflix scenario. Two explanations fit a click-through slide with flat offline metrics.
If a wave of new titles arrived, the catalog the model scores looks different from its training data. That is data drift, and the feature comparison would show it.
If the catalog stays the same and viewing habits change, for example a seasonal shift, the same user features now lead to different clicks. That is concept drift. Feature distributions would look stable, and performance on the last 2 weeks of logged clicks would show the drop.
The diagnostic order: compare feature distributions first, because it is cheap and needs no labels. Then score recent labeled data. Then train a challenger on fresh data and see whether it recovers the lost clicks.
Trade-Offs
Drift tests have a sensitivity problem. With millions of rows, a KS test flags tiny shifts that do not affect the model. With thresholds set too loose, real shifts pass. Tune thresholds against past incidents.
A feature shift is a warning. Accuracy may or may not have fallen, so check performance before acting. Concept drift needs labels, so you often detect it late. Retraining on recent data fixes concept drift and can erase older patterns, such as holiday seasonality, so keep enough history to cover them.
31. When Should You Retrain a Machine Learning Model?
Difficulty: Advanced
Type: Theory
Retrain when evidence says the model is out of date: a schedule you have validated, enough new data to matter, drift, measurable performance loss, or a business change that alters what the model should predict. More frequent retraining is not automatically better.
Uber asked how to decide between hourly, weekly, and monthly retraining for an ETA model, and what has to be in place before retraining runs unattended.
Retraining Cadence for an ETA Model
Last Updated: September 2026
An ETA model is retrained weekly. One engineer wants hourly, another says monthly is fine. How do you decide, and what must be in place before retraining runs unattended?
There are five common triggers:

- Scheduled: Simple and predictable. Choose the interval from how fast the underlying data changes.
- New data: Retrain after a set volume of fresh labeled data arrives.
- Drift: Retrain when input distributions or prediction distributions cross a threshold.
- Performance degradation: Retrain when labeled outcomes show a drop.
- Business changes: A new product, pricing change, or market launch can invalidate old patterns overnight.
Most teams combine a schedule with event triggers: retrain weekly, and retrain sooner if drift or performance alerts fire.
To choose a cadence, run a backtest. Retrain on historical data at each candidate cadence and measure how the model would have performed over the same period. Pick the slowest cadence whose results are within noise of the faster ones.
Retraining also needs a promotion rule. The new model replaces the old one only if it beats it by a set margin on a fixed holdout, on recent data, and on key segments.

Example
Say you backtest the ETA model over the past 6 months at hourly, daily, weekly, and monthly cadences. Hourly and daily retraining give RMSE within 1% of weekly.
Monthly is 6% worse. Weekly is the slowest cadence that matches the faster ones, so it is the default, with an extra retrain when a new city launches.
Hourly has a second problem for this model. ETA labels exist only after a trip finishes, so an hourly run sees short trips first and long trips later. The batch is biased toward short trips, and the model learns that bias.
Trade-Offs
Hourly retraining costs compute and adds review overhead. It can train on incomplete data, as above. It can chase noise, so the model's behavior shifts when nothing really changes. It can also train on bad data: an automated pipeline pushes a bad batch into production within hours. When a model's own predictions influence the data it later learns from, frequent retraining strengthens that feedback loop.
Before retraining runs unattended, put these in place:
- Data validation that stops the run on schema breaks or abnormal distributions.
- An automatic comparison against the currently serving model on a fixed holdout and on recent data.
- A promotion rule with a margin on key segments.
- Canary rollout and automatic rollback, as in question 33.
32. How Would You Reduce ML Inference Latency?
Difficulty: Advanced
Type: Theory
Define
Measure latency across the whole serving pipeline first, then fix the stage that takes the most time. The model is often not the slowest part.
OpenAI asked how batching, caching, and model size interact under a strict p99 latency budget of 100 ms, and where to look first if the budget is missed.
Serving Under a p99 Budget
Last Updated: March 2026
A model must serve predictions under a strict p99 latency budget of 100ms. Walk through how batching, caching, and model size choices interact, and where you would look first if the budget were being missed.
Look at p99, the latency that 99% of requests stay under, since averages hide the slow tail. Users feel the tail, and a service with a 20 ms average can still miss a 100 ms p99 budget.

Break one request into stages: network, request parsing, feature retrieval, preprocessing, model computation, and postprocessing. Time each stage. In some systems, feature lookups from a remote store take longer than the model forward pass.
Then fix the stage that dominates:
- Simpler models: A smaller tree ensemble or a distilled model cuts compute with a small accuracy loss.
- Feature caching: Cache features that change slowly, such as user profile aggregates.
- Model compression: Quantization (lower-precision weights), pruning, and distillation shrink the model.
- Batching: Group requests so the hardware does more work per call.
- Hardware: Move to a GPU or a faster instance type when computation dominates.
- Precomputation: Compute scores or embeddings in advance for common inputs and look them up.

Fixes outside the model often pay more than model changes. Fetching features in parallel, trimming payloads, and keeping the service warm all shorten the path without touching accuracy.
Example
Say a trace of the slowest 1% of requests shows this budget:

The total misses the 100 ms budget by 10 ms. Feature retrieval takes half of it. Swapping in a smaller model would save a few milliseconds and cost accuracy.
Caching the slow-changing features and fetching the rest in one batched lookup brings retrieval down to about 20 ms, and the total to about 75 ms with the model unchanged.
Trade-Offs
Caching returns stale values, so set a time-to-live that matches how fast each feature changes. Quantization can lower accuracy, so re-evaluate the model after applying it. Batching raises throughput and adds waiting time for each request, which hurts p99 if the batch window is too long. A GPU raises cost per hour and only pays off with enough traffic to keep it busy.
State which cost you accept and why. An interviewer wants to hear a decision tied to the latency budget.
33. How Would You Safely Release a New Model?
Difficulty: Advanced
Type: Theory
Release a new model in stages that limit the damage if it is worse than expected: offline evaluation, shadow deployment, canary release, A/B test, then full rollout. Every stage has monitoring and a rollback.
Anthropic asked how to design a shadow deployment and canary rollout that limits the blast radius of a worse model.
Shadow Deployment & Canary Rollout
Last Updated: July 2026
You want to deploy a new ranking model. Design a shadow deployment and canary rollout process that limits the blast radius if the new model performs worse than expected.
Each stage catches a different kind of failure:
1. Offline evaluation. Beat the current model on a holdout, including key segments. This catches a model that is worse before it sees any user.
2. Shadow deployment. Run the new model on live traffic and log its predictions without using them. This catches serving errors, missing features, and distribution mismatches with zero user impact.
3. Canary release. Send a small share of real traffic, say 1% to 5%, to the new model and watch guardrail metrics such as latency, error rate, and a core business metric.
4. A/B test. Split traffic for a statistically meaningful comparison on the target business metric.
5. Full rollout. Increase traffic in steps, keeping the old version available and warm.

Write the rollback thresholds before launch. For example: roll back if p99 latency exceeds the budget, if the error rate doubles, or if the conversion guardrail drops beyond a set margin. Deciding during an incident leads to arguments.
Example
Say a team replaces a ranking model. Offline, the new model improves NDCG on the holdout and on each of the top 5 regions. In shadow mode for 3 days, it logs predictions on all traffic, and the team finds 2% of requests missing a feature that the training pipeline filled with a default. They fix the serving code.
A 5% canary then runs for a day with the guardrails watched: p99 latency, error rate, and click-through. Nothing trips. A 2-week A/B test, sized in advance to detect a 1% change in click-through, shows a gain. Traffic moved to 25%, 50%, and 100% over 3 days, with the old model kept running until the end.
Trade-Offs
Each stage buys safety and costs time. Shadow mode doubles the inference compute for its duration. A canary with 1% of traffic is too small to detect a small business effect. It can only catch large failures. The A/B test is the stage that measures impact, and it needs enough traffic and time to be powered.

Watch for these pitfalls. An underpowered A/B test can show nothing in either direction. Novelty effects can make a new ranking look better for a week. Canary traffic may not represent all users. A model can improve the average while hurting one segment, so check segments. Match the number of stages to the cost of a bad release: a model that gates payments warrants every stage, and an internal report ranker might skip the A/B test.
34. How Would You Debug a Model That Performs Well Offline but Poorly in Production?
Difficulty: Advanced
Type: ML Problem
Work through causes in order of how cheap they are to rule out: production bugs, training-serving skew, leakage, distribution shift, a metric mismatch, and feedback loops. Do not retrain until you know which one it is.

Spotify asked about a recommendation model whose offline precision rose 15% while online results got slightly worse (ID 2571).
Offline Wins, Online Loses
Last Updated: September 2026
A recommendation model improved offline precision by 15% but did slightly worse online. Give the likely reasons, how you would tell them apart, and what you would change.
Business Objective
The business objective is engagement with recommendations: users listening to, saving, and returning to what the system suggests. The model exists to move that number. Offline precision is a stand-in for it, and the debugging question is why the stand-in and the target diverged.
Start the answer by restating this, and by asking how "slightly worse" was measured: a proper A/B test with enough traffic, or a before-and-after comparison. A sample ratio mismatch or a novelty effect can produce the same symptom without any model problem.
ML Objective
The ML objective is to rank items by how likely a user is to engage with them. The model is trained on logged interactions and scored offline with precision on a historical test set.
Those are two different measurements. Offline, the model predicts which of the old system's shown items a user clicked. Online, it must choose among all items, including ones the old system never showed.
Data
The data is the first place to look, because most of the explanations live there:
- Logging bias and feedback loops: Logged data records what users clicked among items the old system showed them. A model that gets better at predicting those clicks can get worse at recommending anything new. Past recommendations shaped the logged clicks, so the test set rewards repeating them.
- Leakage: Check feature timestamps. An offline gain that looks too good often points here, for example a feature computed after the click.
- Distribution shift: Compare the offline test set's population with current traffic: users, devices, regions, catalog.
- Training-serving skew: Compare logged online feature values with offline values for the same entities. Different preprocessing, defaults, or null handling show up as diffs.

Model
Next, rule out failures in the model and the serving path. The table orders the candidate based on how cheap they are to test.

Interviewers reward a systematic order of diagnosis over a long list of guesses. Say what you would check first and why it is the cheapest.
Metric
The offline metric may simply not predict the online one. Test that directly: take past experiments, compute the offline precision change for each, and see whether it correlated with the online change. If it did not, the metric cannot be trusted to select models.
Precision on logged clicks also ignores ranking order, diversity, and novelty. Metrics such as NDCG, coverage of new items, and counterfactual estimates that correct for what the old system showed are closer to the online goal. Any metric you adopt should be validated against past A/B results before you rely on it.

Trade-Offs
Fix the cause you find. For skew, share feature code between training and serving. For a metric mismatch, adopt an offline metric that tracks the online goal. For logging bias, collect some exploration traffic, such as showing random or lower-ranked items to a small share of users, so the training data covers more than the old model's choices.
Each fix has a cost. Exploration traffic gives up some engagement in the short term to produce better training data. Counterfactual evaluation is more complex to build and depends on logged propensities. Shared feature code limits technology choices. The right choice depends on how large the gap is and how often the team ships.
Machine Learning System Design Interview Questions
This section stays short on purpose. Each answer follows Requirements → Data → Features → Model → Evaluation → Serving → Monitoring, with the details relevant to the problem.

35. How Would You Design a Recommendation System?
Difficulty: Advanced
Type: System Design
Start with the product requirement, then walk through data, features, model, evaluation, serving, and monitoring. A recommender is usually two stages: a fast stage that picks a few hundred candidates and a slower model that ranks them.
Audible asked how to build one.
Build a Recommendation System
Last Updated: February 2020
Can you walk us through how you would build a recommendation system?
Requirements
Ask what is being recommended, where it appears, and what the goal is: clicks, purchases, or watch time. Ask for the latency budget and the catalog and user counts. A homepage carousel refreshed once a day has a different design from a "next item" widget that updates after every click.

Data
The core data is interactions (views, clicks, purchases, ratings), item metadata, and user attributes. Interactions are implicit feedback: a missing click does not mean a user disliked an item, only that they may not have seen it. New users and new items have no history, which is the cold-start problem. For a new product with little data, a popularity ranking is a reasonable start.
Features
Build features for the user (history, recent activity, preferences), the item (category, price, age, popularity), and the context (time, device, location). Add user-item features such as how often this user interacted with this category. Compute them as of the time of each logged impression to avoid leakage.
Model
Use two stages. Candidate generation narrows millions of items to a few hundred. Sources include friends' pages as in question 24, popular items, similar items, and embedding nearest neighbors. Ranking then scores each candidate with a classifier or ranking model, for example the probability of a click or purchase. Gradient boosted trees are a common first ranker, and neural models help at large scale.
Evaluation
Offline evaluation uses different metrics for each stage:
- Candidate generation - Recall@K: Measures how many relevant items appear among the K retrieved candidates. High recall matters because the ranking model cannot recommend items that were never retrieved.
- Ranking - NDCG (Normalized Discounted Cumulative Gain): Measures how well relevant items are positioned, rewarding models that place the most relevant recommendations at the top.
- Ranking - Precision@K: Measures what proportion of the top K recommendations are relevant, helping assess recommendation quality.
Online evaluation: Run an A/B test to measure whether the new recommender improves real user behavior, such as clicks, purchases, or watch time. Offline metrics cannot fully predict how users will respond to recommendations.
Serving
Precompute candidates in a batch, since they change slowly. Rank at request time within the latency budget, using fresh context features. Keep a fallback such as popular items when the ranker is slow or down.
Monitoring
Track click-through and conversion, diversity, coverage of new items and users, feature drift, and latency. Watch for feedback loops where the system keeps showing what it already showed.
For the complete architecture, see ML System Design Interview.
36. How Would You Design a Fraud Detection System?
Difficulty: Advanced
Type: System Design
A fraud system scores each transaction in real time, with models trained on past labeled fraud and a threshold tuned around the cost of each type of error.
Adobe asked for an end-to-end design that covers data pipelines, features, model selection, evaluation, and A/B testing.
AI-Powered Fraud Detection System Design
Last Updated: January 2026
Design a production-grade fraud detection system end-to-end. Discuss data pipelines, feature engineering (including how you would use LLM-based feature extraction from transaction descriptions and user messages), model selection, online and offline evaluation metrics, and how you would set up A/B testing.
Requirements
The decision happens at transaction time, with a latency budget in tens of milliseconds. Agree on an acceptable false-positive rate up front, because every false positive is a blocked legitimate customer. Ask which actions are available: approve, block, step-up authentication, or send to manual review.

Data
Transaction data comes with labels from chargebacks and manual review. Labels arrive late, sometimes weeks after the transaction, so recent transactions are not yet labeled. Blocked transactions never produce a chargeback, so the labels are biased toward fraud that the old system let through. Fraud is also rare, often well under 1% of transactions.
Features
Use transaction amount, merchant, device, location, and velocity (transactions in the last hour or day). Add account history: age, typical amounts, and how far the current transaction departs from them. Features that compare a transaction with the account's own baseline tend to be more informative than the raw amount.
Model
Gradient boosted trees are a strong tabular baseline. Handle class imbalance with class weights or resampling on the training data. A simple rules layer in front of the model can catch known patterns and give analysts a way to react fast to new attacks.
Evaluation
Accuracy is useless when 99.9% of transactions are legitimate, so use PR-AUC and precision and recall at the chosen threshold. This is the confusion matrix from question 8 applied: a false negative is lost money, a false positive is a blocked customer. The threshold is a business decision, and a cost-weighted metric makes it explicit. Split by time, not randomly, and validate with a shadow period before enforcing decisions.
Serving
Compute velocity counters as online features and merge them with slower batch history at request time. Score within the latency budget, with a fallback to rules if the model service fails. Route borderline scores to step-up authentication or manual review instead of a hard block.
Monitoring
Watch drift in features and scores, shifts in fraud type, manual-review queue volume, and approval rate. Compute performance once chargeback labels mature. Fraudsters adapt to the model, so a model that was accurate last quarter can degrade without any change in the data pipeline.
For hands-on practice with a modeling dataset, the platform's Fraudsters Detection data project is built from a Revolut scenario.
37. How Would You Design a Churn Prediction System?
Difficulty: Advanced
Type: System Design
A churn system defines churn, builds a time-correct training set, trains a model, scores users in batch, and connects the scores to a business intervention.
Robinhood asked what churn is and how to predict it.
Churn
Last Updated: January 2021
What is churn? How can we predict if a person is churning?

Requirements
Define churn first, with the business: no session in 30 days, a cancelled subscription, or another definition everyone agrees on. Then ask who acts on the scores and how many users they can contact each week. That capacity sets how the model is evaluated later.
Data
Frame the data around the entity (one row per user), the prediction point (for example, January 31), a feature window (the 90 days before it), and a label window (the 30 days after). Activity after the prediction point cannot be a feature. Build the table with the leakage and grain rules from questions 11, 12, and 22, and validate it with the checks from question 21.
Features
Use recency (days since last session), frequency (sessions in the window), usage trend (last 30 days against the previous 60), support tickets, plan type, and tenure. Every feature must be computed from data available at the prediction point.
Model
Start with logistic regression, which is fast to build and easy to explain to the retention team. Move to gradient boosting if the lift justifies the extra complexity.
Evaluation
Evaluate precision and recall at the number of users the retention team can contact, since a score nobody can act on is useless. Split by prediction date so the test set is later in time than the training set. Run the intervention with a holdout group to measure whether it causes lower churn. A model can identify users who would have stayed anyway.
Serving
Weekly batch scoring works because churn risk moves slowly. Write the scores to a table that the CRM or campaign tool reads, with the top-scored users flagged for offers or outreach. Online serving would add cost and no benefit here, as in question 27.
Monitoring
Track the score distribution and the feature distributions each week. Compute calibration and recall once the 30-day label window closes for each cohort. Watch the holdout group's churn rate to confirm the intervention still works, and retrain on a schedule or when performance drops.
38. How Would You Design a Real-Time Prediction System?
Difficulty: Advanced
Type: System Design
A real-time system flows from events to online features to a model service to a prediction, which a downstream application uses within the user's request.
The path: Streaming/events → online features → model service → prediction → downstream application.

Requirements
Set a latency target (for example, p99 under 100 ms), the expected peak requests per second, and the availability target. Decide what happens when the model is unavailable. The answer to that last question shapes the whole design.
Data
User actions flow into an event stream, which updates counters and aggregates. Historical data in the warehouse builds the training set. Log every request with its features and prediction, so you can replay traffic and build later training sets from what the model actually saw.
Features
A low-latency store holds the latest features per entity, such as counts over the last 5 minutes. Slower features come from batch jobs and are merged at request time. Compute online and offline features from one definition, or training-serving skew from question 25 follows.
Model
A stateless service loads a versioned model and scores each request. Keep preprocessing code identical to training. Choose the smallest model that meets the accuracy target, because model size sets latency, and latency sets cost.
Evaluation
Evaluate offline on a time-split holdout, then replay logged traffic through the service as a load test. Run a shadow deployment and a canary as in question 33. Measure latency per stage against the budget, not just end to end.
Serving
Budget each stage: feature fetch, preprocessing, inference, response. Use caching and a small model if needed. Define a fallback, such as a simple rule or the last known score, so a failure degrades the product instead of breaking it. Use timeouts, retries with limits, and autoscaling for peaks.
The trade-off is cost and complexity against freshness. If the decision does not need up-to-the-second data, batch scoring from question 27 is simpler.
Monitoring
Track latency percentiles, error rates, feature freshness (how old the online values are), and the prediction distribution. Alert on fallback rate, since a rising fallback rate means the main path is failing quietly.
39. How Would You Design a Model Monitoring System?
Difficulty: Advanced
Type: System Design
A monitoring system logs production predictions, tracks feature and prediction behavior, detects drift, joins delayed labels for performance, and triggers retraining or review.
The flow: Production predictions → logging → feature monitoring → drift detection → delayed labels → performance evaluation → retraining trigger.

Waymo asked how to design drift-triggered retraining and what happens when the threshold is wrong.
Drift-Triggered Retraining
Last Updated: April 2026
Instead of retraining a model on a fixed schedule, you want retraining triggered by drift. Design the detection and triggering mechanism, and explain the failure modes of getting the threshold wrong.
Requirements
Decide which models are covered, who owns the alerts, and what action each alert triggers. Ask how long labels take to arrive, because that sets how soon performance can be measured. A monitoring system with no owner produces dashboards nobody reads.
Data
Log the request ID, timestamp, model version, input features, and prediction for every call. Store outcomes separately and join them to predictions by request ID as they arrive. Keep the training data baseline, since every drift comparison needs one.
Features
The monitored signals are statistics about the model's inputs and outputs: per-feature distributions, null rates, out-of-range values, and the distribution of predictions. Compute them per model version and per key segment. Pick a small set tied to decisions, as in question 29.
Model
The detection logic is a set of drift tests: PSI or KS tests per feature and on the prediction distribution, with thresholds set from historical variation. Add a performance estimator that computes the model's metrics on matured label cohorts. Start with simple statistical tests, because they are easy to explain when an alert fires.

Evaluation
Evaluate the monitoring system itself. Backtest its thresholds against past incidents: would it have fired, and how early? Count false alarms per week. A threshold set too low causes constant retraining on noise. A threshold set too high lets a degraded model run for weeks.
Serving
Run drift jobs on a schedule, hourly for fast-moving models and daily for slow ones. Send results to a dashboard and alerts to the owner. Open a ticket or start a retraining run when drift and performance signals agree. Start with alerts to a person and automate the trigger once the signals have proven reliable.
Monitoring
Monitor the monitor. Alert when logging coverage falls, when a drift job fails or runs late, and when alert volume spikes. A silent monitoring failure looks the same as a healthy model.
AI and LLM Questions for Machine Learning Engineers
This section covers the part of the role that is growing, in short form. For deeper preparation, our 50 LLM Interview Questions and Answers article goes much further.
40. What Are Embeddings?
Difficulty: Intermediate
Type: Theory
Define
Embeddings are numerical vectors that represent items such as words, documents, images, products, or users, positioned so that similar items sit close together in vector space.
Explain
A model produces the vector for each item. Similarity is then measured with a distance metric, commonly cosine similarity. That makes embeddings useful in several places:
- Semantic search: Embed the query and the documents, and return the nearest documents even if the words differ.
- Recommendation: Embed users and items, and recommend items near a user's vector.
- Retrieval: Find the context most relevant to a question.
- LLM applications: Retrieval over a company's own documents relies on them.

Queries and documents must be embedded with the same model, or the distances mean nothing. For large collections, a vector index finds approximate nearest neighbors quickly instead of comparing the query with every vector.
Example
A support site has an article titled "Reset your password". A user searches "can't log in". The two share no words, and a keyword search misses the article. An embedding model places both close together because the meanings are related, so semantic search returns it.
The same idea powers recommendations. If a listener's vector sits near the vectors of several jazz albums, other albums near that point become candidates.
Trade-Offs
Higher-dimensional vectors capture more and cost more storage and search time. Approximate nearest-neighbor search is fast and can miss the true closest match. A general-purpose embedding model can perform worse on specialized vocabulary, such as legal or medical text, than one tuned on domain text.
Changing the embedding model means re-embedding the whole collection, since old and new vectors are not comparable. That is a real cost for a large index. Embeddings are also hard to inspect: when a retrieval result looks wrong, no single dimension tells you why.
41. What Is RAG?
Difficulty: Advanced
Type: Theory
Define
Retrieval-augmented generation (RAG) gives a language model relevant documents at question time, so its answer is based on supplied context instead of only its training data.
The flow: Documents → retrieval → context → LLM → response.
Oracle asked how to architect a RAG system from scratch and improve retrieval quality.
RAG System Architecture
Last Updated: August 2024
Describe how you would architect a RAG (Retrieval-Augmented Generation) system from scratch. What components are needed, and how would you optimize retrieval quality?
Explain
Documents are split into chunks, embedded, and stored in a vector index. At question time, the question is embedded, the closest chunks are retrieved, and the model receives them as context along with the question. The model writes an answer from that context, and a good system can cite which chunks it used.
Retrieval quality limits answer quality. If the right chunk is not retrieved, the model cannot use it. Most RAG improvements target retrieval: better chunking, hybrid search that combines keywords and embeddings, and reranking the top results.

Example
An HR assistant answers questions about company policy. An employee asks how many weeks of parental leave they get. The system retrieves the 3 chunks of the leave policy closest to the question and passes them to the model. The model answers from those chunks and cites the policy section.
If the leave policy was split in the middle of the eligibility rules, retrieval might return the weeks but not the conditions, and the answer would be incomplete. Chunking affects the answer.
Trade-Offs
Small chunks retrieve precisely and lose surrounding context. Large chunks keep context and add noise and token cost. Retrieving more chunks raises the chance of including the right one and increases cost and latency, and too much context can distract the model.

The retrieval step adds latency to every request. The index goes stale if documents change and nobody re-indexes.
42. What Is the Difference Between RAG and Fine-Tuning?
Difficulty: Advanced
Type: Theory
Define
RAG adds knowledge by retrieving documents at query time. Fine-tuning changes the model's weights by training it further on examples.
OpenAI asked when to use each and how they compare on cost, latency, accuracy, and maintainability.
RAG vs. Fine-Tuning
Last Updated: September 2025
When would you use Retrieval-Augmented Generation (RAG) instead of fine-tuning an LLM, and vice versa? What are the tradeoffs in terms of cost, latency, accuracy, and maintainability?
Explain

RAG changes what the model can look up. Fine-tuning changes how the model behaves. Facts that change often belong in a retrieval index, since updating an index takes minutes and retraining takes a pipeline run.
Example
A company builds a support assistant. The product documentation changes every week, and answers should link to the source page. That is a RAG problem: update the index when docs change, and cite the retrieved page.
The same company needs every reply in a fixed JSON format with a specific tone. Prompting gets close and misses on edge cases. Fine-tuning on a few thousand good examples makes the format consistent. Many production systems use both, with fine-tuning for format and RAG for knowledge.

Trade-Offs
RAG adds infrastructure and a retrieval failure mode, and fine-tuning adds training cost, data preparation, and a model you must re-evaluate after each run. Combining them gets the benefits of both and carries both sets of maintenance. Start with prompting and RAG, because they are cheaper to change, and fine-tune when you have evidence that behavior is the problem.
43. How Would You Evaluate an LLM Application?
Difficulty: Advanced
Type: Theory
Define
Evaluate an LLM application on whether it completes the task, with separate checks for relevance, correctness, and groundedness, then add human review, cost, and latency.
OpenAI asked how to evaluate a RAG solution, with metrics for both retrieval and generation (ID 2474).
Evaluating RAG Systems
Last Updated: April 2025
How would you evaluate the performance of a RAG (Retrieval-Augmented Generation) solution? What metrics would you use for both the retrieval and generation components?
Explain
- Task success: Did the user get what they needed, as defined for this product?
- Relevance: Do the retrieved documents and the answer address the question?
- Correctness: Is the answer factually right, checked against a reference set?
- Groundedness: Is every claim supported by the retrieved context?
- Human evaluation: Reviewers rate a sample, and their ratings calibrate any automated judge.
- Cost and latency: Tokens per request and response time.

For RAG, separate retrieval from generation. Retrieval metrics such as recall at K show whether the right context was found. Generation metrics show what the model did with it. Without that split, you cannot tell which component to fix.
Automated judges, where one LLM grades another's output, scale to thousands of examples. Check them against human ratings on a sample before trusting them.
Example
Say you build a RAG assistant over HR policy documents. Write 200 real employee questions, each with the policy section that answers it and a reference answer.
Measure recall at 5: for how many questions does the correct section appear in the top 5 retrieved chunks? Suppose it is 82%. Then grade the answers for correctness and groundedness. If groundedness is high and correctness is low for the questions where retrieval failed, the problem is retrieval, and prompt changes will not help.
Trade-Offs
Human evaluation is the most trustworthy and the slowest and most expensive. Automated judges are cheap and can be biased, for example toward longer answers. Reference sets go stale as documents and user questions change, so refresh them.
Quality also trades against cost and latency. A larger model or more retrieved chunks may improve answers and cost more per request. Report quality, cost, and latency together.
44. When Should You Use Traditional ML Instead of an LLM?
Difficulty: Advanced
Type: Theory
Use traditional ML when the problem is structured prediction with labeled data, and an LLM only when the task needs language understanding or generation that simpler models cannot provide. A strong ML engineer does not reach for an LLM by default.
IBM asked when to choose traditional ML-based, deep learning-based, or LLM-based approaches for NLP tasks).
Traditional NLP vs. LLM-Based Approaches
Last Updated: September 2024
Compare and contrast different NLP approaches: traditional ML-based NLP, deep learning-based NLP, and LLM-based approaches. When would you choose each?
Explain
Several factors push toward traditional ML:
- Structured prediction: Churn, fraud, and demand forecasting on tabular data are usually handled well by gradient boosted trees.
- Deterministic requirements: A model that must give the same output for the same input is easier to guarantee without free-text generation.
- Cost: A small model scores millions of rows for a fraction of an LLM call.
- Latency: A tree model typically answers in milliseconds.
- Interpretability: Feature importance and simple models are easier to explain to regulators and stakeholders.
- Available training data: With thousands of labeled examples, a trained classifier often matches an LLM on a narrow task.
- Task complexity: Open-ended language tasks, summarization, and extraction from messy text are where LLMs earn their cost.

Example
Take support-ticket routing. If you have 100,000 labeled tickets and a fixed set of categories, a text classifier is cheap and fast. If tickets arrive in any language and need a drafted reply, an LLM fits better.
Churn prediction is a clearer case. The inputs are tabular (sessions, plan, tenure), the label is binary, and the retention team wants to know which features drive the score. A gradient boosted model handles that at a fraction of the cost, and an LLM adds nothing.
Trade-Offs
An LLM needs no labeled data to get started, so it can be the faster way to prototype. Traditional ML needs labels, feature work, and a training pipeline, and then it is cheaper, faster, and more predictable at volume.
The two can work together. An LLM can extract structured fields from messy text, and a tree model can use those fields. An LLM can also draft labels that humans review, which gives a traditional model training data it would not otherwise have.
Machine Learning Engineer Coding Interview Questions
The questions above already cover three coding problems in full.
This table is a practice directory of real questions that fit machine learning engineer interviews. Each one supports Python.
The first three are solved above.
IDs 2135, 10303, and 10350 practice prediction error, thresholds, and evaluation.
IDs 2106, 2097, 10566, and 10314 practice data preparation, time-window logic, and rolling features. IDs 9713 and 10019 cover distributions and probability.

Useful Links
- Recommendation System
- Naive Forecasting
- Words With Two Vowels
- Actual vs Predicted Arrival Time
- Top Percentile Fraud
- Algorithm Performance
- Rows With Missing Values
- Revenue Over Time
- Premium Accounts
- Search Click Success Rate by User Segment
- Find the Scores of 4 Quartiles of Each Company
- Find the fraction of rides for each weather and the hour
For more practice, see our Python Interview Questions and SQL Interview Questions articles, and the full set of coding questions.
How to Answer Machine Learning Engineer Interview Questions
Use a simple framework for each question type, and say it out loud. Interviewers score the reasoning, so communication counts.

Theory Questions
Define → Explain → Example → Trade-off. A textbook definition on its own scores low. Add a concrete example and the cost of the choice.
Coding Questions
Clarify → Explain approach → Code → Test → Discuss complexity. Ask about edge cases first, describe your plan before typing, and talk while you code. Run a small example by hand at the end.
ML Problems
Business objective → ML objective → Data → Model → Metric → Trade-off. Restate the business goal, translate it into a prediction target, and choose a metric that matches the cost of errors.
Data Problems
Entity → Prediction point → Feature window → Label window → Validation. State the grain and the time boundary before writing any query. For the full method, see the ML Engineer data interview guide.
System Design Questions
Requirements → Data → Features → Model → Evaluation → Serving → Monitoring. Spend the first minutes on requirements and constraints.
Common Machine Learning Engineer Interview Mistakes

Memorizing Algorithms Without Understanding Trade-Offs
Interviewers follow a definition with "when would you use it?" Explain when and why you would pick a model, and when you would not.
Jumping Into Coding Before Defining the Problem
This costs the most in dataset construction and system design. Spend the first minutes on the entity, the label, and the constraints.
Ignoring Data Leakage
State what information would exist at prediction time for every feature you propose.
Using Accuracy for Every Classification Problem
Pick a metric from the costs of the different errors. On imbalanced data, accuracy can be high for a useless model.
Ignoring Baselines
Say what the model has to beat before you propose a complex one. A baseline takes minutes to build and anchors every later result.
Focusing Only on Model Training
ML engineers own what happens before and after training: data, features, deployment, and monitoring. Mention them without being asked.
Ignoring Production Constraints
Latency, scale, reliability, and cost shape which model you can ship. A model that is too slow or too expensive to serve never reaches users.
Forgetting Monitoring
The work continues after deployment. Say what you would monitor and what would trigger action.
How to Prepare for a Machine Learning Engineer Interview
1. Review Machine Learning Fundamentals
Practice classification, regression, clustering, evaluation, regularization, and model selection. For each, be ready to give an example and a trade-off.
2. Practice Python
Focus on data structures, Pandas, NumPy, data manipulation, and algorithms. Work through the practice table above and the Python coding questions on the platform.
3. Practice SQL and Dataset Construction
Cover joins, aggregations, window functions, time-based logic, feature construction, labels, and leakage.
4. Practice Statistics
Review probability, distributions, sampling, hypothesis testing, and experimentation.
5. Practice ML System Design
Design a recommendation system, a fraud detector, a churn system, a real-time prediction service, and a monitoring setup. Time yourself and use the seven-step framework.
6. Learn Production ML
Understand deployment, feature stores, batch versus online inference, monitoring, drift, and retraining. Questions 25 to 34 above are a checklist.
7. Know the Basics of Modern AI Engineering
Depending on the role, review embeddings, LLMs, and RAG. Use LLM Interview Questions, RAG Interview Questions, and Agentic AI Interview Questions for depth.
Machine Learning Engineer Interview Questions FAQ

What Questions Are Asked in a Machine Learning Engineer Interview?
Expect a mix: Python and SQL coding, ML fundamentals, statistics, dataset construction, production ML, and system design. Some roles add embeddings, RAG, and LLM questions. The exact mix depends on the company and level.
How Do I Prepare for a Machine Learning Engineer Interview?
Review fundamentals, then practice coding, dataset construction, statistics, and ML system design, in that order. Solve real questions in the code editor and rehearse explaining trade-offs out loud.
Are Machine Learning Engineer Interviews Difficult?
They can be, mainly because of breadth: one loop can test coding, ML, data, and design. Preparing each area separately makes the load manageable.
Do Machine Learning Engineer Interviews Include Coding?
Yes. Most include Python, SQL, or both, and some add algorithms and data structures. Expect data manipulation and sometimes an ML-flavored problem such as a baseline or an evaluation metric.
Do Machine Learning Engineers Need SQL?
Yes. Building training datasets from production tables takes joins, aggregations, and window functions, and interviewers test it directly.
Do Machine Learning Engineers Need System Design?
For senior and production-focused roles, yes. Even junior candidates are sometimes asked how a model would be deployed and monitored.
How Much Statistics Do Machine Learning Engineers Need?
Enough to evaluate models and experiments correctly: probability, distributions, sampling, hypothesis testing, and metric choice. Interviewers test whether you apply them correctly, such as choosing a test and reading its result.
Do Machine Learning Engineers Need to Know LLMs?
It depends on the role. Many teams now expect at least the basics of embeddings and RAG, and some roles focus on LLM applications. Check the job description.
Conclusion
Machine learning engineer interviews test the whole lifecycle: data, features, models, evaluation, deployment, and monitoring. The questions in this guide move from core concepts through production scenarios, and the real StrataScratch questions give you problems to solve in the code editor.

Start with the practice table, work through the dataset construction guide, and rehearse the system design framework out loud. Then pick the weakest area and spend your next week there.
Share