Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 11 of 16
Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
Make the shop's forecast a nightly job, then kill it halfway: a plain rerun publishes 35 rows instead of 21 with exit code 0. A run id from the date, one part file per product and a primary key make the resume print scored 1, skipped 2, published 21.
What you will learn
- Turn a forecast into one nightly script with validate, score and publish stages
- See how a crash plus a plain rerun publishes duplicate rows with exit code 0
- Make the job safe to rerun with a run id, part files and a primary key
- Hand the same script to a scheduler that retries
Before you start
- Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
- Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
So far, our shop's forecast runs when somebody types a command. In this part it becomes a job that runs every night on its own. We'll kill that job halfway through on purpose, look at the damage, and then fix it so a restart never publishes anything twice.
The demand is still synthetic (milk, bread and rice, seed 7). Every crash, rerun and row count below comes from real runs of the project's nightly.py.
The night shift
Picture the night shift that fills the shop's shelves before opening. One worker, three aisles. Halfway through, the worker is called away: milk and bread are done, rice isn't. A new worker arrives with no notes and starts again from aisle one. Milk and bread get stocked twice, and the shelves overflow.
A better shift keeps a checklist. Each aisle gets a tick only when it's finished, so the new worker reads the list and goes straight to rice. That's this whole part. Jobs do crash, so what matters is what the restart does.
Crash once, rerun once
Let's do the clumsy version first. nightly.py has a naive mode (set the NAIVE environment variable) with no part files and no key, and we score the night of 10 February 2026. A helper in common.py kills the process on purpose:
def maybe_crash(n):
"""the job dies hard when CRASH_AT is this product"""
if os.environ.get("CRASH_AT") == str(n):
os._exit(1)
With CRASH_AT=1, the process dies right after bread. It prints nothing, and the exit code is 1. Milk and bread are already in the table, 14 rows. Run it again without the crash:
run-2026-02-10: scored 3, skipped 0, published 35
Three products times seven days is 21 rows, so 14 of those 35 are duplicates. And this second run exits with code 0. Nothing looks wrong, and anyone adding up the table counts milk and bread twice.
Three small guards
The fix is three small things, and none of them is clever:
| Guard | What it is | What it answers |
|---|---|---|
| Run id | Built from the date: run-2026-02-10. Run the same night twice, get the same id. | Which night? |
| Part file | One file per product in a folder named after the run. If the file is there, that product is done. | What's finished? |
| Primary key | (run_id, product, day) on the table. Publishing the same row again replaces the old one. | Is a second publish harmless? |
If you've read Batch Scoring a Million Rows, the run id and part files will look familiar. Here they sit in a real nightly forecast, with a database table at the end.
Validate, score, publish: nightly.py
import os
import sys
from pathlib import Path
import pandas as pd
from common import *
NAIVE = os.environ.get("NAIVE") # no run id, no parts
day = pd.Timestamp(sys.argv[1])
run_id = f"run-{day:%Y-%m-%d}"
run = Path("out") / run_id
run.mkdir(parents=True, exist_ok=True)
hist = history(day)
validate(hist, day)
model = fit(hist)
db = store(DB)
scored = skipped = 0
for n, name in enumerate(PRODUCTS):
part = run / f"{name}.csv"
if NAIVE:
frame = forecast(model, hist, name, day)
publish(db, run_id, frame, "naive")
scored += 1
maybe_crash(n)
elif part.exists():
skipped += 1
publish(db, run_id, pd.read_csv(part))
else:
write_part(forecast(model, hist, name, day), part)
scored += 1
maybe_crash(n)
publish(db, run_id, pd.read_csv(part))
table = "naive" if NAIVE else "forecasts"
sql = f"select count(*) from {table} where run_id = ?"
count = db.execute(sql, (run_id,)).fetchone()[0]
print(f"{run_id}: scored {scored}, skipped {skipped}, "
f"published {count}")
- The date becomes the run id, and the run id becomes a folder under
out. - Validate.
history(day)returns only what the shop knew that night.validateasserts the newest date equals the run date and the units are present and not negative, so stale data stops the job before anything is scored. - Score. For milk,
part.exists()is false, so we forecast seven days, write the part and count it as scored. - Publish reads from the part file, so what's in the table is exactly what's on disk.
- The other branch: if the part is already there, we skip the scoring but still publish it. Keep an eye on that line.
One detail: the nightly model in common.py is a Ridge refitted each night on lag_7, lag_14 and dow. It doesn't use mean_7, so it isn't the exact model from Part 2.
Done means complete: common.py
Two short functions carry most of the safety:
def write_part(frame, part):
tmp = part.with_name(part.name + ".tmp")
frame.to_csv(tmp, index=False)
tmp.replace(part) # a part exists when complete
def publish(db, run_id, frame, table="forecasts"):
"""the key makes a second publish a replace"""
verb = "insert"
if table == "forecasts":
verb = "insert or replace"
rows = [(run_id, *r)
for r in frame.itertuples(index=False)]
sql = f"{verb} into {table} values (?, ?, ?, ?)"
db.executemany(sql, rows)
db.commit()
write_part doesn't write to milk.csv. It writes milk.csv.tmp first, then tmp.replace(part) renames it in one step. If the process dies during the write, there's only a tmp file, and part.exists() still says no.
publish uses insert or replace on the forecasts table, whose primary key is (run_id, product, day). The first time, the row goes in. The second time it's the same key, so it takes the old row's place and the count doesn't move. A test checks exactly this: publish rice twice, and the table still has seven rows. All five tests pass:
..... [100%]
5 passed in 2.09s
Same crash, safe job
Same night, same crash, the safe path this time. The job dies at bread again. Bread's part file was written, but the crash came before publish. So milk is in the table, bread is only on disk, and rice hasn't started. Then two plain reruns:
run-2026-02-10: scored 1, skipped 2, published 21
run-2026-02-10: scored 0, skipped 3, published 21
Bread is the line I asked you to watch. Its part is there, so it's skipped, and this time it reaches the table. Without the publish in the skipped branch, bread would never be published for this run. The third run says scored 0, skipped 3, still 21, and the table matches a clean run with no crash at all.
The schedule: an Airflow DAG
So far I've rerun the job by hand. In production a scheduler does that, and Airflow is a common choice. The project includes a small DAG file. Airflow isn't installed in this project, so this file was never parsed or run; treat it as an example to read. The crash and resume results above come from plain reruns of nightly.py.
"""The nightly forecast job as an Airflow DAG (needs an Airflow setup)."""
from datetime import datetime
from airflow import DAG
from airflow.operators.bash import BashOperator
with DAG(
"nightly_forecast",
schedule="0 2 * * *",
start_date=datetime(2026, 2, 3),
catchup=False,
default_args={"retries": 2},
) as dag:
BashOperator(
task_id="validate_score_publish",
bash_command="python nightly.py {{ ds }}",
cwd="/opt/forecast",
)
It says: run every night at two, with one task that calls our same script with the date. Validate, score and publish all stay inside nightly.py. With retries at 2, if the script exits with code 1, Airflow runs it again, and that's exactly the rerun you just saw. So Airflow decides when to run and when to try again; the part files and the key are what make trying again safe. For more on the scheduler itself, see Orchestrating ML Pipelines with Airflow and The Training Pipeline as a DAG.
Running the safe job for every night from 3 to 17 February gives 15 runs of 21 rows each, 315 forecasts. That's the table Part 4 serves and monitors.
Common mistakes
- Trusting exit code 0. The naive rerun succeeded and doubled 14 rows.
- A random or time-of-run id. The id must come from the date being scored, so a rerun lands on the same rows.
- Writing the final file directly. A half-written file looks finished. Write a tmp file and rename it.
- Skipping finished work entirely. If a product's part is there but never reached the table, skipping the publish loses it.
- Letting the scheduler fix it. Retries only help when the job is safe to run again.
Recap
| Run | Output |
|---|---|
| Naive: crash, then rerun | published 35 (14 duplicates), exit code 0 |
| Safe: crash, then resume | scored 1, skipped 2, published 21 |
| Safe: run again | scored 0, skipped 3, published 21 |
| Tests | 5 passed |
Try it yourself: remove the publish line from the skipped branch, crash at 1, rerun, and count the rows.
In Part 4, the shop reads these forecasts through an endpoint, and we check them against what actually sold.
StudyEasy AI Community
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
Related course on Udemy
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 (paid course, opens in a new tab)Related posts
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.