Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathEnd-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing
  1. 1
    Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
  2. 2
    Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
  3. 3
    Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
  4. 4
    Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
  5. 5
    Recommendations, Part 1: Two Stages, Candidates Then Ranking
  6. 6
    Recommendations, Part 2: Candidate Generation With Embeddings
  7. 7
    Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
  8. 8
    Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
  9. 9
    Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
  10. 10
    Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
  11. 11
    Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
  12. 12
    Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
  13. 13
    Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
  14. 14
    Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
  15. 15
    Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
  16. 16
    Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. End-to-End Use Cases

Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 12 of 16

Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule

Serve 315 published forecasts through one FastAPI route that never runs the model, then join them to what actually sold. A synthetic milk promo pushes milk's recent-to-older error ratio to 6.61 and the rule flags only milk, but a week earlier the same rule fired on one bad day.

Chaand Sheikh

·27 November 2026End-to-End Use Cases

What you will learn

  • Serve batch forecasts through a FastAPI read endpoint with no model in the request
  • Join forecasts to the actuals that have arrived with a left merge
  • Turn recent vs older error into a per-product retrain flag
  • Spot a false alarm from a short window

Before you start

  • Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
  • FastAPI basics (routes and HTTPException)

In Part 3, the nightly job published fifteen runs of forecasts for our shop: 315 rows. Now let's put them to use. The shop reads them through a small endpoint, and then we check them against what actually sold and ask whether the model needs retraining.

The demand is synthetic, and so is a milk promo I add halfway through. The retrain limit is a choice for this project, not a standard.

The sold-out signs

Picture a shop manager at closing time, holding this morning's forecast. She walks the aisles. There's a sold-out sign on milk, so the forecast was too low. Bread's about right, rice too. One sign doesn't mean much, so she keeps a note every day and looks for a pattern. That's monitoring: compare what we said with what happened, and keep doing it.

Serving and monitoring read the same table nightly job forecasts table GET /forecast outcome join the shop retrain flag latest run every run
The endpoint and the monitor read the same published table in different ways.

A small read endpoint: api.py

import sqlite3

from fastapi import FastAPI, HTTPException

import common

app = FastAPI()


@app.get("/forecast/{product}")
def read_forecast(product: str):
    db = sqlite3.connect(common.DB)
    sql = "select max(run_id) from forecasts"
    run_id = db.execute(sql).fetchone()[0]
    rows = db.execute(
        "select day, yhat from forecasts "
        "where run_id = ? and product = ? order by day",
        (run_id, product)).fetchall()
    if not rows:
        raise HTTPException(404, f"no {product}")
    days = [{"day": d, "yhat": y} for d, y in rows]
    return {"run_id": run_id, "product": product,
            "forecast": days}

First it asks the table for the biggest run id. Our ids carry the date (run-2026-02-17), so the biggest one is the latest. Then it fetches only that run, for that product, ordered by day. No rows means a 404.

And look what's missing: there's no model in this file. The model never runs during a request. That's what batch serving means; Online, Batch or Streaming? explains when to pick it.

Two calls

Called through FastAPI's TestClient, so no server was started. GET /forecast/milk returns 200:

{"run_id": "run-2026-02-17", "product": "milk", "forecast": [{"day": "2026-02-18", "yhat": 204.9}, {"day": "2026-02-19", "yhat": 188.0}, {"day": "2026-02-20", "yhat": 139.0}, {"day": "2026-02-21", "yhat": 94.3}, {"day": "2026-02-22", "yhat": 127.3}, {"day": "2026-02-23", "yhat": 163.8}, {"day": "2026-02-24", "yhat": 204.3}]}

And GET /forecast/tea returns 404:

{"detail": "no tea"}

Every request gets the same answer until the next run publishes. That's how a batch forecast should behave. (For limits, health checks and versions on a model API, see A Production FastAPI for an ML Model.)

Forecasts meet actuals: the outcome join

Every forecast is a guess about a day that hasn't happened yet. Then the day happens. Here is monitor.py:

import sqlite3
import sys

import pandas as pd

from common import DB, make_demand

LIMIT = 1.5   # retrain when recent error is 1.5x older


def outcome_join(db, today):
    """forecasts meet the actuals that have arrived"""
    f = pd.read_sql("select * from forecasts", db)
    a = make_demand()
    a = a[a["date"] <= today].copy()
    a["day"] = a["date"].dt.strftime("%Y-%m-%d")
    a = a[["product", "day", "units"]]
    j = f.merge(a, on=["product", "day"], how="left")
    j["abs_err"] = (j["units"] - j["yhat"]).abs()
    return j
  • It reads every forecast from every run, including the older ones.
  • It takes the actuals only up to today, because that's all we'd know.
  • It's a left merge on product and day. Forecasts whose day hasn't arrived have to stay; an inner join would quietly drop them.

