Sub topic 9
Building a batch scoring pipeline
This chapter assumes you know basic machine learning vocabulary (training, model, features, prediction), can read Python, and understand scheduled jobs. It builds on the earlier chapters on batch prediction and freshness. It shows how to turn a one-off scoring script into a pipeline you can run every day and trust.
What a batch scoring pipeline is
A batch scoring pipeline is a scheduled job that reads a set of records, computes features, applies a trained model, and writes the scores somewhere other systems can read them. The job runs, finishes, and releases its compute. Nothing waits for a user.
The basic version is short. This job loads a saved classifier, scores every customer in one pass, and writes the results to a file.
import joblib
import pandas as pd
model = joblib.load("model.joblib")
customers = pd.read_parquet("customers_2026-11-28.parquet")
feature_columns = ["tenure_months", "monthly_spend", "support_tickets"]
customers["churn_score"] = model.predict_proba(customers[feature_columns])[:, 1]
customers[["customer_id", "churn_score"]].to_parquet("scores_2026-11-28.parquet")This script works, but it is not yet a pipeline. It has no checks on its input, no record of which model produced the scores, and no safe way to rerun it. The rest of the chapter adds those pieces.
The stages of a pipeline
Most batch scoring pipelines have the same stages, whatever tool runs them.
- Extract. Read the records to score for a given run date.
- Validate. Check that the input has the expected columns, types, and a plausible row count.
- Build features. Compute the same features the model saw in training.
- Score. Apply the model to all rows.
- Validate output. Check that scores are in range and that no rows were lost.
- Publish. Write results to a destination that downstream systems read.
The two validation gates matter most. A batch job has no user watching it. If it silently produces bad scores, downstream systems will use them until someone notices.
Choosing the run date and input window
Tie every run to an explicit run date, not to "now". A job that calls the current time inside its logic gives different results when you rerun it tomorrow. A job that receives the date as a parameter gives the same result each time.
The example above already does this by putting the date in the file names. Make it a parameter:
import sys
from datetime import date
run_date = date.fromisoformat(sys.argv[1])
input_path = f"customers_{run_date.isoformat()}.parquet"
output_path = f"scores_{run_date.isoformat()}.parquet"Run it with python score.py 2026-11-28. This gives you three things: you can backfill past dates, you can rerun a failed day, and the output names tell you which snapshot each file came from.
Features at batch time
In batch scoring, features usually come from the same warehouse or tables used for training, so access is easy. The risk is consistency. If training computed monthly_spend as the average of the last three months and the batch job computes it from the last month, the model receives inputs from a different distribution than it learned from. This is training-serving skew.
Two practices reduce it:
- Put feature logic in one shared function or library that both the training code and the scoring code import.
- Keep the feature column order fixed in a single list, such as
feature_columnsabove, and use it in both places.
Also make sure features are computed as of the run date. If a feature table contains values from after the run date, you leak information that will not exist when you score live data. Backfills are where this goes wrong most often.
Validating input
Write the checks as code that fails the job, not as a comment saying someone should look.
import pandas as pd
REQUIRED = ["customer_id", "tenure_months", "monthly_spend", "support_tickets"]
def validate_input(df: pd.DataFrame, min_rows: int = 1000) -> None:
missing = [c for c in REQUIRED if c not in df.columns]
if missing:
raise ValueError(f"Missing columns: {missing}")
if len(df) < min_rows:
raise ValueError(f"Only {len(df)} rows, expected at least {min_rows}")
if df["customer_id"].duplicated().any():
raise ValueError("Duplicate customer_id values")
null_share = df[REQUIRED].isna().mean()
too_many = null_share[null_share > 0.05]
if not too_many.empty:
raise ValueError(f"High null share: {too_many.to_dict()}")Choose min_rows from your history. A table that normally has 2 million rows and suddenly has 40,000 almost always means an upstream failure, not a quiet day.
Scoring at scale
predict_proba on a DataFrame is fast for a few million rows on one machine. When the data no longer fits in memory, score in chunks. Chunking also lets you write partial output and bound memory use.
import joblib
import numpy as np
import pandas as pd
model = joblib.load("model.joblib")
feature_columns = ["tenure_months", "monthly_spend", "support_tickets"]
def score_in_chunks(df: pd.DataFrame, chunk_size: int = 100_000) -> pd.Series:
parts = []
for start in range(0, len(df), chunk_size):
chunk = df.iloc[start:start + chunk_size]
scores = model.predict_proba(chunk[feature_columns])[:, 1]
parts.append(pd.Series(scores, index=chunk.index))
return pd.concat(parts)Throughput is what matters here, not the delay for one row. Larger chunks usually use the CPU better, up to the point where memory becomes the limit. If one machine is still too slow, split the input by a key such as a hash of customer_id and run workers in parallel, or move to a distributed engine such as Spark. Do that only when measurement shows you need it.
Validating output
After scoring, check the result before publishing it.
def validate_output(scores: pd.DataFrame, expected_rows: int) -> None:
if len(scores) != expected_rows:
raise ValueError("Row count changed during scoring")
if scores["churn_score"].isna().any():
raise ValueError("Null scores found")
if not scores["churn_score"].between(0, 1).all():
raise ValueError("Scores outside [0, 1]")
mean = scores["churn_score"].mean()
if not 0.01 <= mean <= 0.60:
raise ValueError(f"Mean score {mean:.3f} outside the usual range")The last check compares the distribution to what you normally see. It catches the case where every row is valid but the model is clearly misbehaving, for example because a feature column shifted.
Publishing safely
Publishing is the step where partial failure hurts. If the job crashes halfway through writing, a downstream reader may load half a file.
- Write to a temporary path, then rename. A rename on the same file system is atomic, so readers see either the old file or the new one.
- Make the job idempotent. Running it twice for the same date should overwrite the same output, not append duplicates. Name outputs by run date, or use an upsert keyed on
customer_idand run date. - Record metadata. Store the model version, run date, row count, and feature version beside the scores.
import json
import os
import pandas as pd
def publish(scores: pd.DataFrame, output_path: str, model_version: str, run_date: str) -> None:
tmp_path = output_path + ".tmp"
scores.to_parquet(tmp_path)
os.replace(tmp_path, output_path)
meta = {
"run_date": run_date,
"model_version": model_version,
"rows": len(scores),
}
with open(output_path + ".meta.json", "w") as f:
json.dump(meta, f)Scheduling and dependencies
A scheduler such as cron, Airflow, or a cloud workflow service starts the job. The important design question is not which tool, but what the job waits for.
A job that runs at 02:00 assumes the upstream data is ready at 02:00. When the upstream job is late, you score yesterday's data and call it today's. Prefer a dependency over a clock: have the job start when the input marker for the run date exists, or have it check for that marker and wait or fail.
Set a deadline too. If the scores must be ready by 07:00 for a morning campaign, alert at 06:00 when the job has not finished. Add retries for transient errors such as a network timeout, but not for validation failures, which will fail the same way each time.
Freshness is set by the schedule
Predictions from a daily job are up to a day old when they are produced, and older by the time they are read. The effective staleness is the schedule interval plus the run time plus the delay before consumers pick them up. If a customer cancels at 09:00, a score computed at 02:00 still reflects the earlier state. A nightly run is fine for a weekly retention campaign and wrong for a fraud check on a live payment. If the schedule cannot be shortened enough, that is the signal to consider micro-batch or real-time scoring, covered in later chapters.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| Scores differ from offline evaluation | Feature logic differs between training and scoring | Share one feature function and one column list |
| Duplicate rows after a rerun | Output is appended instead of replaced | Overwrite by run date or upsert on key |
| Downstream reads a half-written file | Writing directly to the final path | Write to a temporary path, then rename or write a marker |
| Scores look fine but are wrong | Input was stale or truncated | Validate row counts and freshness before scoring |
| Backfill gives unrealistic accuracy | Features include data after the run date | Compute features as of the run date |
| Job runs out of memory | Whole table loaded at once | Score in chunks or partition the input |
| Old model used silently | Model file replaced without a version | Load a pinned version and store it in metadata |
Exercise
A nightly scoring job crashes at 03:10 after writing about half of its output to scores_latest.parquet. A downstream dashboard reads that file at 03:30. Name two changes to the pipeline that prevent the dashboard from showing partial results, and one change that makes the rerun safe.
Show answer
To prevent partial reads: (1) write to a temporary path and rename it to the final name only after the write succeeds, or write all files under a run-specific prefix and create a marker file last; (2) validate the output (row count equals input count, no null scores) before publishing, so a failed run never reaches the final path. To make the rerun safe, make the job idempotent: key the output by run date, or upsert on customer_id and run date, so running the same date twice replaces the earlier output instead of appending duplicates.
Exercise
Your daily job normally scores about 2 million customers. Today the input table has 60,000 rows and the job finished in a few seconds with no error. Which stage should have caught this, and what check would you add?
Show answer
The input validation stage should have caught it. Add a minimum row count check based on recent history, for example failing when the count is below 50% of the trailing seven-day average. Also check duplicate keys and the null share of each feature column. A sharp drop in rows usually means an upstream failure, so the job should stop and alert instead of publishing scores for a fraction of customers.