ML System Design · Module 30 of 47 · 11 concepts · about 14 min

Design: Demand Forecasting

A complete design for forecasting how much of each product each Kirana Kart store will sell, every night, to decide what to stock: millions of series, demand hidden by stock-outs, promotions and festivals, one global model over many series, forecasts as ranges, and turning a forecast into an order.

At work: Asked as 'design demand forecasting for a retailer', 'forecast ride demand by area' or 'capacity planning for a service'. It tests time-series thinking, batch systems at scale and the link from prediction to decision.

Requirements

What it is

Clarify:

  • goal: less waste of fresh food and fewer stock-outs, together;
  • scale: 400 stores × 50,000 products ≈ 20,000,000 series; forecasts for each of the next 7 days;
  • timing: every night, finished by 4 a.m. so purchase orders reach suppliers;
  • users: the replenishment system orders automatically; category managers review exceptions;
  • hard parts: perishables, promotions, festivals, new products and new stores, and slow sellers that sell zero most days.

Why it matters

This is a batch problem with a strict deadline, unlike the online designs.

  • Latency per forecast hardly matters; total job time does.
  • The forecast feeds a decision (how much to order), and the cost of error differs by product.

In the real world: Grocery and quick-commerce companies forecast at store × product × day, and often at finer time slots for fresh items.

Treating it as one forecast per product nationally. Stock is held per store; a national forecast cannot say how many packs to send to each store.

Framing

What it is

Forecast demand, as a range, then decide separately:

  • target: units customers would buy at each store, for each product, each day (demand, not sales; see below);
  • output: several percentiles (for example the 10th, 50th and 90th), not one number;
  • offline metrics: WAPE and bias by category and store; pinball loss for the percentiles (module 16);
  • business metrics: waste (units thrown away), stock-out rate, sales lost to stock-outs, inventory held.

Why it matters

A range is what the ordering decision needs.

  • For fresh bread, ordering at the median wastes too much; for rice, ordering at the median runs out too often.
  • The decision layer chooses the percentile per product from costs (below).

In the real world: Kirana Kart reports forecast WAPE to the data science team and waste and stock-out rates to the business; both must improve for a model to ship.

Judging the forecast only by its accuracy. A slightly less accurate forecast with less bias can produce less waste and fewer stock-outs.

Demand hidden by stock-outs

What it is

Sales are not demand. When a product sells out, sales stop at the stock level, while customers would have bought more:

  • those days are censored: sales are a floor on demand, not its value;
  • training on raw sales teaches the model to forecast too low for popular items;
  • too-low forecasts lead to smaller orders, more stock-outs, and even lower recorded sales: a feedback loop (module 22).

Fixes: mark stock-out days, estimate the missing demand (from the hour it sold out, or similar stores), or drop or down-weight censored days.

Why it matters

This is the most common hidden error in retail forecasting.

  • It hits the best-selling items hardest, which matter most.
  • Logging stock levels and sell-out times through the day is what makes the correction possible.

In the real world: Kirana Kart logs the time each product sells out at each store; a day that sold out at 6 p.m. has its demand estimated from the share usually sold after 6 p.m.

Visual example

Computed

One store's toned milk, 50 packs stocked daily. On 4 of 7 days it sold out, so the average of 46.4 sold understates demand.

Sales capped at stock on sold-out days
daysoldsold out?true demand
142No42
250Yesat least 50
350Yesat least 50
438No38
550Yesat least 50
645No45
750Yesat least 50

Averaging past sales as the baseline. On a week with frequent sell-outs, the average is well below true demand.

Data and features

What it is

Forecasting features, computed only from information available at forecast time:

  • lags and rolling statistics: sales 1, 7 and 14 days ago; rolling means and spreads over 7 and 28 days (with stock-out days corrected);
  • calendar: day of week, month, holidays and festivals (with days before and after), paydays, school terms;
  • promotions and price: planned discounts, price relative to normal, placement on the home screen, competitor events if known;
  • weather: forecast temperature and rain (ice cream, umbrellas);
  • product and store: category, brand, shelf life, store size, area type;
  • hierarchy: sales of the category and of the store overall.

Why it matters

Promotions and festivals cause the biggest swings and are known in advance, so they must be features.

  • Lags capture each series' level and recent trend.
  • Hierarchy features let thin series borrow strength from their category and store.

In the real world: Kirana Kart's promotion calendar is fed to the forecast two weeks ahead; forecasts for promoted items made without it were the largest single source of stock-outs.

Using lag-1 sales for a forecast seven days ahead. For day 7, yesterday's sales relative to that day are not known yet; each horizon must use only lags available at forecast time.