As of 17 February: 315 forecasts, 231 with actuals, 84 still waiting. Move today to 24 February and waiting drops to 0; every row now has an absolute error. Waiting for answers is a theme of its own in When Labels Arrive Weeks Late.

Something changes: a synthetic promo

Now let's change the world a little. In common.py, from 18 February milk sells 35% more:

PROMO = "2026-02-18"   # synthetic: milk sells 35% more

Our last run was on 17 February, so every forecast for that week was made before the promo. Here is that run's milk forecast next to what sold:

Milk: the 17 February forecast vs units sold 18 Feb 19 Feb 20 Feb 21 Feb 22 Feb 23 Feb 24 Feb 284 175 94.3 forecast (run-2026-02-17) units sold Bars to scale. Synthetic demand with a synthetic promo from 18 Feb.
The forecast was made before the promo, so it's short every day of the week.

On the 18th we said about 205 and the shop sold 284, roughly 79 units short. The 21st is worse: we said 94.3 and it sold 175. Nothing crashed. The job is fine and the endpoint is fine. Only the comparison shows this.

The retrain rule: decide

def decide(joined, today):
    seen = joined.dropna(subset=["units"]).copy()
    age = today - pd.to_datetime(seen["day"])
    seen["age"] = age.dt.days
    old = seen[seen["age"] >= 7].groupby("product")
    new = seen[seen["age"] < 3].groupby("product")
    out = pd.DataFrame({"older": old["abs_err"].mean(),
                        "recent": new["abs_err"].mean()})
    out["ratio"] = out["recent"] / out["older"]
    out["retrain"] = out["ratio"] > LIMIT
    return out.round(2)

It splits the rows that have actuals by age. Older means seven days old or more; recent means the last three days. It takes the mean error of each and divides recent by older. If that ratio is above LIMIT, 1.5, retrain is true. That limit is my choice for this project. Running python monitor.py 2026-02-24:

315 forecasts, 0 waiting
         older  recent  ratio  retrain
product
bread     7.41    4.27   0.58    False
milk      7.37   48.72   6.61     True
rice      2.98    3.92   1.32    False

Milk goes from 7.37 to 48.72, a ratio of 6.61, so retrain is true. Bread at 0.58 and rice at 1.32 stay false. The promo only touched milk, and the rule points only at milk.

A false alarm

That looks neat, but run the same rule a week earlier, as of 17 February, before the promo begins:

315 forecasts, 84 waiting
         older  recent  ratio  retrain
product
bread     5.25    5.91   1.13    False
milk      3.39   11.75   3.47     True
rice      2.92    3.17   1.09    False

Milk fires with a ratio of 3.47, and there's no promo yet. Why? The recent window is only three days. Milk was off by 7.7, then 0.0, then 27.6. One bad day pushed it over the limit. So this rule didn't see the promo coming; it was a false alarm that happened to land a day early.

And the monitor doesn't retrain anything. It raises a flag. True means somebody takes a look, not that a model gets replaced on its own. How to wire flags like this to a retrain pipeline is covered in Retraining Triggers.

Common mistakes

  • Running the model in the request. For a batch forecast, the endpoint only reads what was published.
  • An inner join to the actuals. It drops every forecast still waiting, and the waiting ones disappear from view.
  • One error number for all products. The promo hit only milk; per-product ratios showed that.
  • A window too short to trust. Three days let one day of 27.6 trigger a retrain.
  • Auto-retraining on a flag. Treat the flag as a reason to look.

Recap

PieceResult
Read endpointLatest run (run-2026-02-17), 200 for milk, 404 for tea, no model in the request
Outcome join, 17 Feb315 forecasts, 231 with actuals, 84 waiting
Rule on 24 Febmilk 6.61 (retrain), bread 0.58, rice 1.32
Rule on 17 Febmilk 3.47 (false alarm from one bad day)

Try it yourself: change the recent window in decide from 3 days to 5, run the monitor for 17 February, and see if milk still fires. The project files are in the community, free to join.

That completes the forecasting use case: the business problem, the backtest, the nightly job and the serving and monitoring above.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
Next →
Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API

The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.

Fraud Scoring, Part 1: The Problem, the Metric and the Baseline

Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.

Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold

Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.

Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget

A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.

On this page
  • The sold-out signs
  • A small read endpoint: api.py
  • Two calls
  • Forecasts meet actuals: the outcome join
  • Something changes: a synthetic promo
  • The retrain rule: decide
  • A false alarm
  • Common mistakes
  • Recap
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.