Supply chains rely on a small set of well-known algorithms: forecasting methods predict demand, inventory formulas such as economic order quantity and safety stock decide how much to order and when, and routing and assignment algorithms decide which truck goes where and which item gets picked next. Most of them come from operations research, and several fit in a few lines of code.
This post walks through the main problems, shows working Python for three of them (inventory ordering, forecasting and delivery routes), and says where the simple versions stop being good enough. The numbers in the examples are made up for illustration, not data from a real company.
1. Demand forecasting
Everything downstream depends on a guess about future demand. Common methods, from simple to complex:
- Moving average: the mean of the last k periods. Easy, but slow to react to a trend.
- Exponential smoothing: a weighted average where recent periods count more. The new forecast is
alpha * latest_demand + (1 - alpha) * old_forecast. Larger alpha reacts faster and is noisier. - Seasonal and trend models (Holt-Winters, ARIMA): handle weekly or yearly patterns.
- Machine learning models (gradient-boosted trees, neural networks): can use extra signals such as promotions, price and weather, when you have enough history.
def ses(series, alpha):
"""Simple exponential smoothing; returns the forecast for the next period."""
f = series[0]
for x in series[1:]:
f = alpha * x + (1 - alpha) * f
return f
demand = [120, 132, 101, 134, 90, 150, 140, 160]
print(round(ses(demand, 0.3), 1)) # smoothed forecast
print(round(sum(demand[-3:]) / 3, 1)) # 3-period moving average
138.0
150.0
The two methods disagree (138 versus 150) because the series is noisy and trending up; the moving average only sees the last three points, while smoothing with alpha 0.3 remembers the whole history. Which one is better is an empirical question: hold out the last few periods, forecast them with each method, and compare the errors. In practice, teams measure forecast error (for example mean absolute percentage error) and pick the method that wins on their data, product by product.
2. Inventory: how much to order, and when
Two questions, two classic formulas.
How much per order: economic order quantity (EOQ). Ordering often costs a fixed fee per order; holding stock costs money per unit per year. EOQ balances them and was published by Ford W. Harris in 1913. With annual demand D, fixed cost per order S and annual holding cost per unit H:
EOQ = sqrt(2 * D * S / H)
When to reorder: reorder point. Reorder when stock falls to the demand you expect during the supplier’s lead time, plus a buffer called safety stock. If daily demand is roughly normal with mean mu and standard deviation sigma, and the lead time is L days, the textbook formula is mu * L + z * sigma * sqrt(L), where z comes from the service level you want (z is about 1.645 for 95% of cycles without a stockout).
import math
from statistics import NormalDist
def eoq(D, S, H):
return math.sqrt(2 * D * S / H)
def total_cost(Q, D, S, H):
return D / Q * S + Q / 2 * H # ordering cost + holding cost
D, S, H = 12000, 50, 2.4
q = eoq(D, S, H)
print(round(q, 1))
for Q in (500, round(q), 1500):
print(Q, round(total_cost(Q, D, S, H), 2))
def reorder_point(daily_mean, daily_sd, lead_days, service):
z = NormalDist().inv_cdf(service)
safety = z * daily_sd * math.sqrt(lead_days)
return daily_mean * lead_days + safety, safety
rp, ss = reorder_point(40, 12, 9, 0.95)
print(round(rp, 1), round(ss, 1))
707.1
500 1800.0
707 1697.06
1500 2200.0
419.2 59.2
Ordering 707 units per order costs 1,697 a year in this example, while 500 or 1,500 cost more. With demand of 40 units a day (standard deviation 12), a 9-day lead time and a 95% service level, you reorder at about 419 units, of which about 59 are safety stock.
Know the assumptions: EOQ assumes steady demand, a constant cost per order and no quantity discounts; the safety stock formula assumes normally distributed demand and a fixed lead time. Real systems relax these with simulation, probabilistic models or reinforcement learning, but these two formulas are still the baseline other methods are compared against.
3. Routing deliveries
The vehicle routing problem (VRP) asks: given a depot, customers with known demands and trucks with limited capacity, what set of routes minimizes total distance? It generalizes the traveling salesman problem, so it is NP-hard: no known algorithm solves every large instance exactly in reasonable time. Practical systems use heuristics and metaheuristics that find good routes quickly.
One classic heuristic is the Clarke-Wright savings algorithm (1964). Start with each customer on its own round trip from the depot. Merging customers i and j into one route saves d(0,i) + d(0,j) - d(i,j), because you drive one shared stretch instead of two return trips. Sort all pairs by savings, and merge routes in that order when (a) i and j are in different routes, (b) both are at the ends of their routes, and (c) the combined load fits the truck.
import math, itertools
coords = {0: (0, 0), 1: (4, 3), 2: (6, 1), 3: (-3, 5), 4: (-5, 2), 5: (2, -6), 6: (5, -4)}
demand_c = {1: 4, 2: 3, 3: 5, 4: 4, 5: 6, 6: 3}
CAP = 10
def d(a, b):
(x1, y1), (x2, y2) = coords[a], coords[b]
return math.hypot(x1 - x2, y1 - y2)
savings = sorted(((d(0, i) + d(0, j) - d(i, j), i, j)
for i, j in itertools.combinations(demand_c, 2)), reverse=True)
routes = {i: [i] for i in demand_c} # customer -> its route
load = {id(r): demand_c[i] for i, r in routes.items()}
for s, i, j in savings:
if s <= 0:
break
ri, rj = routes[i], routes[j]
if ri is rj or load[id(ri)] + load[id(rj)] > CAP:
continue
if ri[-1] == i and rj[0] == j: new = ri + rj
elif ri[0] == i and rj[-1] == j: new = rj + ri
elif ri[0] == i and rj[0] == j: new = ri[::-1] + rj
elif ri[-1] == i and rj[-1] == j: new = ri + rj[::-1]
else:
continue
ld = load[id(ri)] + load[id(rj)]
for c in new:
routes[c] = new
load[id(new)] = ld
def length(r):
p = [0] + r + [0]
return sum(d(p[k], p[k + 1]) for k in range(len(p) - 1))
final = {id(r): r for r in routes.values()}.values()
for r in final:
print(r, sum(demand_c[c] for c in r), round(length(r), 2))
print(round(sum(length(r) for r in final), 2),
round(sum(2 * d(0, c) for c in demand_c), 2))
[1, 2] 7 13.91
[3, 4] 9 14.82
[5, 6] 9 16.33
45.07 70.05
Three trucks, each under the capacity of 10, drive 45.07 units in total, against 70.05 for one dedicated trip per customer. The result is not guaranteed optimal, since savings is a heuristic. That is why it is often used to produce a starting solution that local search then improves (for example 2-opt swaps within a route, or moving a customer between routes).
Real routing adds time windows, driver hours, multiple depots, traffic and pickups with deliveries. For that, teams typically use a solver rather than writing their own: Google’s open-source OR-Tools has a routing library for exactly these problems.
Inside each route, the distance d(a, b) would come from a shortest-path algorithm on the road network, typically Dijkstra or A* variants. If you have not implemented Dijkstra yet, the Dijkstra’s Algorithm lesson is a good place.
4. Warehouse operations
- Slotting: decide where each product lives. Fast-moving items go near the dock or at waist height; items often ordered together go close to each other. A common first step is ABC classification: sort products by how much they move and give the top group the best locations.
- Pick-path routing: a picker must visit locations for an order and come back. This is a small traveling salesman problem on a warehouse layout. Simple rules such as an S-shape route (walk each aisle with items from end to end) work well and are easy to explain; optimal routing is better but harder to use on the floor.
- Batching and wave planning: group orders so one trip serves several of them.
- Bin packing: fit cartons into containers or pallets. Heuristics such as first-fit decreasing give near-optimal results quickly.
5. Supplier choice and network design
Supplier selection is a multi-criteria decision (price, quality, lead time, risk). Methods like the Analytic Hierarchy Process turn pairwise comparisons into weights, and a weighted score ranks suppliers. Bigger strategic questions, such as where to open warehouses and which plant serves which region, are modeled as linear or mixed-integer programs and solved with solvers.
What goes wrong in practice
- Bad data. Missing records, unit mismatches and stockouts that hide true demand (you cannot sell what you do not have) mislead every model.
- Models that ignore constraints people care about. A route that is mathematically shortest but unloads a pallet in the wrong order, or breaks a driver’s break rules, will be overridden by the drivers.
- Treating a forecast as certain. Plans should carry safety stock or scenarios, not a single number.
- Not measuring. Compare an algorithm against the existing process on real orders (forecast error, fill rate, miles driven) before trusting it. Keep humans able to override it, and review those overrides: they often reveal a missing rule.
- Disruptions. Plans built for normal weeks fail in unusual ones. Re-run planning often and keep slack where a failure is expensive.
Learning the algorithms behind it
Supply chain software is built from the same pieces you meet in algorithm courses: shortest paths, greedy choices, sorting, heaps, dynamic programming and graph search. If you want to build them, practice the building blocks: real-world applications of graph algorithms shows where graphs appear, and the Greedy section of the lessons, for example Maximum Units on a Truck, is a small version of a loading decision.
