← Blog

From Demand Forecasts to Inventory Decisions: A Retail AI Architecture

Summary

An engineering guide to retail forecasting and inventory decisions: reliable data, model selection, distributed execution, calibrated uncertainty and measurable ROI.

RB
Roozbeh Bandpey

Co-founder and CEO of Bandpey GmbH

Outcome
A reference architecture and evaluation framework for turning product-location forecasts into scalable, reproducible inventory decisions, with transparent performance and ROI calculations.
From Demand Forecasts to Inventory Decisions: A Retail AI Architecture

A forecast becomes useful when it changes an inventory decision before the order deadline. The engineering problem is therefore larger than predicting the next sales value. We need a reproducible view of demand, a model that behaves well at the replenishment horizon, a policy that converts uncertainty into a feasible order, and a delivery path that can be operated every day.

In our retail work, forecasting sat alongside client development, commerce and other data products. The portfolio perspective is covered in The Highest-ROI AI Use Cases in Luxury Retail. Here we follow one decision path in depth: source data to product-location forecasts, forecasts to inventory policies, and policies to measurable operating value.

The implementation reference is our public Fine-Grained Demand Forecasting at Scale repository. Its notebooks demonstrate distributed Prophet training, comparisons with aggregate-and-allocate forecasts, and a daily forecasting simulation using Delta Lake and MLflow. The inventory-policy design and production controls described below extend that reference; they are not all packaged in the repository. Historical notebook timings, programme observations and illustrative calculations are identified separately.

Define the replenishment decision before choosing the model

Begin with the decision's grain and deadline. A store replenishment process may need product-location-day forecasts, while an upstream purchasing process may require product-market-week forecasts. They do not necessarily share the same target: consumer sell-out, shipments to a distributor and orders placed upstream represent different events.

The prediction horizon must cover the period in which the business cannot immediately correct a stock position. For continuous review, lead time is central. For a periodic review policy, the protection period also includes the time until the next review. An accurate next-day forecast is not a sufficient input to a weekly order with a two-week delivery lead time.

The interface between forecasting and planning should make those semantics explicit:

ContractWhat it specifiesFailure it prevents
Series identityProduct, location, channel, unit of measure and active assortmentJoining incompatible units or inventing inactive product-location combinations
TimeForecast issue time, target period, timezone and data-availability cutoffTraining on information that was unavailable when the order was placed
PredictionPoint estimate, calibrated uncertainty, model version and fallback statusTreating an estimate as a guaranteed quantity
Inventory stateUsable on-hand stock, confirmed receipts, backorders and reservationsOrdering stock that is already on the way or unavailable to sell
PolicyLead time, service target, review frequency, case packs and capacity limitsProducing a mathematically attractive but infeasible recommendation

A timestamp is part of the contract, not just metadata. A recommendation delivered after the purchasing cutoff has missed its purpose even if its forecast error is low.

Separate the data, prediction and decision layers

The architecture below shares a data foundation between forecasting and inventory decisions. That reuse matters: the inventory policy should consume the same product keys, sales history and availability definitions used to evaluate the forecast.

Retail inventory architecture: sell-in, sell-out, inventory and market data feed a shared feature dataset, demand-forecasting models and inventory-policy components, with outputs delivered to operational systems.Retail inventory architecture: sell-in, sell-out, inventory and market data feed a shared feature dataset, demand-forecasting models and inventory-policy components, with outputs delivered to operational systems.

Read the diagram as a functional decomposition, not as a claim that each icon represents a neural network. The time-series and ensemble components estimate demand. Economic order quantity (EOQ) and reorder point (ROP) are inventory-policy concepts. A random forest can estimate an input such as demand or lead time; by itself it does not enforce a replenishment policy or optimise a constrained allocation.

The critical interface is the forecast distribution over the protection period, together with current inventory and policy constraints. Those inputs must reach the inventory decision layer even where the high-level diagram leaves the interface implicit.

Preserve source meaning through the data foundation

Sell-in and sell-out should be aligned, not summed. The former can contain channel replenishment and order batching; the latter is closer to consumer purchases but may be incomplete. Inventory snapshots help establish whether observed sales were constrained by availability. Returns, cancellations and transfers need their own definitions before they enter a demand target.

Retain the source event time, ingestion time and the time a correction became available. A historical snapshot should answer both “what happened?” and “what did we know at the forecast cutoff?” A late correction must not silently improve a backtest that is meant to reproduce an earlier decision.

