Sub topic 5
Freshness and staleness of predictions
Prerequisites and scope
This chapter assumes you know basic machine learning vocabulary (training, model, features, prediction) and can read Python. You should also know what a scheduled job and an HTTP API are. It builds on the earlier chapters that defined batch prediction (scoring many records on a schedule) and real-time prediction (scoring one request on demand). Here the focus is a single question: how old is the information behind a prediction at the moment someone uses it?
What freshness means
A prediction is a function of a model and a set of feature values. Both can be out of date. Freshness describes how recent the inputs and the computation behind a prediction are. Staleness is the opposite: the gap between the state of the world and the state of the world that the prediction reflects.
Staleness is not a single number. There are three separate ages to track:
- Feature age. How old the feature values are when the model reads them. A "support tickets in the last 30 days" feature computed at midnight is up to 24 hours old by the next evening.
- Prediction age. How long ago the score was computed. A batch score written at 02:00 and read at 17:00 is 15 hours old, whatever the age of its features.
- Model age. How long ago the model was trained. A model trained three months ago may no longer match current behavior. This is a related problem, usually called drift, and it affects batch and real-time serving equally.
The total staleness a user experiences is roughly the feature age at scoring time plus the prediction age at reading time. A batch score can be stale in both ways. A real-time score has a prediction age near zero but can still use old features.
How batch and real-time differ
In a batch job, every record is scored at one point in time, and the results sit in storage until something reads them. The staleness of any given score grows steadily until the next run replaces it.
In an online service, scoring happens when the request arrives. Prediction age is close to zero. Staleness comes only from the features.
The diagram below shows how staleness changes over time for a daily batch job.
The worst-case staleness of a scheduled batch is the schedule interval plus the job's runtime plus any delay before the data is loaded into the system that serves it. A daily job that takes three hours and publishes at the end can deliver scores that are up to 27 hours old.
Measuring staleness
You cannot manage what you do not measure. Store a timestamp with every score and compute age at read time.
from datetime import datetime, timezone
import pandas as pd
def score_age_hours(scores: pd.DataFrame, now: datetime | None = None) -> pd.Series:
"""Return the age in hours of each score, based on its scored_at column."""
now = now or datetime.now(timezone.utc)
scored_at = pd.to_datetime(scores["scored_at"], utc=True)
return (now - scored_at).dt.total_seconds() / 3600
scores = pd.DataFrame(
{
"customer_id": [1, 2, 3],
"churn_score": [0.82, 0.10, 0.45],
"scored_at": [
"2026-11-28T02:00:00Z",
"2026-11-28T02:00:00Z",
"2026-11-27T02:00:00Z",
],
}
)
now = datetime(2026, 11, 28, 10, 0, tzinfo=timezone.utc)
scores["age_hours"] = score_age_hours(scores, now)
print(scores[["customer_id", "age_hours"]])The output shows ages of 8, 8, and 32 hours. The third row is older than the others, which usually means a previous run skipped that customer or a later run failed. A sudden spread in ages is often the first visible sign of a pipeline problem.
Two metrics are worth putting on a dashboard:
- Maximum score age across all records, which catches failed or skipped runs.
- Percentile score age (for example the 95th percentile), which shows what most users see.
When freshness matters
Freshness has value only if the underlying signal changes quickly relative to how often the prediction is refreshed. Ask how fast the thing you are predicting can change, and how much a change would alter the decision.
| Use case | How fast the signal changes | Typical tolerance for staleness |
|---|---|---|
| Card fraud on a payment | Seconds, the current transaction is the signal | Under a second of feature lag, scored per request |
| Product recommendations on a home page | Minutes to hours, based on recent clicks | Minutes to hours |
| Customer churn risk | Days to weeks | One day is usually fine |
| Credit limit review | Weeks to months | Weekly or monthly |
A churn score that is 20 hours old is rarely a problem, because a customer's tenure and spending pattern barely change in a day. A fraud score computed from yesterday's data is useless, because the fraudulent transaction did not exist yet.
Staleness can change the decision, not just the number
A useful test is to ask whether a stale score would lead to a different action than a fresh one. If a customer's churn score moves from 0.45 to 0.47 overnight, no one acts differently. If a customer opens three support tickets in an hour and their score would jump from 0.45 to 0.85, a campaign that targets scores above 0.7 misses them until the next run. The cost of staleness is the cost of the wrong decisions made in that gap.
Ways to reduce staleness
You have several options, and they cost different amounts.
- Run the batch more often. Moving from daily to hourly cuts worst-case staleness from about 24 hours to about 1 hour. The cost is more compute and more pipeline runs to monitor. If the job rescoring every customer is wasteful, rescore only records whose inputs changed.
- Use micro-batches. Run small jobs every few minutes on recently changed records. A later chapter covers this pattern.
- Score on demand. Compute the prediction when it is requested. This removes prediction age, but you still need fresh features.
- Precompute with a live fallback. Serve a stored score when it is recent enough and compute a new one when it is not.
The last option can be written as a small function that makes the freshness rule explicit:
from datetime import datetime, timedelta, timezone
def get_score_with_max_age(customer_id, stored, live_predict, features_for, max_age):
"""Return a stored score if it is recent enough, otherwise score live.
stored maps customer_id to a (score, scored_at) tuple.
max_age is a timedelta.
"""
now = datetime.now(timezone.utc)
entry = stored.get(customer_id)
if entry is not None:
score, scored_at = entry
if now - scored_at <= max_age:
return score, "batch"
return live_predict(features_for(customer_id)), "realtime"
stored = {
1: (0.82, datetime.now(timezone.utc) - timedelta(hours=2)),
2: (0.10, datetime.now(timezone.utc) - timedelta(hours=30)),
}
result = get_score_with_max_age(
2,
stored,
live_predict=lambda features: 0.12,
features_for=lambda customer_id: [12, 40.0, 1],
max_age=timedelta(hours=24),
)
print(result)Customer 2's stored score is 30 hours old, which exceeds the 24-hour limit, so the function falls back to the live path and prints (0.12, 'realtime'). The max_age parameter turns a vague requirement ("reasonably fresh") into a testable one.
Edge cases and common errors
- Staleness hidden by the serving layer. A cache in front of an online endpoint can return a score that is minutes or hours old. Set a time-to-live (TTL) on cached predictions and make sure it matches your tolerance.
- Late-arriving data. A batch job that runs at 02:00 may miss events that were recorded at 01:55 but arrived at 02:10. The score looks fresh but ignores recent events. Define a cutoff and wait for late data, or accept the gap and document it.
- Training-time leakage of freshness. If you train on features computed with full knowledge of the day, but serve with features lagged by 24 hours, the model sees different data in production. This is a form of training-serving skew and is covered in the chapter on skew.
- Silent job failures. If a batch job fails and the old file remains in place, readers keep consuming old scores without any error. Check the timestamp, not just that the file exists.
- Mixed ages in one table. If only some records are rescored each run, the table contains scores of different ages. Report the age of each score along with its value.
- Time zones. Compute ages in UTC. Comparing a local timestamp with a UTC one produces ages that are off by hours.
A practical way to set a freshness requirement
- Identify the decision the prediction supports.
- Estimate how quickly the relevant signal changes.
- Estimate the cost of acting on a stale score, in money or user harm.
- Pick a maximum acceptable age, such as "no older than 6 hours".
- Choose the cheapest serving design that meets that limit with margin.
- Monitor the real age against the limit.
Stating the requirement as a number lets you compare designs. "Fresh" is not a requirement. "95% of scores younger than 15 minutes" is.
Exercise
A nightly batch job starts at 01:00, takes 2 hours, and publishes its results at the end. Scores are read by a dashboard at any time of day. What is the worst-case age of a score at the moment a user reads it, assuming each run succeeds? How would the worst case change if the job were moved to run every 6 hours with the same runtime?
Show answer
The worst case is just before the next run's results are published. The schedule interval is 24 hours and publishing happens 2 hours after each start, so the previous scores were computed from data as of 01:00 and a user reading just before the next publish at 03:00 sees data about 26 hours old (24 hours interval plus 2 hours runtime). If the job ran every 6 hours with the same 2-hour runtime, the worst case would be about 8 hours (6 plus 2). The trade-off is four times as many runs, so higher compute cost and more runs to monitor.
Exercise
An online prediction endpoint responds in 30 ms, but its features come from a table that is rebuilt once per day. A product manager says the predictions are "real time and therefore fresh". Is that correct? What would you check or change?
Show answer
Not correct. The prediction age is near zero, but the feature age can be up to 24 hours, so the score reflects day-old inputs. Check how and when the feature table is refreshed and how old the values are at read time. To improve freshness, refresh the features more often, compute the fast-changing features from live events at request time, or move those features into an online store that is updated as events arrive. Also add feature timestamps to the logs so that feature age can be monitored.