Predicting Late Arrivals: Leakage-Safe Flight Delay Modeling
Machine LearningModel answerLast updated
Design a leakage-safe pipeline that predicts 15+ minute late arrivals from pre-departure data: audits, time-based validation, models, explanations, stress tests, and an A/B plan.
An airline analytics team wants a model that flags, ahead of time, domestic flights likely to land at least 15 minutes behind schedule. Predictions may only use information that exists by the scheduled departure time.
You have a historical table of about 50 million flights with these columns:
flight_date(YYYY-MM-DD),sched_dep_time(local HH:MM)carrier,dep_airport,arr_airport,route_id,aircraft_taildistance_miles,holiday_flagweather_dep_*andweather_arr_*(temperature, precipitation, visibility)dep_delay_min,arr_delay_min
The label is late15 = 1 when arr_delay_min >= 15, otherwise 0.
Write up how you would approach each of the following.
- Exploratory analysis. List the specific checks and plots you would run to detect leakage, drift in the label rate, and rare-category problems. Name at least three concrete leakage risks in these columns and how you would neutralize each one.
- Validation. Propose a time-based cross-validation scheme that respects seasonality and avoids look-ahead. Give exact train, validation, and test date windows and justify them.
- Modeling. Choose two candidates (one linear, one tree-based). Describe feature engineering (cyclical time encodings, rolling airport and carrier aggregates, weather joins), how you treat class imbalance, your primary metrics, and how you would select and calibrate an operating threshold.
- Explainability and robustness. Explain how to use SHAP and partial dependence responsibly on time-ordered data, and describe at least two stress tests of stability across airports or carriers (for example, unseen storms or newly launched routes).
- Deployment. Define an inference contract (latency, feature freshness, failure modes) and outline one A/B test, such as proactive rebooking or gate assignment, with success metrics and guardrails.
Hints
Hint 1
Start by fixing a single prediction timestamp (for example a couple of hours before scheduled departure) and ask of every column and every aggregate: is it known by then?
Hint 2
For validation, think expanding windows ordered in time, an embargo gap equal to your longest rolling-feature window, and a final untouched full year so every season is represented.
Hint 3
Keep probabilities honest: avoid resampling, calibrate on recent held-out data, and derive the threshold from explicit costs of a missed late flight versus an unnecessary intervention.
Hint 4
For the A/B test, randomize at a unit that avoids interference (such as flight or hub-day), and pair a primary operational metric with guardrails like cost per action and customer complaints.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is mostly a time-and-leakage problem rather than a modeling problem. Fix the prediction time T = scheduled departure − 2 hours. Every feature, aggregate, split, and explanation must be computable using only information available at T.
1. Exploratory analysis
Checks and plots
- Single-feature AUC against
late15. Anything above roughly 0.85 is a leakage suspect.dep_delay_minwill score around 0.9. - Timestamp audit. For each column, document when its value becomes known relative to T. Weather data needs an
observed_atorissued_atfield; without one, treat it as leaky. - Label drift. Plot the daily and monthly late rate with a 28-day rolling mean, overlay holidays and the 2020-21 pandemic period, and add a month-by-weekday heatmap and a late-rate-by-scheduled-hour curve.
- Covariate drift. Monthly population stability index per feature against a reference year, plus counts of distinct routes and tails over time.
- Label integrity. Count null
arr_delay_minvalues (cancellations, diversions). Dropping them silently removes the worst days. Either treat them as positives or report them separately. - Rare categories. Rank-frequency plots for carrier, airports, route, and tail. Flag levels under about 500 rows and measure what share of validation rows have a route or tail unseen in training.
Leakage risks
| Risk | Why it leaks | Mitigation |
|---|---|---|
dep_delay_min | Realized after pushback; arrival delay is roughly departure delay plus noise | Drop as a direct feature; use only in lagged aggregates ending at D-1 |
arr_delay_min | It is the label | Use only to build the label |
weather_dep_*, weather_arr_* | Probably observed at actual departure or arrival | Use forecasts issued at or before T, or observations at T, via as-of joins |
| Rolling stats and target encodings | Computed over the full dataset or including the same day | Compute over data up to D-1 only; fit encoders inside training folds |
aircraft_tail rotation | The inbound leg's actual delay may not be known at T | Use only status reported by T, otherwise scheduled turnaround buffer |
2. Validation
Assume data spans 2018-01-01 to 2023-12-31. Use an expanding window with a 7-day embargo so 7-day rolling features never straddle the boundary.
| Fold | Train | Validate |
|---|---|---|
| 1 | 2018-01-01 to 2021-12-24 | 2022-Q1 |
| 2 | 2018-01-01 to 2022-03-24 | 2022-Q2 |
| 3 | 2018-01-01 to 2022-06-23 | 2022-Q3 |
| 4 | 2018-01-01 to 2022-09-23 | 2022-Q4 |
| Test | 2018-01-01 to 2022-12-24 | 2023 full year, used once |
Rationale: four quarterly folds cover a full seasonal cycle (winter storms, summer thunderstorms, holiday peaks); the test year is a whole untouched season set; the pandemic period gets a flag or down-weighting, and I compare against a variant that drops it. Calibration is fit on the final month of each training window, never on the validation quarter.
3. Modeling
Candidates
- L2 logistic regression with one-hot carrier and airport, hashed routes, splines on distance and weather, and cyclical time terms. A fast, interpretable baseline.
- LightGBM with native categoricals, a minimum-data-per-group setting for rare levels, and monotone constraints where physics justifies them (more precipitation never lowers risk).
Features (all as of T)
- Cyclical encodings: sin/cos of hour (period 24), day of week, and day of year; holiday flag and distance to nearest holiday.
- Rolling late rate and mean departure delay at 7/28/90 days, per carrier, origin, destination, route, and origin-by-hour, with shrinkage toward the global rate for sparse levels.
- Scheduled congestion: flights at origin and destination within ±1 hour.
- Forecast weather for departure and arrival hours plus a severe-weather indicator.
- Rotation: scheduled turn buffer, earlier legs of the tail, inbound status known at T.
- Rare levels collapsed to
OTHER; new routes fall back to origin and destination priors.
Imbalance. The positive rate is around 20%, which is moderate. Avoid resampling because it distorts probabilities. Use class weights only if PR-AUC improves, then recalibrate.
Metrics. Primary: PR-AUC and log loss. Calibration: Brier score and reliability curve. Operational: recall at a fixed precision (for example 0.6).
Threshold.
- Calibrate (isotonic, or Platt for logistic) on recent held-out data.
- Estimate costs C_FN (missed intervention) and C_FP (unneeded intervention).
- Choose t minimizing
C_FP·FP(t) + C_FN·FN(t); with good calibration this is nearC_FP / (C_FP + C_FN). - Verify t is stable across folds and respects capacity limits (such as a maximum number of actions per hub-hour).
4. Explainability and robustness
- Compute SHAP on out-of-time rows, with a background sample from the period just before the evaluation window.
- Features are strongly correlated (weather, congestion, aggregates), so report grouped SHAP and prefer ALE over PDP, which extrapolates into impossible combinations such as zero visibility in a desert summer.
- Compare importance rankings across folds; large swings suggest drift or leakage.
Stress tests
- Held-out storm events. Remove a major weather event (a hurricane or winter storm week) from training, evaluate on it, and check recall and calibration.
- New routes and airports. Evaluate only on routes absent from training to confirm the fallback priors work.
- Per-segment slices. PR-AUC, log loss, and calibration slope per hub and carrier, with bootstrap intervals and a minimum-sample rule.
- Feature-outage simulation. Null out weather or inbound status and measure degradation.
5. Deployment
Inference contract
- Scoring at T with p99 latency under about 100 ms per request, or batch refresh every 15 minutes.
- Freshness: weather forecasts under 1 hour old, schedule data under 15 minutes old, aggregates refreshed daily.
- Failure modes: if weather is missing, use climatological defaults and flag the row; if the model service is down, fall back to the last cached score or a rule-based baseline; log feature values for drift monitoring.
- Version the feature definitions so training and serving match exactly.
A/B test (proactive rebooking)
- Randomize at flight level (or hub-day if spillover exists) between control (no action) and treatment (action for flights above threshold).
- Primary metric: missed-connection rate or passenger-minutes of disruption.
- Secondary: rebooking cost per flight, customer satisfaction.
- Guardrails: cost per action, complaint rate, on-time performance of other flights, capacity violations.
- Run long enough to cover weekday and weekend patterns, with a power calculation done up front.
Common mistakes
- Random k-fold splits that leak future information.
- Using realized weather or departure delay as features.
- Resampling and then reading the probabilities as calibrated.
- Tuning on the test year.
- Interpreting PDP in regions with no data.