Route Each Order to One of Two Suppliers to Minimize Cost
Machine LearningModel answerLast updated
Design a constrained decision model that selects a supplier per order to minimize expected total cost while keeping SLA attainment at or above 95% and staying within a monthly budget.
Supplier Routing Under Cost and SLA Constraints
Your company sources inventory through two third-party suppliers, Supplier A and Supplier B. For every incoming order you must pick exactly one. You have historical order-level records with the following fields:
| Field | Description |
|---|---|
lead_time_days | Actual days from order to delivery |
unit_price | Per-unit cost quoted by that supplier |
on_time_rate | Trailing delivery punctuality rate |
defect_rate | Trailing fraction of units failing QC |
min_order_qty | Supplier minimum order quantity |
capacity | Supplier monthly unit capacity |
distance_km | Warehouse-to-destination distance |
historical_cancellation_rate | Fraction of orders the supplier cancelled |
late_penalty_per_order | Fixed fee charged when SLA is missed |
stockout_cost_per_day | Cost per day of inventory gap |
sla_met | Whether the order met the agreed lead-time SLA |
Your goal is to design a complete decisioning system. Address each of the following:
-
Objective and decision rule. Write out the expected-cost formula for routing order i to supplier v, covering price, expected late penalties, expected quality failures, and stockout costs. Then state the constrained optimization problem — one routing per order, SLA attainment ≥ 95% across the month, a hard budget cap, and per-supplier capacity limits. Show how Lagrangian relaxation reduces this to a per-order scoring rule.
-
Feature engineering and modeling. List features available at decision time, including order-level, supplier-level, and time-varying supplier state features. Recommend a modeling approach for each outcome (lateness probability, lead-time distribution, defect rate, cancellation rate), and justify your choices over alternatives such as a fixed-threshold cost-sensitive classifier, pairwise learning-to-rank, or a contextual bandit. Address class imbalance (SLA misses are rare, around 5%) and non-stationarity in supplier performance.
-
Selection bias. Historical routing was not random — certain order types were always sent to one supplier. Explain how this causes confounding, how you would estimate and use propensity scores, how you would stabilize inverse-probability weights, and what doubly robust estimation buys you here.
-
Offline evaluation. Describe a sound evaluation pipeline: how to split time-series data, how to estimate the expected cost and SLA attainment of a candidate policy without deploying it, and how to choose operating-point hyperparameters (the Lagrange multipliers) against a cost–SLA frontier.
-
Online rollout and operational concerns. Lay out a staged rollout with safety guardrails. Describe how you would handle a new supplier with no history (cold start) and how you would enforce per-supplier capacity limits at serving time. If Supplier A consistently looks cheaper in the model but late penalties are rising in production, walk through the diagnostics you would run.
Hints
Hint 1
Start by separating the problem into three independent layers: outcome prediction, constrained decision-making, and counterfactual evaluation. The modeling choices in each layer are different, and conflating them is the most common mistake.
Hint 2
The stockout cost depends on how much the actual lead time exceeds your inventory buffer — that requires a lead-time *distribution* (e.g., quantile regression or a survival model), not just a mean prediction. Think about what happens to the cost formula if delivery is 3 days late versus 10 days late.
Hint 3
Historical data only shows outcomes for the supplier that was actually chosen. Before you can compare policies, you need to adjust for the fact that hard orders may have been systematically routed to the better supplier — or the worse one. Propensity modeling addresses this, but positivity (overlap) is a hard requirement you must check.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
This is a decision problem first and a prediction problem second. Three layers need to be built independently before being composed:
- Outcome models — estimate lateness probability, lead-time distribution, defect rate, and cancellation rate for each (order, supplier) pair.
- Constrained decision layer — turn those estimates into a routing choice that satisfies SLA, budget, and capacity constraints.
- Counterfactual evaluation and safe rollout — historical data only reveals outcomes for the supplier that was actually used, so naive training and evaluation will be biased.
1. Objective Function and Decision Rule
For order i routed to supplier v, define expected cost as:
E[C_iv] = q_i · p_v # purchase price
+ P(late | x_i, v) · L_v # expected late penalty
+ q_i · d̂_iv · (c_replace + c_rework) # expected quality failure cost
+ E[max(0, T_iv − S_i) | x_i, v] · s_i # expected stockout cost
+ P(cancel | x_i, v) · c_cancel # re-sourcing cost on cancellation
where T_iv is the random lead time, S_i is days of on-hand inventory, s_i is stockout_cost_per_day, and L_v is late_penalty_per_order. The stockout term requires the distribution of lead time — a quantile or survival model — not a point estimate.
The monthly constrained problem over N orders is:
min Σ_i Σ_v x_iv · E[C_iv]
s.t. Σ_v x_iv = 1, x_iv ∈ {0,1} # route each order once
(1/N) Σ_i Σ_v x_iv · P(SLA met | x_i, v) ≥ 0.95 # SLA floor
Σ_i Σ_v x_iv · q_i · p_v ≤ Budget # spend cap
Σ_i x_iv · q_i ≤ Cap_v ∀ v # supplier capacity
Lagrangian relaxation with multipliers λ (SLA) and μ (budget) yields a per-order scoring rule:
score_iv = E[C_iv] − λ · P(SLA met | x_i, v) + μ · q_i · p_v
route to v* = argmin_v score_iv
Setting λ = μ = 0 recovers unconstrained expected-cost minimization. λ and μ are tuned on held-out data using a cost–SLA frontier sweep (see Section 4).
2. Features and Modeling
Features available at decision time:
- Order-level: quantity, required delivery date, days of inventory slack, distance_km, SKU category, urgency flag, whether
min_order_qtyis satisfied per supplier. - Supplier snapshot: quoted unit price, quoted lead time, rolling 7/30/90-day on-time rate, defect rate, cancellation rate, current utilization vs. capacity, open-order backlog.
- Calendar: week of year, holidays, known peak seasons.
- Interactions: supplier × region, supplier × quantity bucket.
Trailing rates must be lagged to avoid leakage: the 30-day on-time rate for today's order should exclude today.
Recommended models:
| Outcome | Model | Reason |
|---|---|---|
| P(late) | Calibrated gradient-boosted classifier | Handles non-linearity, calibrate with isotonic regression per supplier |
| Lead time distribution | Quantile GBM or discrete-time survival model | Censored open orders; needed for stockout cost term |
| Defect rate | Beta-binomial with hierarchical shrinkage | Sparse per-segment counts benefit from partial pooling |
| Cancellation rate | Same as defect rate | Similar data sparsity |
Why not the common alternatives:
- Fixed-threshold cost-sensitive classifier assumes a constant cost ratio. Here,
late_penalty,stockout_cost_per_day, and quantity all vary per order — you need calibrated probabilities multiplied by per-order costs. - Pairwise learning-to-rank produces relative preferences but cannot support the absolute probability values needed to evaluate SLA and dollar constraints.
- Contextual bandit alone is appealing for exploration but reward delay is weeks long and there are only two arms. Better to use Thompson sampling as a thin exploration wrapper over the outcome models.
Class imbalance (~5% SLA misses): use class weights or downsampling during training, then recalibrate. Evaluate with PR-AUC and Brier score, not accuracy.
Non-stationarity: use time-decayed sample weights, retrain weekly, and monitor feature PSI and per-vendor calibration error by week. Shrink toward recent trailing rates when drift is detected.
3. Selection Bias
Historical routing was not random. Urgent orders may have always gone to Supplier B; large orders may have always gone to A. Naive models confound supplier quality with order difficulty.
Propensity estimation: fit e(x) = P(route = A | x) on decision-time features using logistic regression or a calibrated GBM. Verify overlap with propensity histograms. Where the old rule was deterministic, positivity fails — you cannot learn counterfactuals there without randomized exploration, so flag those regions and exclude them from policy evaluation.
Stabilized IPW: use w = P(v) / e_v(x). Clip at the 99th percentile or a maximum of 20 to prevent extreme weights from dominating. Self-normalized IPW reduces variance further.
Doubly robust (DR) estimator: combine the outcome model's prediction with an IPW-weighted residual correction. DR stays consistent if either the propensity model or the outcome model is correctly specified — a useful robustness property given how noisy propensities can be.
Going forward, log the propensity of every routing decision and introduce a small ε-randomization so future data supports valid off-policy evaluation.
4. Offline Evaluation
Splits: forward-chaining only — train on months 1–6, evaluate on month 7, then roll forward. Never shuffle time-series data. Respect label delay: SLA outcomes resolve only after delivery, so hold out a buffer window.
Policy value estimation: for each candidate policy, compute DR-estimated cost per order and SLA attainment. Report bootstrap 95% confidence intervals. Compare against three baselines: always-A, always-B, and the historical routing rule.
Operating-point selection: sweep λ and μ across a grid to trace a cost vs. SLA-attainment frontier. Select the cheapest policy where the lower confidence bound of SLA attainment is ≥ 95% and expected spend is within budget. Using the LCB rather than the point estimate provides a safety margin before deployment.
5. Online Rollout, Cold Start, and Diagnostics
Staged rollout:
- Shadow mode — log model decisions alongside actual routing, no impact.
- Route 5–10% of orders via the model with ε-randomization; log propensities.
- Ramp up in 10% increments. Trigger automatic rollback if the LCB of SLA attainment falls below 95% in sequential monitoring.
Capacity enforcement: implement a greedy assignment layer on top of the scoring model. Score all pending orders at batch time, sort by the margin score_iB − score_iA, and route to A greedily until Supplier A's capacity is consumed, then fall back to B. This is a lightweight knapsack approximation; for stricter guarantees, solve a small LP at dispatch time.
Cold start for a new supplier: initialize outcome models with industry-average priors or the other supplier's estimates with high uncertainty. Use Thompson sampling to route a small fraction of exploratory orders and update priors as outcomes arrive. Restrict exploratory routing to low-risk, low-urgency orders until uncertainty shrinks.
Diagnosing rising late penalties when A appears cheaper:
- Check calibration: is
P(late | A)still accurate, or has A's recent performance drifted? - Check label delay: are penalties being attributed to the correct order cohort?
- Check selection composition: has the mix of orders routed to A shifted toward harder orders, making the model's features stale?
- Decompose the cost delta into price savings vs. penalty increase. If A's penalty cost now exceeds its price advantage, λ needs re-tuning or A's capacity should be throttled.
- Run a PSI check on features of orders routed to A versus the training distribution.
The root cause is usually one of three things: model calibration drift, covariate shift in routed order mix, or a real change in supplier performance that retraining has not yet captured.