At the curated layer, enforce uniqueness at the chosen grain, standardise units, retain assortment start and end dates, and distinguish missing records from genuine zero demand. A closed store is not necessarily a zero-demand training example. Neither is an out-of-stock day. If demand is censored by availability, flag it and evaluate any imputation method separately.

Build features that can exist at prediction time

Lagged sales, trailing averages, weekday patterns and seasonal indicators are useful only if their values are available at the issue time. Shift the target before calculating rolling features. A promotion scheduled for next month can be a known future input; next month's realised sales, actual weather or corrected stock snapshot cannot.

Use the same availability rules in training and scoring. For future covariates that are themselves forecasts, retain the version available at the cutoff. Otherwise the model is evaluated with better inputs than it will receive in production. The scikit-learn lagged-feature example illustrates why time-aware evaluation is necessary when converting forecasting into tabular regression.

Select models by demand regime and evidence

Our public reference uses one Prophet model per store-item series. That is a concrete implementation choice, not a requirement that every product receive its own model. Local models can capture distinct seasonal behaviour; pooled models can share evidence across products with shorter histories. Both should compete against inexpensive baselines.

Demand regimeCandidate methodsEngineering consideration
Stable, recurring demandSeasonal naïve, exponential smoothing, ARIMAStart with a reproducible baseline before paying for more complex fitting
Clear seasonality and calendar effectsProphet or a suitable statistical model with regressorsValidate history length, changepoints and future regressor availability
Many related products with useful attributesPooled gradient-boosted trees, quantile regression or other global modelsPrevent leakage across time and test performance on sparse or newly introduced items
Intermittent demandIntermittent-demand baselines and count or occurrence-size modelsZero-heavy demand requires suitable loss functions and a defensible uncertainty model
New or retiring productsAnalogue-based or pooled estimates with lifecycle rulesExpose low-confidence cases rather than forcing a poorly identified local model

Croston's method separates non-zero demand sizes from the intervals between them. It is a useful intermittent-demand reference, but not a complete probabilistic model with ready-made prediction intervals; Hyndman and Athanasopoulos explain its limitations. An inventory policy needs more than a plausible average for a slow-moving item.

The repository's comparison notebook contrasts store-item forecasts with item-level forecasts allocated using historical store shares. This is an important comparison because aggregate performance can conceal local misses. It does not establish that fine-grained modelling always wins. Re-estimate allocation shares inside each training window and compare alternatives at the decision grain.

When planners need mutually consistent store, region and category totals, add a reconciliation step. Forecast reconciliation makes the aggregation constraints explicit. Point forecasts and uncertainty require separate care: the sum of individual quantiles is generally not the quantile of total demand.

Evaluate at the horizon and cutoff used by the business

A random train-test split is a poor approximation of a replenishment process. Use rolling forecast origins: fit with information available at one cutoff, forecast the required horizon, advance the cutoff and repeat. Keep a final period outside model selection. The rolling-origin procedure supports multi-step evaluation rather than only next-day error.

Build each fold from an as-of snapshot. Refit transformations, estimate allocation ratios and select models without the evaluation period. Include enough cutoffs to expose the seasonal peaks, promotions and lifecycle transitions relevant to the decision. Compare every candidate on the same cutoffs and retain the result by horizon and segment.

Use a small set of measures with explicit denominators:

  • MAE or RMSE for error in demand units, with bias reported separately.
  • MASE or RMSSE where scaled comparisons are useful; flag series whose training-scale denominator is zero.
  • Portfolio WAPE for a weighted operational summary, with zero-total-demand groups handled explicitly and low-volume segments reported separately.
  • Pinball loss and empirical coverage for quantiles and intervals, alongside interval width.
  • Inventory-policy outcomes from a replay of replenishment decisions: fill rate, stockout cycles, average inventory, write-offs and order feasibility.

MAPE is problematic when actual demand is zero or near zero, a common condition in fine-grained retail data. The distinction between forecast errors, scaled errors and percentage errors is set out in Forecasting: Principles and Practice. Do not collapse these measures into a generic “accuracy” percentage.

The repository makes another useful distinction visible. In its operational simulation, the field called accuracy measures the share of observations inside the prediction interval. It is interval coverage, not a point-forecast accuracy score. The notebook reports roughly 88% coverage for a nominal 95% interval; that is a calibration gap to investigate, not evidence of a 95% service level. Those are historical example outputs, not results from the retail programme.

