Sub topic 7
Avoiding training-serving skew
Training-serving skew happens when the features a model sees in production differ from the features it saw during training. The model code is unchanged and nothing crashes, but the predictions get worse. This chapter explains how skew arises, how batch and real-time serving each invite it, and how to prevent and detect it.
It assumes you can read Python and pandas, know what a feature and a trained model are, and have read the earlier chapters on batch prediction, real-time prediction, and where features come from at prediction time.
What skew is
A model learns a mapping from feature values to outcomes. If a feature means one thing in training and another in serving, the learned mapping no longer applies. Common examples are a column in different units, a missing value filled with a different default, or a count over a different time window.
Skew is not the same as drift. Drift means the real world changed after training, so the same features now describe different behavior. Skew means the pipeline produced different numbers for the same behavior. Skew is a bug you can fix. Drift calls for retraining.
Skew is hard to notice because the service keeps returning plausible scores. Usually only a drop in business metrics reveals it.
Where skew comes from
| Cause | Example | Typical symptom |
|---|---|---|
| Duplicated logic | Training code in a notebook, serving code rewritten in another service | Small numeric differences in every row |
| Different defaults | Training fills missing tickets with 0, the service sends -1 or null | Odd scores for new or sparse records |
| Different data sources | Training reads a warehouse table, serving reads a live database with other cleaning rules | Differences for some columns only |
| Time leakage | Training features include events that happened after the label date | Great offline metrics, poor production results |
| Stale lookups | A feature table refreshes nightly but training assumed hourly values | Scores lag behind customer behavior |
| Library or schema changes | A new version changes rounding, encoding, or category order | A sudden shift after a deployment |
Time leakage is the least obvious cause. When you build a training set, each row's features must be computed as they would have looked at the moment of prediction. If you compute "support tickets in the last 90 days" using today's data for a row labeled six months ago, the feature includes tickets the model could not have known about at the time. This is called point-in-time correctness, and the offline training set must respect it.
How batch and real-time serving differ in skew risk
Batch scoring usually reads from the same warehouse that produced the training data. It often reuses the same SQL or dataframe code, so the risk is lower. Its typical failures are stale feature tables and time windows that shift because the job ran late.
Real-time serving usually needs features from an online store or from the request itself. The training code was written against a warehouse, so the service often gets a second implementation. This duplication makes real-time serving the most common source of skew. The hybrid pattern adds a further risk. A precomputed batch score and a live fallback score come from two code paths, so the same customer can get slightly different scores depending on which path answered.
The main defense: one definition of each feature
The most reliable fix is to write feature logic once and call it from training, batch scoring, and the online service. The module below takes raw columns and produces model-ready features.
# features.py
import pandas as pd
FEATURE_COLUMNS = ["tenure_months", "monthly_spend", "support_tickets"]
def build_features(raw: pd.DataFrame) -> pd.DataFrame:
"""Turn raw customer columns into model features.
Used unchanged by training, batch scoring, and the online service.
"""
out = pd.DataFrame(index=raw.index)
out["tenure_months"] = raw["tenure_days"] / 30.0
out["monthly_spend"] = raw["total_spend_90d"] / 3.0
out["support_tickets"] = raw["support_tickets"].fillna(0).astype(int)
return out[FEATURE_COLUMNS]The training script calls build_features(train_raw) before fitting. The batch job calls it on the whole table. The online service calls it on a one-row dataframe built from the request:
import pandas as pd
from features import build_features
payload = {"tenure_days": 450, "total_spend_90d": 210.0, "support_tickets": None}
row = build_features(pd.DataFrame([payload]))
print(row.to_dict(orient="records"))This prints [{'tenure_months': 15.0, 'monthly_spend': 70.0, 'support_tickets': 0}]. The missing ticket count becomes 0 exactly as it did in training. Without the shared function, a service author might have written payload["support_tickets"] or -1, and the model would receive a value it never saw during training.
Sharing code has limits. If the batch job runs in Spark and the service runs in a small Python container, one module may not run in both places. In that case you have three options:
- Package the logic as a library and run the same code in both environments, even if it is slower in one.
- Use a feature store that computes each feature once and serves it both offline for training and online for serving.
- Keep two implementations, but add automated tests that run both on the same inputs and compare the outputs.
The third option is the weakest, but it is better than leaving the duplicates untested.
Version the model and the features together
A model file is only valid with the feature logic it was trained on. If you change how monthly_spend is computed, every model trained earlier now receives different inputs. Store a feature version, or the git commit of the feature code, alongside the model artifact. Have the service refuse to start or log a warning if the two do not match.
Also keep the exact feature order inside the artifact or the code. Scikit-learn models trained on arrays use column position, not names. The service in the earlier example builds a plain list in a fixed order, so reordering the fields silently swaps the meaning of two features. Passing a dataframe with named columns and using FEATURE_COLUMNS for ordering removes this risk.
Detecting skew in production
Prevention is not enough. You also need to look for skew after deployment. The usual approach has three steps:
- Log the feature values the service actually used for each prediction, or a sample of them.
- Keep summary statistics of each feature from the training set.
- Compare the two on a schedule and alert when they diverge.
A common comparison is the population stability index (PSI). It splits the training values into bins, then measures how much the share of serving values per bin differs.
import numpy as np
def psi(expected, actual, bins=10):
"""Population stability index between training and serving values."""
expected = np.asarray(expected, dtype=float)
actual = np.asarray(actual, dtype=float)
edges = np.quantile(expected, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf
e = np.histogram(expected, edges)[0] / len(expected)
a = np.histogram(actual, edges)[0] / len(actual)
e = np.clip(e, 1e-6, None)
a = np.clip(a, 1e-6, None)
return float(np.sum((a - e) * np.log(a / e)))
rng = np.random.default_rng(0)
train_spend = rng.normal(70, 15, 5000)
healthy_spend = rng.normal(70, 15, 1000)
skewed_spend = rng.normal(70, 15, 1000) / 3.0 # divided by 3 twice by mistake
print("healthy:", round(psi(train_spend, healthy_spend), 3))
print("skewed: ", round(psi(train_spend, skewed_spend), 3))The healthy comparison prints a value near 0. The skewed one prints a value far above 1. A common rule of thumb treats PSI under 0.1 as stable, 0.1 to 0.25 as worth a look, and above 0.25 as a likely problem. These cutoffs are conventions, not guarantees, so tune them on your own data.
A second check is to replay. Take a sample of recent real requests, compute their features through the online path, and compare them with the features the batch or training path produces for the same records. Any difference larger than floating-point rounding points to a real bug, and it is easier to diagnose than a distribution shift.
A practical checklist
- Define each feature in one place and call it from every path.
- Compute training features as of the prediction time, not as of today.
- Use the same defaults, units, encodings, and category lists everywhere.
- Store the feature version with the model and check it at startup.
- Use named columns and a fixed column list instead of positional lists.
- Log served features and compare their distributions with training.
- Add a test that runs the online and batch paths on the same sample and checks the outputs match.
- In hybrid systems, test that the precomputed and live scores agree for the same customer.
Exercises
Exercise
A fraud model scores well offline but performs badly in production. The online service computes "transactions in the last 24 hours" from a live database. The training set computed the same feature from a daily warehouse snapshot taken at midnight and joined to each transaction by date. Name two possible sources of skew here and one fix for each.
Show answer
First, the time window differs. The snapshot count for a transaction at 3 pm includes only activity up to midnight of the previous day, or even later activity depending on the join, while the live count covers the exact last 24 hours. Fix it by rebuilding the training set with point-in-time joins that compute the count as of each transaction's timestamp. Second, the data sources differ, so cleaning rules, late-arriving events, or duplicates may be handled differently. Fix it by computing the feature with one shared definition, or from one feature store, for both training and serving. Time leakage in the warehouse join is also a valid answer.
Exercise
A service receives a request where support_tickets is null. In build_features the null becomes 0. A teammate proposes handling nulls in the API layer instead, by rejecting the request with an error. Does this remove the skew risk? Explain.
Show answer
Not entirely. Rejecting nulls avoids sending a wrong value, but the training data contained nulls that were filled with 0, so the model expects that case to exist, and rejecting it makes the service fail on inputs the model could handle. It also creates a second place where missing values are handled, which is the duplication that causes skew. It is safer to keep the null handling inside the shared feature function and, if needed, log how often it happens.