Design an ML System to Forecast Shipment Arrival Time
Machine LearningModel answerLast updated
Design an end-to-end ML system that predicts when a parcel will arrive, covering target definition, features, leakage prevention, uncertainty, and production monitoring.
Shipment Arrival Time Forecasting
An e-commerce platform wants to show customers a reliable delivery estimate at every stage of their order's journey — from checkout through final drop-off. You have access to historical shipment data including order timestamps, origin and destination locations, carrier and service tier selections, logistics scan events, route-level weather forecasts, and holiday calendars.
Design a machine learning system that predicts how long a shipment will take to arrive. Your answer should address:
- Target definition and prediction timing — What exactly are you predicting, and at which points in the shipment lifecycle do you generate a prediction?
- Feature engineering and model selection — Which signals matter most, and what model family fits this problem well?
- Missing or delayed data and leakage prevention — Scan events arrive late and in batches. How do you prevent future information from contaminating training?
- Offline and online evaluation — How do you measure model quality before and after deployment?
- Prediction intervals and product integration — How do you produce calibrated uncertainty estimates, and how should the product surface them?
- Production monitoring and retraining — How do you detect when the model degrades and keep it fresh?
There is no single correct architecture. The interviewer is looking for clear reasoning about trade-offs, awareness of the failure modes specific to logistics forecasting, and a design that would actually work under real operational conditions.
Hints
Hint 1
Think carefully about what information is actually available at each prediction stage — checkout, label creation, first scan, and in-transit updates each have different feature sets. Define one prediction problem per stage rather than trying to handle all stages with the same snapshot.
Hint 2
The most common source of leakage in this problem is not using point-in-time correct feature computation. Any aggregate — such as a carrier's historical median transit time or a warehouse's handling time — must be computed as of the prediction timestamp, not as of today. Also, always use ingestion time when building scan-based features, never event time.
Hint 3
Uncertainty is a first-class deliverable, not a nice-to-have. Think about how a p10/p50/p90 prediction translates into a product experience differently from a single point estimate, and how you would verify that your p90 interval actually covers 90% of outcomes in practice.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a system design question, not a modeling contest. The interviewer wants to see you convert a loosely stated "predict ETA" requirement into a precise, leakage-free prediction problem with honest uncertainty and a self-correcting production loop. Candidates who spend the first few minutes on target definition and leakage prevention consistently outperform those who jump straight to a model choice.
1. Clarify Scope Before Designing
Before drawing any architecture, pin down a few things:
- Who consumes the prediction? A checkout promise ("arrives by Friday"), a tracking page that refreshes on each scan, a merchant dashboard, and a proactive delay alert all have different latency requirements and different costs of being wrong.
- Assumed scale: 5M shipments per day, ~10 scan events per shipment. Checkout inference needs sub-50ms p99. Tracking page updates can be event-driven and tolerate a few minutes of lag.
- Asymmetric error cost: a late delivery damages customer trust far more than an early one, so optimizing only mean error is not enough. This motivates quantile outputs.
2. Target Definition and Prediction Stages
What to predict: remaining transit time in hours from prediction timestamp to delivered timestamp, log-transformed to reduce right skew. Business-hours to delivery is a useful parallel target for checkout promises that reference calendar dates.
Why remaining time, not total transit time: the same model family can serve every stage of the journey, because the prediction is always "how much longer from now."
Label pitfalls:
- Use the carrier's delivered scan as ground truth, not an estimated date.
- Lost and returned shipments should be excluded from the regression and handled by a separate exception-probability model.
- Shipments that have not yet been delivered are right-censored. Dropping them biases the training set toward fast deliveries in the most recent window. Either enforce a maturity window (wait 21 days before including a shipment in training) or use a survival model that handles censoring natively.
Four prediction stages, each a distinct snapshot:
| Stage | Trigger | Newly available signals |
|---|---|---|
| T0 Checkout | Before label exists | Destination ZIP, candidate carrier/service, cart contents, time of day |
| T1 Label created | Label purchased | Confirmed carrier/service, package dimensions and weight |
| T2 First carrier scan | Pickup confirmed | Actual handoff time, label-to-handoff lag |
| T3 In-transit | Every subsequent scan | Current facility, scan sequence, dwell time, overdue status |
Start with three separate models — one for T0/T1 (their feature sets are similar), one for T2, and one for T3 — rather than a single model with heavy masking. Their feature availability, latency requirements, and error tolerances differ enough to justify the split.
3. Features
- Route: origin/destination ZIP3 pair, straight-line distance, zone, urban vs rural flag, cross-border flag.
- Carrier and service tier: carrier × service level, and target-encoded historical lane transit distributions (rolling p50/p90 over the past 7 and 28 days, computed strictly before prediction time).
- Temporal: day of week, hour of label creation relative to carrier cutoff, days until the next public holiday, peak-season flag. Merchant-level handling time (label creation to first scan) is often the largest variance source at T0 and T1.
- Live conditions: weather severity forecast along the route for the upcoming days (forecast data only — not observed actuals), carrier network congestion index, active service disruption flags.
- In-transit (T3 only): last scan facility type, hours since last scan, total scans so far, whether the package is out for delivery, and that facility's recent median dwell time.
4. Model Selection
- Baseline: lane × carrier × service historical median transit time. You must beat this before claiming success. It is often surprisingly competitive.
- Primary model: gradient-boosted trees (LightGBM) with quantile loss at p10, p50, and p90, or a distributional variant like NGBoost that directly outputs a parametric distribution. GBDTs handle heterogeneous tabular features, tolerate missingness, and are fast at serving time.
- Survival framing as an alternative: a discrete-time hazard model predicts P(delivered by day d) for d = 1…10. It handles censoring cleanly, produces a full distribution, and makes "probability of on-time delivery" a direct output rather than a derived one.
- Sequence models for T3: a GRU or transformer over the ordered scan event sequence can capture patterns that hand-crafted dwell features miss. Add it only if an ablation study shows meaningful lift over the tabular model. Justify sequence complexity with evidence, not by default.
5. Missing and Delayed Scans, and Leakage Prevention
Scan timing: carriers batch-upload scan events, so a scan's event_ts can precede its ingested_ts by hours. Always build features from ingestion time — the timestamp when your system actually saw the event. This is the single most important leakage point in logistics models and the one most commonly missed.
Missingness as signal: "hours since last scan" and "is the next expected scan overdue" are explicit features, not nulls to impute. Prolonged silence is predictive of delays.
Leakage checklist:
- Every aggregate (lane median, merchant handling time, facility dwell) is computed as of
prediction_tsusing a point-in-time feature store. - No feature derived from the delivered scan, the final carrier status code, or any post-hoc exception label.
- Weather features use forecast data available at prediction time, not observed actuals.
- Training splits are time-based only — train on months 1–9, validate on month 10, test on months 11–12 including at least one peak period. Random splits allow lane-level congestion patterns to leak across folds.
- When a single shipment contributes multiple T3 snapshots, all of them belong to one side of the split.
6. Offline and Online Evaluation
Offline:
- MAE in hours and business days, sliced by stage, carrier, lane, and peak vs non-peak.
- Pinball loss per quantile (p10/p50/p90).
- Coverage: the p10–p90 interval should contain roughly 80% of actual outcomes, checked per carrier and per lane rather than only in aggregate.
- On-time-promise rate and promise slack — how tightly can you quote a date without increasing miss rate?
- Backtest across at least one peak shopping season. Most failure modes surface during high-volume periods and weather events.
Online:
- Shadow the baseline model before full rollout.
- A/B test on the checkout promise: measure the conversion rate of showing a tighter date range and the customer contact rate when predictions miss.
- Track coverage and MAE as a rolling metric per cohort of shipments by label-creation date.
7. Calibrated Uncertainty and Product Use
Raw quantile regression outputs often drift from their nominal coverage levels across slices. Apply conformalized quantile regression on a recent holdout: compute signed residual adjustments per segment (carrier × stage) so that the p90 interval genuinely covers 90% of outcomes within each segment. Recompute adjustments weekly, since conformal calibration assumes exchangeability and model or distribution drift breaks that assumption.
Product surfaces:
- Checkout promise: display a date range derived from p10 and p90 ("Arrives March 4–6"). The p50 drives internal SLA tracking.
- Tracking page: show "Expected today by 8 PM" with a confidence band. If P(on-time) falls below a threshold, proactively surface an alert rather than waiting for the customer to notice.
- Merchant dashboard: expose p90 transit time by lane so sellers can set accurate handling promises.
8. Production Monitoring and Retraining
- Data quality monitors: alert on scan ingestion lag spikes, sudden drops in scan completeness per carrier, and feature distribution shift (PSI on key features).
- Prediction quality monitors: track rolling MAE and coverage on matured shipments with a 7- and 21-day lag window. Coverage drift on a specific carrier or lane is usually the first signal of a real-world change.
- Retraining cadence: weekly incremental retraining under normal conditions. Trigger immediate retraining on large coverage drops (>5 pp) or after major network events like a carrier disruption or a natural disaster.
- Model versioning: keep the previous model live as a fallback and use a canary release for new versions, promoting to full traffic only after coverage and MAE hold steady for 48 hours.
Common Mistakes to Avoid
- Using event time instead of ingestion time for scan-based features — this leaks future scan data into training.
- Dropping right-censored shipments instead of modeling them properly — this biases the model toward fast lanes.
- Evaluating only mean error and ignoring interval coverage — a model with good MAE but poorly calibrated intervals is not production-safe.
- Training on a random split — lane-level congestion is a strong seasonal signal that contaminates folds.
- Treating uncertainty as a post-hoc addition rather than designing the loss function around it from the start.