Prophet's own documentation warns that interval coverage depends on assumptions about future trend changes. For inventory decisions, test the error distribution over the actual protection period. Adding daily interval bounds or treating a model's upper bound as an order quantity does not establish the probability of meeting cumulative demand.

Scale the independent work without centralising the data

The public notebooks show the transition from a driver-side loop to Spark's groupBy(...).applyInPandas(...). Each group contains the history for one store-item pair. The fitting function returns a forecast with the same keys; Spark combines the results into a distributed table.

The computational pattern is straightforward: parallelise independent series, while preserving temporal order within each series. The driver should coordinate work, not collect the full panel of historical observations. For pooled models, the unit of parallelism changes, but the requirement to avoid collecting the complete training set onto the driver remains.

The training notebook includes the following sample timings. We reproduce them as published examples rather than claiming to have rerun the benchmark.

Repository example: runtime versus worker cores

Historical sample timings for the notebook's 500 store-item series; not a production SLA

Source: Bandpey Labs, src/02-training.py, revision 67a7f95 (2 April 2024). Values are the repository's published sample timings, not a new benchmark. The table does not specify a complete hardware/runtime configuration or run-to-run variability; do not extrapolate it to a client workload.

The reported change from 8 to 32 worker cores reduces runtime from 5.41 to 1.36 minutes, about a 3.98× speed-up for 4× the cores. But multiplying worker cores by elapsed minutes gives 43.28 and 43.52 core-minutes respectively. In this example, the larger configuration mainly buys a shorter completion window; it does not demonstrate a reduction in worker compute consumption.

Core-minutes are only a rough utilisation proxy, not a bill. Driver cost, cloud instance type, platform charges, cluster startup, idle time and billing granularity are absent. The repository table also lacks enough environment and repetition details to serve as a reproducible modern benchmark. Use it to understand the scaling pattern, then measure the workload you intend to operate.

Bound memory, skew and concurrency

Spark documents that the DataFrame form of applyInPandas requires a shuffle and loads each group into memory. A cluster can have spare aggregate memory while a single large group exhausts a worker. Inspect series lengths and row widths; isolate unusually large groups and bound the history where the modelling design permits it.

Partition for the work, not for a slogan such as “one partition per series”. Too few partitions underuse the cluster; too many tiny tasks add scheduling and serialisation overhead. Benchmark a representative mix of long, short, sparse and high-volume series. If each task launches a multithreaded numerical library, cap its threads to avoid oversubscribing the worker.

Limit concurrent model candidates and backtest folds. With 100,000 active series, three candidates and six cutoffs, a full local-model comparison implies 1.8 million fits before the final production fit. That is a workload count, not a runtime prediction. Screening, segmentation and selective retraining can reduce the work without changing the evaluation standard.

Size forecast output as well as model fitting

For 100,000 active series, a 28-day horizon produces 2.8 million series-date rows per issue date. If three quantiles are stored in long form, that becomes 8.4 million rows; if they are separate columns, it remains 2.8 million wider rows. Thirty retained issue dates produce 252 million long-form rows. These figures are arithmetic capacity examples, not claims about a client deployment.

Choose the representation deliberately. Forecast history is needed for evaluation, but it should not be scanned in full for every planning request. Retain issue date and target date separately, compact output appropriately and publish a small current-release view for consumers. Avoid partitioning storage by every product-location key.

Measure the entire operational window: source readiness, feature construction, shuffle, fitting, scoring, policy calculation, validation and publication. A faster model fit is irrelevant if ingestion arrives late or the planning-system export is the bottleneck.

Turn calibrated forecasts into feasible inventory decisions

Keep the replenishment policy separate from model selection. A model estimates demand; a policy decides what inventory exposure the business will accept. This separation makes it possible to change a service target, order constraint or supplier lead time without pretending the demand model has changed.

For a simple continuous-review policy, the reorder point is expected demand during lead time plus a safety buffer. A periodic-review order-up-to policy must cover the review interval plus lead time. In either case, subtract the relevant inventory position—not just shelf stock—when deriving an order. Include confirmed inbound supply and commitments consistently, without subtracting reservations twice.

EOQ addresses an ordering-versus-holding-cost trade-off under restrictive assumptions. It does not, on its own, handle uncertain demand, shelf-life limits or a network-wide capacity constraint. Similarly, a random-forest prediction is not an optimiser. When suppliers impose minimum orders and case packs, or several locations compete for limited stock, the decision layer needs explicit rules or a constrained optimisation model.

