Sub topic 12
Keeping training and serving computations consistent
This chapter assumes you can build an as-of join, you know what a feature history table is, and you have read the chapters on windowed aggregates and training-set assembly. You should be comfortable with pandas and SQL window functions.
Why consistency is a separate problem
A point-in-time correct training set can still fail in production. The training set may be right about which rows were visible. The model may still see different numbers at serving time than it saw during training. This gap is called training-serving skew.
Skew has a different cause from temporal leakage. Leakage means the training data contained information from the future. Skew means the training pipeline and the serving pipeline compute the "same" feature in different ways. Either one lowers production accuracy while offline metrics stay high, so you need to rule out both.
Take the feature avg_spend_30d. In training, a data engineer writes a SQL query over a warehouse table. In serving, a backend engineer writes a function that reads from a key-value store. The two implementations may disagree on several details:
- Whether the 30-day window includes the prediction day.
- Whether refunds are subtracted.
- How a customer with no purchases is handled (null, zero, or a missing row).
- Which time zone defines "a day".
None of these disagreements raises an error. The model receives a number either way, and the number is slightly wrong.
Where skew comes from
Skew tends to come from a small number of sources. Knowing them lets you review a pipeline systematically.
| Source | Example | Typical symptom |
|---|---|---|
| Duplicated logic | SQL in training, Python in serving | Small numeric differences on every request |
| Different window boundaries | Training window is `[t-30d, t)`, serving window is `[t-30d, t]` | Differences only on rows with events at the boundary |
| Different null handling | Training fills with 0, serving passes NaN | Differences for new customers |
| Different freshness | Training joins the value as of `t`, serving reads a value refreshed once per day | Serving values are older than training values |
| Different data sources | Training reads the warehouse, serving reads an operational database | Systematic offsets after corrections or deduplication |
| Different preprocessing | Scaler fitted in a notebook, not shipped with the model | Distribution shift in model inputs |
The freshness row connects to earlier chapters. An as-of join with a small tolerance assumes the value at time t was the latest one. If serving refreshes the feature only nightly, then at serving time the value is on average half a day old. The model was trained on fresher values than it will ever get. You fix this by choosing training-time tolerance and TTL to match what serving can actually deliver, not what the history table could in theory provide.
A single definition, two execution paths
The most reliable fix is to define each feature once and run that definition in both paths. How you do this depends on your stack, but the idea is constant: one source of truth for the computation, parameterized by "as of when".
The sketch below defines a feature as a pure Python function of an event table and a reference time. Training calls it for many reference times. Serving calls it once for the current time.
import pandas as pd
def avg_spend_30d(events: pd.DataFrame, customer_id: str, as_of: pd.Timestamp) -> float:
"""Average order amount in the 30 days before `as_of`, excluding `as_of` itself.
events columns: customer_id, event_ts, amount
Returns 0.0 when the customer has no orders in the window.
"""
start = as_of - pd.Timedelta("30D")
window = events[
(events["customer_id"] == customer_id)
& (events["event_ts"] >= start)
& (events["event_ts"] < as_of)
]
if window.empty:
return 0.0
return float(window["amount"].mean())
events = pd.DataFrame(
{
"customer_id": ["a", "a", "a"],
"event_ts": pd.to_datetime(["2026-01-02", "2026-01-10", "2026-02-20"]),
"amount": [10.0, 30.0, 100.0],
}
)
# Training path: one call per label row, with the label's prediction time.
print(avg_spend_30d(events, "a", pd.Timestamp("2026-01-15"))) # 20.0
# Serving path: the same function, called with the request time.
print(avg_spend_30d(events, "a", pd.Timestamp("2026-02-21"))) # 100.0The window is half-open: it includes start and excludes as_of. The empty-window case returns 0.0 inside the function, so no caller has to remember it. Both paths share these decisions because they share the code.
Calling a Python function per label row does not scale to hundreds of millions of rows. For large training sets you need a vectorized or SQL version. That brings back the duplication problem, which the next section addresses.
When you cannot share code
Sometimes training runs in a warehouse and serving runs in a low-latency service, so one implementation cannot serve both. In that case, treat the two implementations as a pair that must be tested against each other.
The approach is a parity test:
- Pick a sample of recent (customer, timestamp) pairs.
- Compute the feature with the training implementation as of each timestamp.
- Compute it with the serving implementation as of the same timestamp, using the same underlying events.
- Compare the results and fail when they differ beyond a small tolerance.
import numpy as np
import pandas as pd
def check_parity(train_values: pd.Series, serve_values: pd.Series, rtol: float = 1e-6) -> None:
"""Fail if two aligned feature series disagree.
Both series must share the same index (for example a MultiIndex of
customer_id and prediction_ts).
"""
assert train_values.index.equals(serve_values.index), "indexes differ"
both_null = train_values.isna() & serve_values.isna()
one_null = train_values.isna() ^ serve_values.isna()
assert not one_null.any(), f"{int(one_null.sum())} rows are null in only one path"
comparable = ~both_null
close = np.isclose(
train_values[comparable].to_numpy(dtype=float),
serve_values[comparable].to_numpy(dtype=float),
rtol=rtol,
)
assert close.all(), f"{int((~close).sum())} rows differ beyond rtol={rtol}"
idx = pd.MultiIndex.from_tuples(
[("a", "2026-01-15"), ("b", "2026-01-15")], names=["customer_id", "prediction_ts"]
)
train_vals = pd.Series([20.0, np.nan], index=idx)
serve_vals = pd.Series([20.0, np.nan], index=idx)
check_parity(train_vals, serve_vals)
print("parity ok")The null check runs before the numeric comparison. A value that is null in one path and 0.0 in the other is a common bug, and a plain numeric comparison would hide it or crash on it.
Run the parity test in continuous integration whenever either implementation changes, and on a schedule against fresh data. Schedules catch drift in the underlying sources, which code review cannot.
Logging served features
The strongest consistency guarantee is to stop recomputing features for training. Instead, log the exact feature values the model received at serving time, together with the request timestamp and an identifier for the entity. Later, join those logs to labels once the outcomes are known.
This approach has clear benefits:
- Training data matches what the model saw, by construction.
- Leakage is impossible for the logged features, because they were computed at request time.
- Late-arriving corrections do not rewrite what the model actually saw.
It also has costs:
- You can only train on traffic the model already served. A new feature has no history until you start logging it.
- The logs reflect the old model's traffic. If the old model's decisions shaped who was shown what, the logged population is biased.
- Storage grows with request volume.
Most teams combine the two. They backfill a new feature with an as-of join to get a first training set, then switch to logged features as history accumulates. When they do this, they compare the backfilled values to the logged values for the overlapping period. The difference between the two is a direct measurement of skew.
Measuring skew in production
Parity tests check code. Monitoring checks reality. Once the model is live, compare the distribution of each feature at serving time with its distribution in the training set.
Useful signals include:
- The null rate per feature, in training versus serving.
- The mean, standard deviation, and quantiles per feature.
- A distance measure between the two distributions, such as the population stability index or the Kolmogorov-Smirnov statistic.
A distribution difference does not prove skew. Real-world behavior changes too, which is drift. To separate them, use the logged-feature comparison above: if recomputing the feature offline for a served request reproduces the logged value, the pipeline is consistent and any remaining difference is drift. If the recomputed value differs, you have skew.
Common errors
- Fixing leakage and stopping. Passing the leakage tests from the previous chapter says nothing about whether serving computes the feature the same way.
- Training with fresher data than serving can deliver. Set the as-of join tolerance to match the serving refresh interval, or simulate the lag by joining against
feature_ts <= prediction_ts - refresh_lag. - Fitting preprocessing on the full dataset. Scalers, encoders, and imputers fitted on validation or future data leak information. Fit them on the training period only, then ship the fitted objects with the model so serving applies the same transformation.
- Using different time zones. Store timestamps in UTC and convert only for display. A "day" boundary in a local time zone differs from one in UTC, and daylight saving shifts it twice a year.
- Comparing floating-point values for exact equality. Use a relative tolerance, as in the parity test above.
How the pieces fit
The diagram shows the two paths and the points where you can attach checks.
Exercises
Exercise
A feature orders_7d is computed in training with a window [t - 7 days, t] (inclusive of t) and in serving with [t - 7 days, t). Offline AUC is 0.91 and production AUC is 0.84. The leakage tests pass. Name the likely cause, say which rows are affected, and give two ways to fix it.
Show answer
The cause is training-serving skew from different window boundaries. Only rows where an order has a timestamp exactly equal to the prediction time are affected, and in training those orders are counted while in serving they are not. Because the training window includes an event at the prediction time, it can also be a form of leakage that a feature_ts <= prediction_ts test does not catch. Fix it by (1) defining the window once, half-open as [t - 7 days, t), in a shared function used by both paths, or (2) keeping two implementations but adding a parity test that includes boundary cases, then changing the training query to event_ts < prediction_ts.
Exercise
Your serving system refreshes avg_spend_30d once per day at 02:00 UTC. A request arrives at 17:00 UTC. Training joins the latest value at or before the prediction time. What difference will the model see, and how can you change the training join to reflect serving?
Show answer
At 17:00 serving returns the value computed at 02:00, which is 15 hours old. Training would join a value computed at or just before 17:00, so it sees fresher values than serving. To match, make the training join use the value that serving would have returned: join as of the most recent 02:00 refresh before the prediction time (for example, floor the prediction time to the refresh schedule), or subtract the refresh interval and use a tolerance that matches it. Better still, log served values and compare them to the training values for the same requests.
Exercise
Why does check_parity test for one-sided nulls before comparing numbers?
Show answer
A value that is null in one path and a number in the other is a real disagreement, for example NaN in serving and 0.0 in training for a new customer. A numeric comparison either raises an error on NaN or treats NaN comparisons as false in a way that hides which rows differ. Checking null patterns first reports the exact count of rows where one path is null and the other is not, and leaves only rows where both have values for the numeric comparison.