Delivery Time Estimation: Full ML System Design
Machine LearningModel answerLast updated
Design an end-to-end ML system to predict food delivery duration, covering features, leakage, modeling, calibration, cost-sensitive decisions, fairness, and production deployment.
Delivery Time Estimation: Full ML System Design
A food delivery platform wants to show customers an accurate estimated arrival time the moment they place an order. You have access to a historical dataset of completed orders with order-level, restaurant-level, and courier-level features.
Work through the following seven areas. For each one, be specific: name features, name metrics, write formulas where they add clarity, and call out trade-offs.
A) Target definition and feature design
Define the prediction target precisely, including what population you train on, how you handle outliers, and exactly when the prediction is made. Then list at least 10 features across at least three groups (demand, supply, network/logistics). For each feature, explain why it is predictive and confirm it is available at prediction time.
B) Data leakage and time-based validation
Identify at least five realistic leakage sources in this problem. Propose a time-based train/validation/test split with concrete date ranges and explain why a random split would be wrong. Describe a rolling-origin cross-validation strategy inside the training window and explain how you would handle training data from other cities or markets.
C) Modeling choices
Compare at least three model variants that differ in loss function (e.g., MSE, Huber, MAE, pinball). Explain when you would output a single point estimate versus a full predictive distribution, and what that buys you. List at least three feature interactions you would engineer explicitly and three regularization hyperparameters you would tune and why.
D) Evaluation and calibration
Define the metrics you would report on the held-out test week. Beyond point-estimate accuracy, explain how you would evaluate and visualize quantile calibration. Define calibration error formally and describe how you would fix miscalibration post-hoc without retraining.
E) Cost-sensitive decision-making
The platform incurs a cost when the quoted ETA is too short (late delivery) and a different cost when it is too long (customer under-orders or cancels). Show mathematically how to pick the optimal ETA to quote given asymmetric costs. Then extend the same logic to the dispatch decision: when should a courier be sent to the restaurant to minimize the sum of idle-wait cost and cold-food cost?
F) Explainability and fairness
Describe how you would use feature attribution (e.g., SHAP) to audit the model. Then outline at least two fairness checks you would run—across geography, cuisine type, or courier vehicle type—and name at least two mitigation strategies if you find disparity.
G) Production system
Sketch the production architecture: feature store design, inference latency requirements, retraining cadence, and how you would detect feature or label drift. Describe how you would run an online experiment to confirm that offline metric gains translate to real-world improvement, including what guardrail metrics you would monitor.
What a strong answer looks like: structured responses to all seven parts, specific metric names and formulas, honest discussion of trade-offs at each stage, and a clear thread connecting modeling choices to downstream business outcomes.
Hints
Hint 1
For target definition, think carefully about *when* the prediction must be made — the legal feature set depends entirely on that timestamp. Decomposing the journey into legs (prep → courier travel to restaurant → wait → last-mile) helps both accuracy and interpretability.
Hint 2
Leakage in time-series problems often hides in aggregate features: a 30-day rolling mean of restaurant prep time is leaky if it was computed using data after the order's created_at. The fix is a point-in-time join, not just a train/test split.
Hint 3
The newsvendor formula connects your quantile model directly to the quoting decision: if late-delivery cost is c_late and over-quoting cost is c_early, the optimal quoted ETA is the F⁻¹(c_late / (c_late + c_early)) quantile of your predicted distribution. You do not need to retrain when costs change.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem tests whether you can move an ML project from a vague business goal to a production system while maintaining discipline at each handoff. The math is mostly straightforward — the hard parts are leakage, uncertainty quantification, and translating predictions into decisions.
A) Target Definition and Feature Design
Target: eta_minutes = (delivered_at − created_at) in minutes, using server-side timestamps throughout to avoid clock-skew issues.
Population: completed orders only. Cancellations and test orders are excluded and logged separately so the model's population is fully documented.
Outlier handling: flag and cap implausible values — negative durations or anything over, say, 180 minutes — and treat these as a data quality signal worth investigating.
Prediction time: order creation (created_at), before a courier is assigned. This is the critical constraint that determines which features are legal.
Optional decomposition: modeling prep_time + courier_to_restaurant + wait_at_restaurant + last_mile separately and summing the distributions tends to outperform a single black-box model, because each leg has different drivers and different intervention points.
Feature table:
| Group | Feature | Why it helps |
|---|---|---|
| Demand | Historical prep time by restaurant × hour-of-week (median and P90) | Captures kitchen speed at that time of week |
| Demand | Current queue depth at restaurant | More pending orders = slower service |
| Demand | Open orders within 3 km in the past 10 min | Proxy for local demand surge |
| Demand | Promo active flag | Surges volume and often prep complexity |
| Demand | Order item count and subtotal | Larger orders take longer to prepare |
| Demand | Cuisine type | Pizza and sushi prep times differ structurally |
| Supply | Idle couriers within 3 km in the past 10 min | Affects how quickly one can be dispatched |
| Supply | Demand/supply ratio in the zone | Direct proxy for courier scarcity |
| Network | Road-graph distance (store → customer) | Primary driver of last-mile time |
| Network | Free-flow travel time on that route | Separates distance from road speed |
| Network | Live or forecast rain indicator | Slows traffic and affects courier availability |
| Network | Time-of-day, day-of-week, holiday flag | Rush-hour effects and structural patterns |
| Batching | Probability of being batched with another order | Batching adds time; use predicted probability, not realized batch |
B) Leakage and Validation
Leakage sources to eliminate:
- Anything observed after pickup: actual courier ID, vehicle type,
pickup_attimestamp, realized wait-at-restaurant. - Rolling aggregates (e.g., restaurant 30-day mean prep time) computed using data beyond
created_at. Fix: point-in-time join from an event log. - Target encoding of restaurant or zone without a time cutoff — the mean leaks future orders into the encoding.
- Post-event signals: customer ratings, refund flags, support tickets, the platform's own "late" label.
- Realized batch size: you know the probability of batching at order creation, but not the actual batch composition.
- Traffic or weather data revised after the fact. Use the value that was available at
created_at.
Splits (example using August–September data):
- Train: Aug 1–24
- Validation: Aug 25–31 (used for early stopping and hyperparameter search)
- Test: Sep 1–7, touched exactly once
Add an embargo gap equal to the longest feature window (e.g., 1 day) at each boundary so trailing aggregates do not straddle the split.
Rolling-origin CV inside August: train on Aug 1–10, validate on 11–14; train on 1–14, validate on 15–18; and so on. Report mean and variance of MAE across folds. This surfaces instability across weekdays vs weekends before you ever touch the test set.
Cross-city transfer: pooling helps sparse cities but distributions shift (road speed, cuisine mix, courier density). Mitigations: include city-normalized features (distance / city median speed), add a city embedding, or use importance weighting from a domain classifier (weight = p / (1 − p) where p is the probability of belonging to the target city). Always validate only on the target city.
C) Modeling
| Variant | Loss | Output | When to use |
|---|---|---|---|
| GBM, MSE | L2 | Conditional mean | Baseline; sensitive to outliers on long trips |
| GBM, Huber | Quadratic near zero, linear in tails | Robust mean | Better when stuck-order outliers are common; tune δ ≈ 5–8 min |
| GBM, MAE | L1 | Conditional median (P50) | When you care about the median, not the mean |
| Quantile GBM | Pinball: ρ_τ(u) = u·(τ − 1[u<0]) | P10, P50, P90 jointly | When downstream decisions depend on the full distribution |
ETA residuals are right-skewed and heteroscedastic (longer trips have wider variance), so a single point estimate hides meaningful uncertainty. Training LightGBM with objective=quantile at τ ∈ {0.1, 0.5, 0.9} gives you an uncertainty band. Enforce non-crossing by sorting the three quantile predictions at inference time, or model P90 − P50 as a positive target separately.
Useful explicit interactions: distance × hour (rush-hour inflation), rain × supply_ratio (weather doubles the courier shortage effect), queue_depth × restaurant_prep_P90 (busy restaurants with slow kitchens stack badly), promo × cuisine (promotional surges hit some cuisines harder).
Regularization to tune: num_leaves / max_depth (overfitting risk on rare restaurants), min_data_in_leaf (critical for low-volume merchants), feature_fraction and bagging_fraction (variance reduction), and learning rate with early stopping on the validation week.
D) Evaluation and Calibration
Point metrics on the test week: MAE, median AE, P90 of |error|, and signed mean error (bias). Break these down by city, time-of-day bucket, and distance quintile.
Interval metrics: empirical coverage of the [P10, P90] interval (target: 80%) and mean interval width (a model that quotes [0, ∞) has perfect coverage but is useless).
Quantile calibration: for each τ on a grid from 0.05 to 0.95, compute ĉ(τ) = mean(y ≤ q̂_τ). Plot ĉ(τ) against τ — the diagonal is perfect calibration. Define calibration error as ECE_q = mean_τ |ĉ(τ) − τ|. Also check conditional calibration: bin orders by predicted P50 and verify coverage is ~80% within each bin, since marginal calibration can hide systematic bias on long trips.
Post-hoc fix without retraining: conformalized quantile regression. On the validation week, compute conformity scores s_i = max(q̂_lo − y_i, y_i − q̂_hi). Take the ceil((n+1)(1−α)/n) quantile of these scores as a correction margin and widen all future intervals by that amount. This gives a finite-sample coverage guarantee with no model changes.
E) Cost-Sensitive Decision-Making
Optimal quoted ETA (newsvendor framing):
Let c_late be the cost per minute the actual delivery exceeds the quote, and c_early the cost per minute the quote exceeds actual delivery. Expected cost as a function of quoted value q is:
E[cost(q)] = c_late · E(y − q)⁺ + c_early · E(q − y)⁺
Setting the derivative to zero gives: F(q*) = c_late / (c_late + c_early)
So the optimal quote is the c_late / (c_late + c_early) quantile of the predictive distribution. If late delivery costs three times as much as over-quoting, quote the P75. This is pure post-hoc thresholding — costs can change without retraining.
Dispatch timing: let c_idle be the per-minute cost of a courier waiting at the restaurant and c_cold the per-minute cost of food sitting ready without a courier. The optimal arrival time at the restaurant is F_P⁻¹(c_idle / (c_idle + c_cold)) where F_P is the predictive CDF for restaurant-ready time. If cold food is very costly, dispatch early (low quantile).
Step penalties (e.g., a flat refund if more than 10 min late): these are not linear, so integrate expected cost over the full predictive distribution using a grid search on q, or train with a custom cost-weighted objective.
F) Explainability and Fairness
Compute SHAP values on the test week to get global feature importance and per-order attributions. Spot-check high-error orders: do they share a driver (SHAP for courier ID is high) or a neighborhood? That reveals leakage or proxy discrimination.
Fairness checks:
- Coverage disparity: is the [P10, P90] interval hitting 80% equally across high-income and low-income zip codes? Systematic under-coverage in some neighborhoods means those customers are being misled.
- Bias by vehicle type or courier demographic: if courier vehicle is in the feature set, verify SHAP attributions and check whether quotes differ unexpectedly by vehicle.
Mitigations: monotonic constraints (e.g., distance must not negatively affect ETA), group calibration (run conformalization separately per group), and removing or replacing proxy features that correlate with protected attributes.
G) Production System
Feature store: pre-compute slow features (restaurant prep-time rolling aggregates, zone demand/supply ratios) in batch and serve them via low-latency key-value lookups. Compute fast features (live courier density, current queue depth) from a streaming pipeline with sub-second staleness.
Inference latency: target under 100 ms p99 at the checkout endpoint. LightGBM inference is fast; the bottleneck is usually the feature join. Cache aggressively for high-traffic restaurants.
Retraining cadence: weekly retrain on a rolling window (e.g., the past 60 days) is a reasonable default. Trigger an unscheduled retrain if drift metrics exceed thresholds.
Drift detection: monitor Population Stability Index (PSI) and Kolmogorov-Smirnov statistics on key input features (demand/supply ratio, distance distribution) weekly. Monitor label drift separately — a shift in eta_minutes distribution could be real-world change or a pipeline bug. Set alert thresholds (e.g., PSI > 0.2) and route alerts to an on-call rotation.
Online A/B plan: run a geo-split or time-based holdout rather than a user-level split, since ETA affects dispatch logic and courier assignments — interleaving creates interference. Primary metric: customer-reported accuracy or late-delivery rate. Guardrail metrics: courier utilization, order cancellation rate, and support ticket volume. Pre-register the minimum detectable effect and expected duration before launch to avoid peeking bias.