A small calculation makes the service trade-off tangible. Assume a fixed 14-day lead time and unbiased, independent normal daily forecast errors with a standard deviation of 30 units. Lead-time error standard deviation is then 30 × √14, approximately 112.25 units. Multiplying it by the standard-normal service quantile gives the safety buffer, rounded upward to whole units.

Higher service targets require larger inventory buffers

Calculated example: fixed 14-day lead time; daily forecast-error standard deviation of 30 units

Illustrative calculation, not project results: safety stock = ceil(z × 30 × sqrt(14)). Assumes unbiased, independent normal daily forecast errors, fixed lead time and continuous review. z is the standard-normal quantile at each service target. Cycle service level is not fill rate; use a calibrated lead-time error distribution when these assumptions fail.

Under these assumptions, moving from a 95% to a 99% cycle service target raises the buffer from 185 to 262 units. It does not mean that 99% of demand units will be served. Cycle service level concerns the probability of avoiding a stockout during a cycle; fill rate concerns the fraction of demand fulfilled.

This is a teaching example, not a universal replenishment formula. Correlated errors, bias, intermittent demand and variable lead times invalidate its simple scaling. OpenForecast's safety-stock explanation makes both the assumptions and the service-level distinction explicit. In production, estimate or simulate the distribution of demand over the protection period and evaluate the resulting policy.

Test policies through historical replay before allowing them to place orders. Advance through demand and receipts, apply the real ordering calendar, enforce constraints and carry inventory forward. Compare against the incumbent policy with the same information and cost definitions. Where historical sales were limited by stockouts, lost demand is unobserved; report sensitivity to that assumption rather than presenting replayed lost sales as ground truth.

Make each forecast release reproducible and safe to consume

The MLOps notebook records a training date, Prophet version and Delta table version in MLflow, and retains forecasts by training date. That is a useful foundation for traceability. A production release needs an explicit manifest around those ideas.

Record the code revision, dependency environment, source snapshot identifiers, feature version, model or model-bundle identifier, issue time, horizon and inventory-policy version. Register shared models individually where useful; for a very large collection of local models, use a versioned bundle and an indexed manifest rather than assuming every series needs a separate online endpoint.

Persist forecast output under a stable release key and write to staging first. Check active-series coverage, duplicate keys, finite predictions, ordered quantiles and policy feasibility before publishing a release pointer. Retried jobs must not create duplicate forecast rows or duplicate purchase orders. Reproducibility requires retaining the referenced data and model artefacts, not merely logging identifiers that later expire.

Use an explicit fallback policy for insufficient history, failed fits and stale inputs. A seasonal baseline or previously approved forecast may be acceptable within a defined expiry window; a stale recommendation must not silently appear current. Failures should be visible per series, with the reason attached to the output.

Planning-system integration is a separate reliability boundary. Give each recommendation an idempotency key, record whether it was accepted or overridden, and require approval for material stock or spending changes. Preserve the proposed quantity and the final action so that model error, planner overrides and policy constraints can be evaluated separately.

The public notebooks are an accelerator, not a ready-to-run production deployment. They contain environment-specific paths, example partition counts and reset cells. Run them in an isolated environment, adapt storage and access controls, pin dependencies and review reset operations before execution.

Connect engineering metrics to a defensible ROI model

Forecast error is an intermediate measure. The commercial test is whether the deployed decision process improves service, inventory exposure or avoidable cost after paying for the system.

In the anonymised programme discussed in the companion article, reported forecast accuracy moved from 46% in 2022 to 57% in year-to-date 2024, while the stock write-off rate moved from 17% to 11%. Those are programme observations, not a controlled attribution study. The source's accuracy measure should not be equated with the repository's interval-coverage field, and a YTD endpoint is not a like-for-like full-year comparison. Neither figure establishes a monetary return by itself.

For a financial case, separate three quantities:

  • Recurring operating benefit: avoidable inventory costs, incremental contribution margin and non-overlapping write-off savings.
  • Recurring solution cost: compute, storage, software, monitoring, support and the operational work required to use the recommendations.
  • One-time cash effects: implementation spend and working capital released from inventory. Cash release is not recurring profit.

Use contribution margin rather than gross sales for availability gains. Do not count a reduced write-off once as a carrying-cost saving and again as a separate benefit. Storage contracts or warehouse labour may remain fixed even when stock falls; include only savings that can actually be avoided.

A transparent sensitivity model

The following scenario is illustrative. It does not represent a client result, a quotation or an industry benchmark. It asks how the business case changes when average inventory at cost falls by 5%, 10% or 15%, with service maintained.

