Sub topic 2
Batch prediction: scoring many records on a schedule
This chapter assumes you know basic machine learning vocabulary (training, model, features, prediction). It also assumes you can read Python and have a general idea of what a scheduled job is. You do not need to know any serving framework.
What batch prediction is
Batch prediction means running a trained model over a large set of records at one time, usually on a schedule, and storing the results. The model does not wait for a user to ask. A job starts, reads the records, scores all of them, and writes the scores somewhere. Other systems read those stored scores later.
The key idea is that prediction and consumption are separated in time. The job that creates a score runs at one moment. The system that uses the score reads it at another moment, possibly hours later.
Common examples:
- A nightly job that scores every customer for churn risk, so the retention team has a ranked call list each morning.
- A weekly job that computes product recommendations for all users and stores them for the website to show.
- A monthly job that scores loan accounts for default risk for a regulatory report.
How a batch run works
A batch run follows the same steps each time.
- A scheduler starts the job. This could be cron, Airflow, a cloud scheduler, or a workflow service.
- The job loads the model artifact, which is the saved file containing the trained model.
- The job reads the input records, usually from a data warehouse table or files in object storage.
- The job builds the features for each record.
- The model scores the records, often in large chunks.
- The job writes the scores to a destination such as a table, a file, or a key-value store.
- Downstream systems read the stored scores.
A minimal example
The following job loads a saved scikit-learn classifier, scores every customer row in one pass, and writes the results to a Parquet 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")Several details in this short script matter.
- The model is loaded once, then used for the whole file. Loading cost is paid once per run, not once per record.
predict_probareceives a whole DataFrame. Scikit-learn runs vectorized code over all rows, which is far faster than calling the model in a Python loop.[:, 1]selects the probability of the positive class. For a binary classifier, column 0 is the negative class.- The input and output file names contain the run date. The output keeps only the key (
customer_id) and the score, which keeps the file small and easy to join. - The feature column list is explicit. The order and names must match what the model saw in training.
Why teams choose batch
Batch prediction has strong practical advantages.
- High throughput. The job can process millions of rows with vectorized operations and parallel workers. Throughput means how many records are scored per unit of time.
- Efficient use of hardware. You start compute, use it fully, and release it. You can run on cheaper capacity such as spot or preemptible instances, because a failed run can simply be retried.
- Simple operations. There is no service that must be up at all times. If the job fails, you rerun it. Nobody is waiting on a response.
- Easy access to features. The job can read full history from a warehouse with large joins and aggregations. These would be too slow to run at request time.
- Easy validation. You can inspect the full output before publishing it. You can check row counts, score distributions, and null rates, and stop the release if they look wrong.
- Fast reads for consumers. A consumer looks up a stored score. That is a cheap read, with no model call on the critical path.
The main costs of batch
Batch has limits you should understand before choosing it.
Staleness
A stored score reflects the data at the time the job ran. If the job ran at 02:00 and a customer opened three support tickets at 09:00, the score does not know. The age of a score is called its staleness. A nightly job means scores can be up to about 24 hours old, plus the job's own run time. This is the main trade-off, and a later chapter covers it in detail.
Wasted work
A batch job scores everyone, including records nobody will ever look at. If you score 10 million users nightly and only 500,000 visit the site, most of the compute produced scores that were never read. This is acceptable when scoring is cheap, and a poor fit when it is expensive.
No coverage for new records
A record created after the job ran has no score until the next run. A customer who signs up at noon has no churn score until tomorrow. Systems that read scores must decide what to do when a lookup returns nothing. The hybrid chapter later in this tutorial covers one answer, which is a live fallback.
Delayed failure detection
If a nightly job fails silently, consumers keep reading yesterday's scores, then the day before's. The system looks healthy while its predictions age. You need an explicit check on score freshness, not only on whether the job process exited.
Design choices that matter
Full run or incremental run
A full run scores every record each time. It is simple and always consistent. An incremental run scores only records that are new or changed since the last run. It saves compute but adds logic to track what changed, and it can leave old scores in place that should have been updated because a feature changed for reasons you did not track. Start with full runs. Move to incremental runs when run time or cost forces you to.
Output layout
Write each run to a new, dated location, as the example does with scores_2026-11-28.parquet. Then publish by switching a pointer, such as a view or a "latest" alias, to the new location. This gives you three benefits:
- Consumers never see a half-written file.
- You can roll back by pointing at the previous run.
- You keep a history to compare against when something looks wrong.
Idempotency
A job is idempotent when running it twice with the same inputs produces the same result and causes no harm. Make the run date an explicit parameter, not something read from the clock inside the job. Then a retry or a backfill (rerunning for a past date) behaves predictably. Writing to a dated location, instead of appending to a shared table, helps here, because a rerun overwrites its own output and does not create duplicates.
Chunking large inputs
When data does not fit in memory, read and score it in chunks. The following sketch scores a Parquet dataset one row group at a time.
import joblib
import pyarrow.parquet as pq
model = joblib.load("model.joblib")
feature_columns = ["tenure_months", "monthly_spend", "support_tickets"]
source = pq.ParquetFile("customers_2026-11-28.parquet")
writer = None
for batch in source.iter_batches(batch_size=100_000):
chunk = batch.to_pandas()
chunk["churn_score"] = model.predict_proba(chunk[feature_columns])[:, 1]
table = pq.pa.Table.from_pandas(chunk[["customer_id", "churn_score"]])
if writer is None:
writer = pq.ParquetWriter("scores_2026-11-28.parquet", table.schema)
writer.write_table(table)
if writer is not None:
writer.close()Memory use stays near the size of one chunk, whatever the file size. Pick a chunk size large enough to keep the model's vectorized code efficient, and small enough to fit in memory.
Common errors
| Error | What happens | Fix |
|---|---|---|
| Feature columns in a different order than in training | Scores are wrong but no error is raised, if all columns are numeric | Keep the column list in one shared place and select by name |
| Features computed with different logic than in training | Scores drift from what you validated | Reuse the same feature code for training and scoring |
| Job reads "today" from the clock | Retries and backfills produce different results | Pass the run date as a parameter |
| Output written in place | Consumers read partial files during a run | Write to a new location, then switch a pointer |
| Only job success is monitored | Stale scores go unnoticed | Alert on the age and row count of the published scores |
| Records with missing features dropped silently | Some customers have no score and nobody knows | Count and report dropped rows, and choose an explicit default or failure |
When batch is the right fit
Batch is a good default when most of these are true:
- The decision using the score is made well after the score could be computed, or in bulk.
- A delay of hours or a day does not change the value of the prediction.
- The set of records to score is known ahead of time and is not too large for the budget.
- The features come from historical data that is already in a warehouse.
- Consumers need fast, simple lookups.
Batch is a poor fit when the right answer depends on what the user just did, such as fraud checks on a payment that is happening now.
Exercise
A nightly batch job scores 5 million users for purchase likelihood. A user signs up at 11:00 a.m. and opens the app at 11:05 a.m. Name two problems the batch design creates for this user, and one process change that would make reruns safe.
Show answer
First, the user has no score until the next nightly run, so a lookup for this user returns nothing and the app needs a default. Second, any score the user later receives will be based on data from the run time, so activity during the day (the user's first purchases, for example) is not reflected. To make reruns safe, pass the run date as an explicit parameter and write each run to its own dated output location, then publish by switching a pointer. Retries and backfills then give the same result and never leave duplicates or half-written files.
Exercise
Your batch job finishes with exit code 0 every night, but the sales team reports that the scores look the same for three days. What likely went wrong, and what check would catch it?
Show answer
The job probably succeeded without publishing new data, for example because it read a stale input table or wrote to the old location, so consumers kept reading old scores. A freshness check would catch it: alert when the published scores are older than the expected schedule allows, and compare the row count and score distribution of each run with the previous one.