End-to-End ML System Design Questions
End-to-end design of machine learning systems, covering data collection and validation, feature engineering and feature stores, model training and evaluation, deployment and serving architectures, monitoring and incident management, retraining pipelines, data governance, scalability, security, and MLOps practices.
MediumTechnical
25 practiced
Design a retraining pipeline that triggers automatically on evidence of concept drift or label distribution change. Describe drift-detection signals you would monitor, how to define retraining windows, validation gating, human-in-the-loop checks, and safe deployment practices (shadowing, canaries, rollback).
Sample Answer
Requirements / goals:- Automatically detect meaningful model degradation (performance, fairness) and trigger retraining with human oversight, minimizing false positives and ensuring safe rollout.Drift-detection signals to monitor:- Performance metrics: rolling AUC, accuracy, precision/recall on recent labeled data (with confidence intervals).- Input feature distribution: population stability index (PSI), KL divergence, multivariate distance (MMD).- Label distribution: changes in class priors (chi-square test).- Calibration shifts: Brier score, reliability diagrams.- Model confidence shifts: mean predicted probability, spike in low-confidence predictions.- Business KPIs: conversion rate, revenue per user.Use statistical thresholds + rate-of-change and alerting windows to avoid noise.Retraining window definition:- Use a sliding window of recent examples (time-based, e.g., last 30–90 days) plus a decay-weighted historical buffer; select window length by concept half-life and data volume. Optionally use reservoir sampling for balanced representation of rare classes.Validation gating:- Hold out a stable validation set (temporal holdout + backtest on multiple historical windows).- Required checks before promotion: - Statistically significant improvement in primary metric (with p-values/bootstrapped CIs). - No regression on fairness metrics and secondary metrics. - Calibration within tolerance. - Feature importance sanity checks and drift explanations.- Automated test suite: data schema checks, unit tests for preprocessing, reproducibility (seeded runs), and model versioning.Human-in-the-loop checks:- Auto-generate model card and comparison report (metrics, feature shifts, sample errors, SHAP summaries).- Trigger review when drift magnitude or model change exceeds threshold; require sign-off from data scientist and domain stakeholder for major changes.- Provide tooling to inspect representative examples, label samples, and approve retrain.Safe deployment practices:- Shadowing: run new model in parallel on live traffic; compare predictions and metric deltas without affecting decisions for a set period.- Canary rollout: deploy to small percentage (1–5%) of users with monitoring for business and model metrics; escalate/rollback automatically if SLA breached.- Gradual ramp-up with automated gates.- Rollback plan: automated revert to previous model version if key metrics degrade beyond thresholds.- Observability: monitoring dashboards, alerting, and logging for prediction lineage to enable quick diagnosis.Automation & CI/CD:- Pipeline triggered by drift signal or scheduled runs; built with reproducible steps (data extraction, preprocessing, training, evaluation, model registry).- Use MLflow or similar for tracking; CI tests for data and code; automated promotion to staging after passing gates.This balances sensitivity to real drift with safeguards (statistical rigor, human review, shadow/canary deployments) to keep models reliable in production.
MediumTechnical
25 practiced
Compare methods to handle severe class imbalance for rare-event detection (e.g., fraud): oversampling (SMOTE), undersampling, class weighting, focal loss, anomaly detection, and threshold tuning. For each, explain when it is appropriate and how to evaluate using precision-recall and business cost metrics.
Sample Answer
Start by recognizing the objective: detect rare but costly events (fraud) where positive class is tiny and standard accuracy is meaningless. Below I compare approaches, when to use them, and how to evaluate with precision-recall and business cost.Oversampling (SMOTE)- What/when: Synthesizes minority examples to reduce class skew. Good when you have moderate minority samples and feature space is well-behaved (continuous features).- Pros/cons: Helps classifiers learn minority decision boundary; can create unrealistic examples or amplify noise.- Eval: Use PR-AUC and precision at target recall (e.g., precision@80% recall). Check business cost by mapping false positives (investigation cost) and false negatives (fraud loss).Undersampling- What/when: Remove majority examples to balance. Useful with huge majority set or fast prototyping.- Pros/cons: Simple, reduces training time, risks losing important majority patterns; use ensemble/iteration (e.g., balanced bagging).- Eval: Monitor variance across resamples; compute PR metrics and expected cost per 10k transactions.Class weighting- What/when: Penalize misclassifying minority more in loss. Good baseline for logistic regression, tree-based models (via sample_weight).- Pros/cons: Preserves real data distribution; may underfit if weights extreme.- Eval: Use PR curves, choose threshold that minimizes expected cost = FP_cost * FP_rate + FN_cost * FN_rate.Focal loss- What/when: For deep networks where hard examples should be emphasized; reduces effect of easy negatives.- Pros/cons: Tunable gamma; requires careful hyperparameter tuning.- Eval: Compare PR-AUC and calibration; use cost-weighted loss or convert outputs to probabilities then compute business cost.Anomaly detection- What/when: Use when fraud patterns are unknown/unlabeled or concept drifts; trains on normal behavior and flags outliers.- Pros/cons: Works with very few positives; higher FP rate and requires strong feature engineering.- Eval: Focus on precision at very low recall and time-to-detect; compute expected operational cost and analyst workload.Threshold tuning- What/when: Post-process model scores to trade precision vs recall for operational constraints (investigator capacity).- Pros/cons: Essential step regardless of model; choose threshold by business metric not by accuracy.- Eval: Sweep threshold to produce precision-recall curve and determine threshold that minimizes expected cost or maximizes utility (e.g., profit lift, net savings). Report confusion-matrix-derived costs and metrics like precision@k (top k alerts), recall at fixed FP budget, and PR-AUC.Practical evaluation tips- Use PR-AUC as primary model-agnostic metric; report precision@k and recall@fixed-FP-rate for operational relevance.- Use cross-validation with time-based splits for fraud to avoid leakage.- Translate model performance into dollars: simulate detection pipeline (alerts → investigation → recoveries) and compute expected net benefit per period; choose approach and threshold that maximize net benefit given resource constraints.- Monitor calibration and drift post-deployment and re-evaluate costs periodically.
MediumTechnical
30 practiced
Write an SQL query (standard SQL) to generate labels for supervised training using a cutoff time approach. Given tables: events(user_id, occurred_at, action) and purchases(user_id, purchase_time), produce a label table of users indicating whether they purchased within 7 days after a given cutoff_date without using any data after that cutoff to avoid lookahead bias.
Sample Answer
Approach: for each user and each cutoff_date (could be a single date or many), restrict events/purchases used for features to timestamps <= cutoff_date (no lookahead). Label = 1 if there's at least one purchase with purchase_time > cutoff_date AND purchase_time <= cutoff_date + INTERVAL '7' DAY; otherwise 0. Below is a standard-SQL pattern that produces one row per (user_id, cutoff_date).Key points:- Events and purchases used to build features must be filtered with occurred_at <= cutoff_date and purchase_time <= cutoff_date (not shown above — include similar joins to events when building features).- The purchases join uses strict > cutoff_date so same-time purchases aren’t counted as future.- Handles users with no purchases (label=0). If you need time-to-event instead of binary, return first_purchase_after_cutoff as shown.Edge cases:- Timezone consistency across timestamps.- Multiple cutoffs per user — ensure cutoffs table reflects desired windows.- If purchase_time can equal cutoff and should count, adjust operator accordingly.
sql
-- Assume we have a table "cutoffs(user_id, cutoff_date)" listing cutoffs to label for.
-- If you only have a single cutoff, replace cutoffs with a VALUES(...) or a literal date.
WITH purchases_after_cutoff AS (
SELECT
c.user_id,
c.cutoff_date,
MIN(p.purchase_time) AS first_purchase_after_cutoff
FROM cutoffs c
LEFT JOIN purchases p
ON p.user_id = c.user_id
AND p.purchase_time > c.cutoff_date
AND p.purchase_time <= c.cutoff_date + INTERVAL '7' DAY
GROUP BY c.user_id, c.cutoff_date
)
SELECT
c.user_id,
c.cutoff_date,
CASE WHEN p.first_purchase_after_cutoff IS NOT NULL THEN 1 ELSE 0 END AS label,
p.first_purchase_after_cutoff
FROM cutoffs c
LEFT JOIN purchases_after_cutoff p
USING (user_id, cutoff_date);HardTechnical
30 practiced
Implement a model rollout manager in Python (pseudo-implementation) that supports blue-green and canary deployments with weighted traffic routing, automatic rollback when production SLOs are violated, warmup strategies (gradual weight ramp), and metric aggregation and significance testing to decide promotion or rollback.
Sample Answer
To implement a model rollout manager that supports blue-green and canary deployments with weighted routing, warmup ramps, automatic rollback on SLO violations, and metric aggregation + significance testing, use a controller that: schedules traffic weight changes, collects metrics from model variants, performs statistical tests (e.g., two-sample t-test or permutation test), and triggers promote/rollback actions.Key points:- Router_update abstracts traffic control (service mesh or load balancer).- Metric_fetch pulls per-variant telemetry (latency, error rate, business metrics).- Warmup/ramp uses staged weight changes to prevent sudden load shift.- Statistical tests combine t-test and permutation test to decide significance; use direction-aware checks and SLO thresholds.- Automatic rollback triggers when SLO exceeded or candidate significantly worse.Complexity: metric aggregation O(n), tests O(n + iters) for permutation. Edge cases: low sample counts, non-iid traffic, seasonality — mitigate with longer observation windows, stratified sampling, and holdouts. Alternatives: Bayesian A/B testing (probability of uplift), sequential testing (alpha-spending), or use Thompson sampling for adaptive routing.
python
import time
import math
from collections import defaultdict
from typing import Dict, Callable
import numpy as np
from scipy import stats
class RolloutManager:
def __init__(self, router_update: Callable[[Dict[str,float]], None],
metric_fetch: Callable[[str], Dict[str, list]],
slo_thresholds: Dict[str, float],
min_samples=100):
"""
router_update: function to set traffic weights {'green':0.1,'blue':0.9}
metric_fetch: function that returns recent metric lists for a variant {'latency':[...], 'error_rate':[...]}
slo_thresholds: allowed upper limits for metrics (e.g., {'error_rate':0.02})
"""
self.router_update = router_update
self.metric_fetch = metric_fetch
self.slo = slo_thresholds
self.min_samples = min_samples
self.state = 'idle'
self.weights = {}
def ramp(self, from_w: Dict[str,float], to_w: Dict[str,float], duration_s:int, steps:int=10):
for i in range(1, steps+1):
frac = i/steps
w = {k: from_w.get(k,0)*(1-frac) + to_w.get(k,0)*frac for k in set(from_w)|set(to_w)}
self.weights = w
self.router_update(w)
time.sleep(duration_s/steps)
def aggregate_metrics(self, variant):
# returns aggregated metrics (mean, std, n)
m = self.metric_fetch(variant)
agg = {}
for k, vals in m.items():
arr = np.array(vals)
agg[k] = {'mean': arr.mean() if len(arr) else float('nan'),
'std': arr.std(ddof=1) if len(arr)>1 else float('nan'),
'n': len(arr)}
return agg
def significance_test(self, metric, a_vals, b_vals, alpha=0.05):
# use Welch's t-test if approx normal, else permutation test (small sample)
if len(a_vals)>=30 and len(b_vals)>=30:
t, p = stats.ttest_ind(a_vals, b_vals, equal_var=False, nan_policy='omit')
return p < alpha, p
# fallback permutation test
concat = np.concatenate([a_vals,b_vals])
obs = abs(np.mean(a_vals)-np.mean(b_vals))
count=0
iters=1000
for _ in range(iters):
np.random.shuffle(concat)
if abs(concat[:len(a_vals)].mean()-concat[len(a_vals):].mean())>=obs:
count+=1
p = (count+1)/(iters+1)
return p<alpha, p
def evaluate(self, baseline='blue', candidate='green'):
a = self.metric_fetch(baseline)
b = self.metric_fetch(candidate)
# early exit if not enough samples
if sum(len(v) for v in b.values()) < self.min_samples:
return 'insufficient', {}
violations = []
details = {}
for metric in self.slo:
a_vals = np.array(a.get(metric,[]))
b_vals = np.array(b.get(metric,[]))
better, p = self.significance_test(metric, a_vals, b_vals)
details[metric] = {'baseline_mean': a_vals.mean() if len(a_vals) else None,
'cand_mean': b_vals.mean() if len(b_vals) else None,
'p': p}
# assume lower-is-better metrics (latency, error_rate)
if (b_vals.mean() > self.slo[metric]) or (b_vals.mean() > a_vals.mean() and p<0.05):
violations.append(metric)
return ('promote' if not violations else 'rollback'), details
def canary_deploy(self, baseline_w, candidate_w, ramp_duration=300):
# start ramp-up
self.ramp(baseline_w, candidate_w, duration_s=ramp_duration)
decision, details = self.evaluate()
if decision=='promote':
# move to full candidate
self.ramp(self.weights, {k: (1.0 if k=='green' else 0.0) for k in self.weights}, duration_s=60)
return 'promoted', details
elif decision=='rollback':
# rollback to baseline
self.ramp(self.weights, {k: (1.0 if k=='blue' else 0.0) for k in self.weights}, duration_s=60)
return 'rolled_back', details
else:
return 'wait_for_more_data', detailsMediumSystem Design
49 practiced
Design a monitoring and alerting system for production ML that covers data quality, feature drift, model performance, resource metrics, and business KPIs. Specify which metrics you would collect, how to define SLOs and alert thresholds, and how to reduce alert fatigue while enabling timely incident response.
Sample Answer
Requirements:- Monitor data quality, feature drift, model performance, infra/resource metrics, and business KPIs in production; alert reliably with low false positives; enable fast RCA and mitigation.- Constraints: real-time or near-real-time detection, scalable for many models, integrate with existing MLOps stack.High-level architecture:- Inference logging -> Feature store/stream (Kafka) + metrics extractor -> Monitoring pipeline (Spark/Flink or Airflow batch) -> Metrics DB (Prometheus for infra, Timescale/Influx for timeseries, ML-specific DB like WhyLogs/Feast) -> Alerting/Visualization (Grafana, SLO engine, PagerDuty/Slack) -> Investigation tools (model explainability, sample replay, Jupyter notebooks).Key metrics to collect:- Data quality: missing rate per feature, schema violations, invalid types, cardinality changes, ingestion latency.- Feature drift: population/stats (mean, std, percentiles), PSI/KS per feature, correlation changes, concept drift (label-feature relationship).- Model performance: rolling AUC/accuracy, calibration (Brier score), prediction distribution, uplift/causal metrics if available, latency and QPS.- Resource metrics: CPU/GPU utilization, memory, disk, network I/O, queue length, model loading time.- Business KPIs: conversion rate, revenue per user, churn rate, false positive cost, SLA-related KPIs.SLOs and alert thresholds:- Define SLOs per metric with tiers: - OK (green): within historical baseline (e.g., within 2σ or PSI < 0.05) - Warning (yellow): deviation between 2–3σ or PSI 0.05–0.2 -> log to dashboard, low-priority notification - Critical (red): >3σ or PSI >0.2, drop in AUC >0.03 absolute, calibration shift >0.05, business KPI degradation >5% -> pager/SE on-call- Use percentiles/rolling windows (7/14/28 days) and business-aware windows (daily/weekly) to set thresholds.Reducing alert fatigue:- Multi-signal correlation: only fire critical alert when multiple related signals trigger (e.g., feature drift + model AUC drop + KPI decline).- Alert suppression/aggregation: group similar alerts by model, feature, or service within a time window.- Escalation policies & severity mapping: route warnings to a “review” channel (async) and criticals to on-call.- Auto-triage: include automatic root-cause hints (top drifting features, sample examples, recent deployment/feature changes).- Adaptive thresholds: use anomaly detection models that learn seasonality and reduce false positives.- Playbooks & runbooks: attach remediation steps to each alert type to speed response and reduce cognitive load.Investigation and remediation:- Store sampled inference inputs + predictions + ground truth when available for replay and backtesting.- Provide explainability (SHAP) for affected samples/features.- Enable rollback/redeploy, feature-flagging, or automatic shadowing to compare performance.- Post-incident: blameless postmortems and threshold tuning.Trade-offs:- Real-time detection increases complexity/cost; use hybrid: real-time for infra & critical KPIs, batch for heavy drift computations.- More sensitive thresholds catch issues early but raise noise — mitigate with correlation and automation.This design balances early detection, actionable alerts, and reduced fatigue while enabling fast, data-driven incident response.
Unlock Full Question Bank
Get access to hundreds of End-to-End ML System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.