AssumptionValueBoundary
Starting average inventory at cost€5,000,000Same operational scope in every scenario
Avoidable annual carrying-cost rate12% of inventory releasedScenario assumption; excludes capital charges and the write-offs counted below; validate cost variability
Incremental annual contribution from availability€80,000Net of variable fulfilment costs; held constant for sensitivity analysis
Separate annual write-off savings€30,000No overlap with carrying-cost savings
Annual solution operating cost€90,000Includes the operating team and platform, not only model inference
Initial implementation€180,000One-time cost

Annual gross benefit equals inventory released × 12%, plus €80,000 contribution and €30,000 write-off savings. Three-year cost is €180,000 + 3 × €90,000 = €450,000. Simple three-year ROI is (three-year gross benefit − three-year cost) ÷ three-year cost.

ROI depends on realised operating benefits

Illustrative three-year simple ROI; inventory reductions of 5%, 10% and 15%

Scenario analysis, not a client result or industry benchmark. Starting inventory €5m; avoidable carrying-cost rate 12%; additional annual contribution €80k; separate write-off savings €30k; annual solution cost €90k; implementation €180k. ROI = (3 × annual gross benefit − €450k) / €450k. No discounting, tax or ramp-up. One-time working-capital release is excluded from recurring benefits.

In the middle scenario, a 10% reduction releases €500,000 of working capital. Recurring carrying-cost savings are €60,000; adding the two other benefit lines gives €170,000 a year. After €90,000 operating cost, net recurring benefit is €80,000. The three-year surplus after implementation is €60,000, giving a simple ROI of 13.3%. Undiscounted payback from recurring benefits alone is 2.25 years after full benefits begin; inventory cash release is deliberately excluded from that calculation.

The 5% scenario produces a −6.7% three-year ROI despite a positive annual operating contribution. The 15% scenario produces 33.3%. These are sensitivities to one assumption, not confidence bounds. Holding service contribution constant while reducing inventory is itself a proposition the pilot must test.

The model assumes immediate full benefit, constant annual costs and no discounting or tax. A delivery investment case should add the ramp-up schedule, delayed adoption, demand variation and discounted cash flows. A matched rollout or controlled pilot should establish incremental contribution and policy effects before the model is used to justify expansion.

Release against an operational acceptance test

A sensible first release covers a bounded assortment and planning process, with the incumbent policy retained as a comparison. Agree the data cutoff, forecast horizon, completion deadline and acceptable fallback behaviour before tuning the model.

Require evidence at three levels: out-of-time forecast performance, inventory-policy performance and end-to-end delivery reliability. Then run the recommendation in shadow mode, compare it with the actual order, and expand only after planners can explain and operate the differences. Track recommendation acceptance and override reasons alongside the resulting service and stock outcomes.

The architecture is successful when it can reproduce yesterday's decision, complete tomorrow's run within its operating window and show why the business should trust the recommendation. The model is one component of that system. The shared data foundation, uncertainty calibration, inventory policy and operational controls determine whether forecasting becomes a repeatable source of value.

Implementation and evidence

Start with the Bandpey demand-forecasting repository. For the code and reported example numbers reviewed here, the pinned reference is revision 67a7f95, dated 2 April 2024. Read the preparation, training, comparison and MLOps notebooks as a sequence. The repository implements the forecasting reference; the additional model families, inventory optimisation and production safeguards above are engineering options and extensions, not claims that they are already implemented there.

The scaling chart reproduces the notebook's sample timing table. The service-buffer chart is calculated from explicitly stated distributional assumptions. The ROI chart is a sensitivity calculation from the displayed scenario inputs. Programme metrics retain the limitations of their original reporting. All chart values are embedded in their JSON blocks; none depends on a separate Notion database.

The methodological references are linked at the relevant points in the article: rolling-origin evaluation and forecast reconciliation from Hyndman and Athanasopoulos, lagged-feature evaluation from scikit-learn, grouped execution behaviour from Apache Spark, uncertainty assumptions from Prophet, and inventory-buffer interpretation from OpenForecast. These sources support the methods; they do not validate the illustrative ROI inputs or establish a client outcome.

About the author

Roozbeh Bandpey

Co-founder and CEO of Bandpey GmbH

Roozbeh Bandpey is an engineer and entrepreneur in Munich with more than 20 years of hands-on software engineering. He is the co-founder and CEO of Bandpey GmbH, which builds Facthory, Emolysis, Copolly and Inteliwert, and a Databricks Solutions Architect Champion.

Related insights and work