Practise it: Design a Demand Forecasting Platform, Design a Predictive Maintenance System, Design a Real-Time Fraud Detection System, Design an ML Feature Store

Choosing the model

What it is

Three broad approaches:

  • classical, per series: exponential smoothing, ARIMA, Prophet. Simple and explainable; struggles with millions of series, promotions and sparse data;
  • one global model: a gradient-boosted model trained on all series together, with series features. The common choice at scale;
  • deep models: global neural forecasters (DeepAR, temporal fusion transformers, newer foundation models for time series). Strong with lots of data; more costly to run.

Why it matters

A global model learns patterns shared across series.

  • A new product or a slow seller benefits from what the model learned from similar ones.
  • One model is far easier to train, monitor and release than twenty million.
  • The M5 forecasting competition (Walmart data) was won largely by gradient-boosted global models.

In the real world: Kirana Kart uses one LightGBM model per broad category, trained on all stores and products in it, with a quantile objective for each percentile.

Visual example

Models

At millions of series, a global model is the usual default.

Forecasting approaches compared
approachscalepromotions and eventsnew and sparse serieseffort
Classical per seriesPoor at millionsHardWeakLow per series; huge in total
Global boosted treesGoodAs featuresBorrows from similar seriesModerate
Global deep modelGood with GPUsAs featuresGoodHigh

Fitting a separate ARIMA to every store-product pair. Most series are too short and sparse, the run is enormous, and nothing is shared between related products.

Slow sellers, new products and hierarchy

What it is

Special cases:

  • intermittent demand: many products sell zero on most days at a store; forecast the chance of any sale and the size when it happens, or forecast at a coarser level (weekly);
  • new products and stores: no history, so borrow from similar products (same category, brand, price band) and similar stores (cold start via hierarchy);
  • reconciliation: store-level forecasts should add up to city and national forecasts used for supplier orders; reconcile them so the levels agree.

Why it matters

Most products in a large catalogue are slow sellers, and errors there add up.

  • Percentage measures break on them (module 16), so WAPE and pinball loss are used.
  • Reconciliation keeps warehouse and store plans consistent.

In the real world: Kirana Kart forecasts its slowest 30% of products weekly per store, then splits the weekly figure into days by the store's usual weekday pattern.

Measuring accuracy only on the best sellers. The long tail is where most waste and most empty shelves accumulate.

Practise it: Design a Demand Forecasting Platform

From forecast to order

What it is

The order quantity comes from the forecast range and the costs:

  • cost of being one unit short: the lost margin (and some lost goodwill);
  • cost of being one unit over: waste for perishables, holding cost for long-life goods;
  • the best percentile to stock is short ÷ (short + over): the newsvendor rule;
  • order = that percentile of demand over the period until the next delivery, minus stock on hand.

Why it matters

It turns a forecast into a decision with arithmetic, per product.

  • Perishables with high waste cost are stocked below the median; long-life goods well above.
  • When costs change (a supplier price rise), the decision changes with no retraining.

In the real world: Kirana Kart's replenishment system computes each product's percentile nightly from its margin and shelf life, and applies minimum display quantities set by category managers.

Visual example

Computed

The percentile of demand to stock = cost short ÷ (cost short + cost over).

Illustrative costs per unit, in rupees
productcost of one shortcost of one overstock to percentile
Fresh bread (1-day life)₹10₹3025%
Bananas (3-day life)₹8₹1240%
Basmati rice (long life)₹15₹194%

Bread is stocked below the median; rice far above it.

Ordering the median forecast for everything. Fresh bread is then over-ordered and wasted; rice runs out.

The nightly pipeline at scale

What it is

A batch pipeline with a hard deadline:

  • load the day's sales, stock and sell-out times; correct censored days;
  • build features for every series and horizon in Spark or the warehouse;
  • score all series with the global models (parallel across categories);
  • reconcile levels; validate the output (no negative forecasts; no series jumping 10× without a promotion);
  • write to the replenishment system; flag exceptions for category managers.

Why it matters

With tens of millions of rows a night, the design is about throughput and reliability.

  • Partitioning by category or region parallelises scoring.
  • Output validation stops a broken input from emptying or flooding every store.
  • If the job fails, yesterday's forecasts (shifted by a day) are the fallback.

In the real world: Kirana Kart's forecast job runs on Spark from midnight, scores about twenty million series in under two hours, and pauses orders for any category whose total forecast moves more than 50% without a known event.

Visual example

Pipeline

Validation before anything reaches suppliers.

