Sub topic 6
Limiting staleness with TTL and join tolerance
This chapter assumes you can already write an as-of join, as covered in the previous chapter. It also assumes you are comfortable with pandas merge_asof, SQL left joins and window functions, and timestamps in one consistent time zone. Here you will learn how to stop an as-of join from attaching a feature value that is technically in the past but too old to be useful.
The problem: an as-of join always finds something
An as-of join returns the latest feature row at or before the prediction time. It does not ask how old that row is. If a customer's last feature row is 400 days old, the join attaches it anyway.
This causes two problems:
- Silent staleness in training. The model learns from values that look current but describe a customer a year ago.
- A mismatch with serving. Production systems usually expire old values. If serving returns "missing" for a 400-day-old value but training used it, the model sees a different input distribution online than it saw offline.
Staleness is not future leakage. Every joined row is still from the past. It is a separate correctness problem, and the fix is to put an upper bound on how old a joined value may be.
Defining age, TTL, and tolerance
The age of a joined feature value is the prediction time minus the feature's event time:
age = prediction_ts - feature_tsTwo names describe a limit on age:
- TTL (time to live) is a property of the feature. It says how long a value stays valid after it was computed. Online stores and feature stores such as Feast configure it per feature view.
- Join tolerance is a parameter of the training join. It is the largest age the join accepts. The
toleranceargument ofpd.merge_asofis one example.
They should be the same number. The TTL decides what serving returns, and the tolerance decides what training sees. If a value expires online after 30 days, the training join must also reject values older than 30 days.
The decision for each label row looks like this:
Tolerance in pandas
The tolerance argument rejects matches whose time difference is too large. The label row stays in the result and the feature columns become NaN.
import pandas as pd
labels = pd.DataFrame(
{
"customer_id": [1, 1, 2],
"prediction_ts": pd.to_datetime(["2026-03-01", "2026-04-15", "2026-03-01"]),
"churned": [0, 1, 1],
}
)
features = pd.DataFrame(
{
"customer_id": [1, 1, 2],
"feature_ts": pd.to_datetime(["2026-02-20", "2026-03-10", "2026-01-05"]),
"avg_spend_30d": [40.0, 55.0, 10.0],
}
)
labels = labels.sort_values("prediction_ts")
features = features.sort_values("feature_ts")
train = pd.merge_asof(
labels,
features,
left_on="prediction_ts",
right_on="feature_ts",
by="customer_id",
direction="backward",
tolerance=pd.Timedelta("30D"),
)
train["age_days"] = (train["prediction_ts"] - train["feature_ts"]).dt.days
train["spend_missing"] = train["avg_spend_30d"].isna()
print(train)
print("missing rate:", train["spend_missing"].mean())The three label rows behave as follows:
| Customer | Prediction time | Latest earlier feature row | Age | Result |
|---|---|---|---|---|
| 1 | 2026-03-01 | 2026-02-20 | 9 days | Joined, value 40 |
| 1 | 2026-04-15 | 2026-03-10 | 36 days | Rejected, `NaN` |
| 2 | 2026-03-01 | 2026-01-05 | 55 days | Rejected, `NaN` |
Three details in the code are easy to get wrong:
- Both DataFrames must be sorted by their
oncolumn, not byby.merge_asofraises an error otherwise. - The two time columns must have the same dtype, including the same time zone handling. A mix of naive and timezone-aware timestamps fails.
- The
age_dayscolumn is worth keeping while you develop the pipeline. Its distribution tells you whether the tolerance is sensible, and it feeds the checks described below.
Tolerance in SQL
In SQL you express the tolerance as a lower bound on the join condition. The example below uses PostgreSQL interval syntax. Other engines spell it differently, for example DATEADD or INTERVAL 30 DAY.
WITH candidates AS (
SELECT
l.customer_id,
l.prediction_ts,
l.churned,
f.avg_spend_30d,
f.event_ts AS feature_ts,
ROW_NUMBER() OVER (
PARTITION BY l.customer_id, l.prediction_ts
ORDER BY f.event_ts DESC
) AS rn
FROM labels AS l
LEFT JOIN feature_history AS f
ON f.customer_id = l.customer_id
AND f.event_ts <= l.prediction_ts
AND f.event_ts >= l.prediction_ts - INTERVAL '30 days'
)
SELECT customer_id, prediction_ts, churned, avg_spend_30d, feature_ts
FROM candidates
WHERE rn = 1;Put the tolerance in the ON clause, not in a WHERE clause. A WHERE filter on f.event_ts removes the label rows that had no match, which turns the left join into an inner join. Your label count then shrinks without any error. With the condition in ON, a label row with no fresh feature row survives once, with null feature columns.
The result matches the pandas version. The latest row inside the window is also the latest row overall whenever any row is inside the window.
Choosing a value
There is no universal tolerance. Three inputs decide it.
- Update cadence. If a feature is recomputed daily, a tolerance under one day produces nulls for most rows. Set the tolerance to at least the update interval plus the normal pipeline delay.
- How fast the signal decays. A "last login" feature is almost useless after a few days. A customer's country barely changes in years.
- What serving does. Use the TTL configured online. If you cannot change it, copy its value into training.
Some typical choices:
| Feature kind | Update cadence | Reasonable tolerance | Reason |
|---|---|---|---|
| Rolling 30-day spend | Daily | 2 to 3 days | Missing a few daily refreshes is normal, a month-old value is misleading |
| Account plan or tier | On change | 365 days or none | Value stays true until changed |
| Last session length | Per event | 1 to 7 days | Signal fades quickly |
| Credit score snapshot | Monthly | 35 to 45 days | One missed refresh must not null the feature |
The 30-day tolerance used in the examples is acceptable for a feature refreshed monthly. For avg_spend_30d refreshed daily it would be generous, and you would likely tighten it after looking at the age distribution.
Tolerance can differ per feature. A single global tolerance across a wide join is simple but wrong for features with different cadences. Join each feature group with its own tolerance, then combine the results.
Handling the nulls the tolerance creates
A tolerance converts "stale" into "missing", so you must decide how to treat missing values. Options include:
- Impute with a constant or statistic and add a missing indicator column, as
spend_missingdoes above. This is usually the best default, because the model can learn that "no recent data" is itself informative. - Use a model that handles missing values natively, such as gradient-boosted trees in many libraries.
- Drop the rows. Use this only after checking what you remove.
Serving must apply the same rule. If training imputes a missing value with the median plus an indicator, the online path must do exactly that when the TTL has expired. Chapter material on training-serving consistency returns to this point.
Common errors
- No tolerance at all. The join works and the metrics look fine, but the model trains on values of any age. This is the most common case, because the default of
merge_asofis no limit. - Tolerance in
WHERE. Described above. Row counts drop and nobody notices. - Different numbers in training and serving. Training uses 90 days, the online store uses 7. Offline metrics look better than online results because the model saw fresher-than-real coverage in some rows and staler values in others.
- Measuring age on the wrong clock. Age is computed from event time. If you apply the tolerance to ingestion time, a value ingested yesterday about an event two years ago passes. Late-arriving data needs its own filter on ingestion time, which a later chapter covers.
- Mixed time zones. A tolerance of 1 day compared across a naive and a UTC-aware column either raises or shifts by hours. Convert everything to UTC first.
- Ignoring the age distribution. Check
age_daysafter every build. A median age far above the feature's refresh interval means the pipeline has stalled somewhere, or the tolerance is hiding a broken feed.
A quick check you can add today
After the join, log three numbers: the missing rate per feature, the median and 95th percentile of age, and the row count before and after the join. A sudden jump in the missing rate usually means an upstream feature stopped updating. A row count that changes means the join duplicated or dropped labels. The next chapters turn these checks into assertions that fail the pipeline.
Exercise
A feature days_since_last_login is refreshed daily at 02:00 UTC. Your training join uses tolerance=pd.Timedelta("12H"), and 45% of training rows come back null for it. What is wrong, and what tolerance would you choose instead?
Show answer
The tolerance is shorter than the 24-hour refresh interval. A label row at 01:00 UTC has a latest value that is about 23 hours old, so it is rejected even though that value is the freshest the system could have had. Choose a tolerance of at least the refresh interval plus normal delay, for example 2 days, and set the online TTL to the same value so serving behaves the same way.
Exercise
Your SQL as-of join has AND f.event_ts >= l.prediction_ts - INTERVAL '30 days' moved from the ON clause into the WHERE clause. The query still runs. What changes in the output?
Show answer
Label rows with no feature row inside the 30-day window now have null f.event_ts, and the comparison with null is not true, so the WHERE clause removes them. The output has fewer rows than the label table, and the removed rows are the customers with no recent data, which biases the training set. Keep the condition in the ON clause so every label row survives.