Predicting Delivery Lateness Risk for a Food Delivery Platform
Machine LearningModel answerLast updated
Design an ML system to forecast whether orders will arrive after their promised time, covering feature engineering, temporal validation, calibration, and production deployment.
You're building a machine learning system for a food delivery platform to predict whether orders will be delivered late. An order is considered late if it arrives after the estimated delivery time that was shown to the customer when they placed the order.
You have access to historical order data including merchant information, location details, order attributes, delivery logistics, and final outcomes.
Address the following:
-
Target and data splitting: Define the prediction target precisely. Design a time-based train/validation/test strategy that prevents information leakage from future data. Specify concrete date ranges and explain your embargo periods.
-
Feature engineering: Identify 10+ features that would be available at order placement and would have strong predictive signal. Consider merchant patterns, logistics capacity, geography, timing, and external factors.
-
Leakage prevention: List 5+ sources of potential data leakage in this problem and explain how you would prevent each one.
-
Evaluation and decisions: Choose appropriate metrics for both ranking quality and probability calibration. Define how you would set decision thresholds based on business costs, and estimate the potential financial impact.
-
Production deployment: Outline a staged rollout plan from shadow mode through A/B testing. Describe how you would monitor model performance over time and handle drift and recalibration needs.
-
Cold-start and seasonality: Explain how you would handle new merchants or markets with limited history, and how you would account for time-based patterns like holidays or day-of-week effects.
Your answer should demonstrate production ML thinking: temporal correctness, calibrated probabilities, business-driven decision making, and operational robustness.
Hints
Hint 1
Consider what information is truly known at order creation versus what becomes available later during fulfillment
Hint 2
The difference between your internal estimate and the customer-facing promise is often highly predictive
Hint 3
Random train/test splits will give you overly optimistic results - orders from the same time period should stay together
Hint 4
Calibration matters as much as discrimination when you're making cost-based decisions
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Delivery Lateness Prediction System
This problem tests your ability to build production ML systems with temporal correctness, proper evaluation, and business impact quantification. I'll use gradient boosting (LightGBM or XGBoost) with a calibration layer as the baseline approach, then focus on the challenging aspects.
1. Target Definition and Temporal Splitting
Target variable: is_late = 1 if actual_delivery_time > promised_delivery_time, where:
promised_delivery_timeis the ETA displayed at checkout (the first estimate shown)- We use strict inequality with no grace period for the primary target
- Also capture
minutes_lateas a regression target for more nuanced understanding - Exclude cancelled orders (they're censored, not on-time), test orders, and obvious data errors
- Wait 48-72 hours after delivery before considering labels final to handle resolution delays
Splitting strategy (assuming 18 months of data from Jan 2023 - Jun 2024):
- Train: Jan 1, 2023 → Feb 29, 2024 (14 months, includes full seasonal cycle)
- Gap: Mar 1-7, 2024 (dropped to prevent feature bleed)
- Validation: Mar 8 → Apr 30, 2024 (tune hyperparameters, fit calibrator)
- Gap: May 1-7, 2024 (dropped)
- Test: May 8 → Jun 30, 2024 (final evaluation, touched once)
The 7-day gaps prevent rolling aggregates (which typically span 7-28 days) from bleeding future information backward. Never use random splitting—orders close in time are highly correlated and random splits artificially inflate metrics by 5-10 AUROC points.
Also implement rolling-window backtesting with monthly folds to validate temporal stability.
2. Production-Safe Features
All features computed as of order creation time, respecting pipeline latency:
- Merchant on-time rate by hour-of-week (28-day trailing window, Bayesian-shrunk to global prior)
- Merchant prep time percentiles (p50, p75, p90 of confirmation-to-ready time by hour-of-week)
- Current merchant load: number of open orders in last 10 minutes, current order complexity (item count, special instructions)
- Zone courier availability: ratio of idle couriers to unassigned orders in the delivery zone (5-minute snapshot)
- Recent zone performance: percentage of orders created 60-90 minutes ago that missed their promise (only counting resolved orders)
- Distance metrics: straight-line and routing-estimated distance from merchant to customer, plus estimated courier-to-merchant distance based on current courier distribution
- Traffic conditions: routing service's travel time estimate and its ratio to free-flow baseline
- Weather forecast (not actual): precipitation probability, temperature, wind speed from forecast issued before order creation
- Active incentives: surge multiplier or courier bonuses in effect (proxy for known capacity shortage)
- Quote tightness: promised time minus internal baseline estimate (tight quotes = higher risk)
- Temporal features: cyclic-encoded hour-of-week, holiday flags, special events, minutes until merchant closing time
- Customer history: order frequency tier, past late-order complaint rate (used for action prioritization)
- Order complexity flags: alcohol requiring ID verification, large/catering orders, delivery to apartment building (historical dropoff time at that address type)
- Merchant integration type: POS integration vs tablet vs phone orders (affects confirmation speed)
3. Leakage Hazards and Mitigations
-
Post-creation events: Features derived from courier assignment, actual pickup time, or in-transit events. Fix: Maintain strict feature allowlist with
available_attimestamps; enforceavailable_at <= created_atin pipeline. -
Non-causal time windows: Using "today's average" or centered rolling windows that include future orders. Fix: Only use strictly trailing windows ending at
created_at - pipeline_latency. -
Target leakage in aggregates: Computing merchant late-rate over all data includes the current row's label. Fix: Use out-of-time aggregation with only past data, exclude current order from its own features.
-
Incomplete outcomes in recent metrics: Including orders that haven't finished yet biases recent performance estimates (fast completions appear first). Fix: Only aggregate over orders that have definitely resolved (delivery time < created_at or past their promise).
-
Future information in external data: Using actual weather instead of forecast, or updated traffic after order creation. Fix: Join forecast snapshots from before creation time; version all external data sources.
4. Metrics, Thresholds, and Business Impact
Ranking metrics:
- AUROC for overall discrimination power
- Precision-Recall AUC (base rate ~15% late, so more informative than AUROC)
- Recall@k where k is the operational intervention budget
Calibration metrics:
- Brier score and log-loss
- Calibration curve slope (should equal 1.0) and intercept (should equal 0.0)
- Expected Calibration Error (ECE) and reliability plots
- Per-segment calibration (by market, time-of-day) since global calibration can hide local miscalibration
Decision threshold via cost analysis:
Assume intervention costs $1.20 (courier incentive + ETA buffer) and prevents 35% of late deliveries. Average late delivery costs $7.00 (partial refund $2.50 + churn impact $4.50).
Expected value of intervention = p × 0.35 × 7.00 - 1.20
Act when p > 1.20 / (0.35 × 7.00) = 0.49
This cost-based threshold requires calibrated probabilities. Adjust per customer segment using tolerance signals.
Impact projection: With 800K daily orders, 120K late (15% base rate):
- Flag 60K high-risk orders (mean p = 0.65)
- Daily value = 60K × (0.65 × 0.35 × 7.00 - 1.20) = 60K × 0.36 = ~$21,600/day
- Annual impact ~$7.9M (treat as upper bound until A/B validated)
5. Production Rollout and Monitoring
Staged deployment:
-
Shadow mode (2 weeks): Score all orders but take no action. Compare predictions to actual outcomes; validate latency SLAs; check for infrastructure issues.
-
Gated rollout (2 weeks): Enable interventions for 5% of predicted-risky orders; monitor downstream metrics (merchant experience, courier acceptance rates, customer satisfaction).
-
A/B test (4 weeks): 10% treatment, 10% control, 80% excluded. Primary metric: late rate. Guardrails: order volume, cancellation rate, customer satisfaction, courier earnings. Power analysis: need ~50K orders per arm for 2 percentage point late-rate lift at 80% power.
-
Scale to 100% if A/B confirms net positive impact.
Monitoring:
- Prediction distribution drift: track score distribution shifts via KL divergence or PSI (Population Stability Index)
- Calibration tracking: weekly reliability plots and Brier score by market
- Feature drift: monitor key feature means and quantiles
- Outcome monitoring: actual late rate by prediction bucket
- Alert thresholds: flag if ECE > 0.05, Brier increases >10%, or score distribution shifts significantly
Recalibration:
- Fit Platt scaling or isotonic regression on validation set initially
- Retrain calibrator monthly on recent data (sliding 4-week window)
- Full model retrain quarterly or when drift alerts trigger
- Use time-stratified retraining to preserve temporal ordering
6. Cold-Start and Seasonality
New merchant/market handling:
- Hierarchical Bayesian estimates: shrink new merchant's on-time rate toward cuisine-type and market priors (e.g., new pizza place → pizza category average in that city)
- Pooled baselines: use market-level or cuisine-level features until merchant accumulates 50+ orders
- Entity embeddings: learn merchant and zone embeddings jointly with other features, allowing similar entities to share representation
- Gradual confidence: weight new entity predictions lower in decision-making until sufficient history
Seasonality:
- Cyclic temporal encoding: sine/cosine transforms of hour-of-day, day-of-week, day-of-year
- Explicit holiday features: major holidays, local events, sporting events, weather emergencies
- Seasonal reweighting: in training, slightly upweight recent data (last 3 months get 1.2× weight) to adapt to long-term trends
- Hour-of-week interaction terms: merchant performance varies significantly by day-part; model this explicitly
- Forecast bridging: during major shifts (e.g., pandemic, new market launch), retrain more frequently or use domain adaptation techniques
Common mistakes to avoid:
- Using accuracy instead of proper scoring rules
- Setting thresholds based on F1 score rather than business costs
- Ignoring calibration entirely
- Training on all-time data without temporal splits
- Not having a plan for model decay and retraining
This system requires continuous maintenance: weekly calibration checks, monthly recalibration, quarterly retraining, and ongoing feature pipeline validation. The model is never "done"—it's a production service requiring operational discipline.