The nightly forecasting run

  1. LoadSales, stock, sell-out times, promotions
  2. CorrectEstimate demand on sold-out days
  3. FeaturesLags, calendar, promotions, hierarchy
  4. Score~20 M seriesGlobal quantile models by category
  5. ValidateLevels agree; no wild jumps
  6. Orderby 4 a.m.Newsvendor quantity minus stock

No output checks. A bad promotion file once multiplied forecasts for a whole category; without checks, the orders go straight to suppliers.

Evaluation and monitoring

What it is

Forecasts are judged over many periods:

  • offline: rolling-origin backtests over at least six months (module 16), reported for normal weeks, promotion weeks and festival weeks separately;
  • by segment: category, store type, fast and slow sellers, fresh and long-life;
  • online: a store-level pilot or switchback (some stores on the new model) measuring waste and stock-outs;
  • monitoring: bias by category (steady over- or under-forecasting), WAPE weekly, stock-out and waste rates, and checks after every festival.

Why it matters

Bias is the first thing to watch: a small, steady over-forecast quietly fills stores with waste.

  • Festival weeks are rare, so the backtest must cover past festivals explicitly.
  • Store-level pilots measure the business effect, since the forecast's real test is what ends up on shelves.

In the real world: Kirana Kart pilots new forecasting models in 40 matched stores for four weeks, comparing waste and stock-outs with 40 similar stores on the old model.

Backtesting only on recent normal weeks. The model then fails in the first festival, when errors are most expensive.

Practise it: Design a Large-Scale Classification Platform, Design a Predictive Maintenance System, Design a Real-Time Anomaly Detection System, Design a Recommendation System, Design Feature Monitoring, Design Model Monitoring, Diagnose Training-Serving Skew, Improve a Low-Recall Model, Design a Search Ranking System

Interview questions: the forecasting design

What it is

The questions interviewers ask about the forecasting design, from the first screening call to the senior round. Cover the answer, say yours aloud, then compare.

Why it matters

Reading an idea and explaining it are different skills.

  • Each answer below is the two or three sentences an interviewer is listening for.
  • The reasoning behind each one is in the cards above. If an answer surprises you, go back to that card.

In the real world: Forecasting interviews reward candidates who mention censored demand and the newsvendor decision; both show they have seen the real problem.

Q: Why forecast demand rather than sales?

Sales are capped by stock; on sold-out days true demand is higher. Training on sales under-forecasts popular items and starts a loop of smaller orders and more stock-outs.

Q: One model per series or a global model?

A global model across series learns shared patterns, handles sparse and new series by borrowing strength, and is far easier to run at millions of series.

Q: How do you turn a forecast into an order?

Forecast a range, then stock at the newsvendor percentile, cost short over cost short plus cost over, minus stock on hand.

Q: How do you handle promotions and festivals?

As known future features (planned discounts, calendars with days before and after), and evaluate on past promotion and festival weeks explicitly.

Q: Which metrics would you use?

WAPE and bias by segment, pinball loss for percentiles, and business metrics: waste, stock-outs and lost sales.

Q: What if the nightly job fails?

Fall back to yesterday's forecasts shifted a day, and validate outputs so a bad input cannot flood or empty stores.

Proposing an LSTM before discussing what is forecast and how it becomes an order.

Practise it: Design a Demand Forecasting Platform

Exercise: forecast and order

What it is

A short build that uses this module's ideas. Write it yourself before looking anything up; the checks at the end tell you whether it works.

Why it matters

An idea you have only read fades in a week.

  • Building it once, even in fifty lines, is what makes it yours.
  • Interviewers can tell the difference between someone who has read about a loop and someone who has debugged one.

In the real world: Retail and supply-chain data science interviews often include a version of this exercise.

Your task. Build a global quantile forecasting model on public retail data and turn it into stocking decisions.

Steps

  1. Use the M5 (Walmart) data or another store × product × day dataset.
  2. Build lag, rolling, calendar and price features using only information available at each forecast date and horizon.
  3. Train LightGBM quantile models at 0.1, 0.5 and 0.9 across all series.
  4. Run a rolling-origin backtest over at least four cut-offs; report WAPE and bias overall, for fast and slow sellers, and for holiday weeks.
  5. Assign each product a cost short and cost over, compute its newsvendor percentile, and simulate ordering: count waste and stock-outs against ordering the median.

You are done when

  • Your global model beats a 'same as last week' baseline on WAPE.
  • Newsvendor ordering has lower total cost than median ordering in your simulation.
  • You can show where the model is weakest (a segment or a holiday).

Stretch. Simulate stock-outs by capping sales at a stock level, train on capped sales, and show how much the forecast drops; then correct it.