Sub topic 4
Why training and serving features drift apart
This chapter explains training-serving skew: what it is, where it comes from, and how Databricks feature tables and logged feature lookups reduce it. It assumes you can read PySpark DataFrame code, know the basic train, evaluate, and infer workflow, and have seen Unity Catalog's catalog.schema.table naming. Later chapters build the feature tables and lookups in detail. Here the goal is to understand the problem they solve.
What training-serving skew is
Training-serving skew is a difference between the feature values a model saw during training and the feature values it receives when it makes predictions. The model code is identical in both places. The inputs are not.
The model learns a mapping from feature values to labels. If a feature means something slightly different in production, the mapping no longer applies. The model does not raise an error. It returns predictions that are quietly worse, which is why skew is hard to notice.
A related term is drift. Skew compares training data with serving data at one point in time. Drift describes how data changes over time, for example when customer behavior shifts. The chapter title uses "drift apart" loosely. The causes below are mostly about skew, and the fixes target it.
Where skew comes from
Most skew comes from a few repeating causes.
| Cause | What happens | Example |
|---|---|---|
| Duplicated logic | Training and serving compute the same feature in two code paths that diverge | A data scientist writes a 90-day average in PySpark. An engineer reimplements it in Java for the application. |
| Different windows or definitions | The two paths disagree on boundaries | One path uses `>= date_sub(current_date(), 90)`. The other uses `> now() - 90 days`. |
| Different preprocessing | Encoding, scaling, or null handling differs | Training fills missing amounts with the median. Serving fills them with 0. |
| Stale features | Serving reads values computed long ago | The model expects a 90-day count but receives last month's count. |
| Label leakage | Training features include information from after the event | A feature table is joined on the latest values, not the values at the time of the label. |
| Schema or type changes | A column changes type or meaning | `amount` switches from dollars to cents. |
The first cause is the most common. Any time the same feature is written twice, the two copies will eventually disagree.
A concrete example
Suppose a churn model uses order_count_90d. In training, you compute it with Spark:
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
user_features_df = (
orders
.filter(F.col("order_ts") >= F.date_sub(F.current_date(), 90))
.groupBy("user_id")
.agg(
F.count("*").alias("order_count_90d"),
F.avg("amount").alias("avg_order_amount_90d"),
F.max("order_ts").alias("last_order_ts"),
)
)In production, a service needs the same number for one user at request time. A common shortcut is to write a separate query against an application database. That query might count cancelled orders, which the Spark job excluded upstream. It might use a 3-month window instead of 90 days. It might return no row for new users, so the application substitutes 0, while training dropped those users entirely.
Each difference looks small. Together they shift the input distribution. A model that learned from "typical" counts of 4 to 6 now sees 7 to 9 for the same users.
Three kinds of mismatch to check for
Logic mismatch
The formulas differ. This is the duplicated-code case above. You find it by comparing the feature definitions side by side, or by computing the feature both ways for the same entity and comparing the numbers.
Timing mismatch
The values come from different moments. Training data is historical, so each row should hold feature values as they were when the label event occurred. If you instead join today's feature values to old labels, the model trains on information from the future. Offline metrics look excellent, and production results fall short. This is label leakage, and the point-in-time chapter covers the fix.
A second timing problem is staleness. If a feature table refreshes nightly but the model assumes up-to-date values, serving values lag behind what training assumed.
Data mismatch
The inputs differ in shape: types, units, null rates, or category values. A category seen only in production, such as a new product type, may be encoded differently or fail. The encoding chapter covers handling unseen categories and missing values.
How feature tables reduce skew
A Databricks feature table in Unity Catalog is a Delta table with a primary key. The idea behind it is simple: compute the feature once, store it in one governed place, and have both training and serving read from that place.
You create the table from the DataFrame above:
from databricks.feature_engineering import FeatureEngineeringClient
fe = FeatureEngineeringClient()
fe.create_table(
name="main.ml.user_features",
primary_keys=["user_id"],
df=user_features_df,
description="Per-user order features over the last 90 days",
)
# Later runs update existing rows and insert new ones.
fe.write_table(
name="main.ml.user_features",
df=user_features_df,
mode="merge",
)The feature logic now lives in one pipeline. Anyone who needs order_count_90d reads the stored column and does not recompute it.
Lookups travel with the model
The second mechanism is more important. When you build a training set, you declare which features to read and which key to use:
from databricks.feature_engineering import FeatureEngineeringClient, FeatureLookup
fe = FeatureEngineeringClient()
labels_df = spark.table("main.ml.churn_labels") # user_id, label
feature_lookups = [
FeatureLookup(
table_name="main.ml.user_features",
feature_names=["order_count_90d", "avg_order_amount_90d"],
lookup_key="user_id",
)
]
training_set = fe.create_training_set(
df=labels_df,
feature_lookups=feature_lookups,
label="label",
exclude_columns=["user_id"],
)
training_df = training_set.load_df()Then you log the model with that training set:
import mlflow
from sklearn.ensemble import RandomForestClassifier
train_pdf = training_df.toPandas()
X = train_pdf.drop(columns=["label"])
y = train_pdf["label"]
model = RandomForestClassifier(n_estimators=100, random_state=42).fit(X, y)
mlflow.set_registry_uri("databricks-uc")
fe.log_model(
model=model,
artifact_path="model",
flavor=mlflow.sklearn,
training_set=training_set,
registered_model_name="main.ml.churn_model",
)fe.log_model stores the lookup metadata inside the model artifact. At inference time, the model knows which table, columns, and key to use. Scoring then needs only the key:
# The input needs only the lookup key. Features are retrieved from the feature table.
batch_df = spark.table("main.ml.users_to_score").select("user_id")
predictions = fe.score_batch(
model_uri="models:/main.ml.churn_model/1",
df=batch_df,
)The caller cannot pass a different definition of order_count_90d, because the caller does not supply it. This removes the duplicated-logic cause, which is the largest source of skew.
What feature tables do not fix
Feature tables narrow the problem but do not remove it. Watch for these gaps.
- Preprocessing outside the model. If you scale or encode columns in a notebook before fitting and do not package those steps with the model, serving receives unscaled inputs. Put preprocessing inside the logged model, for example in a scikit-learn
Pipeline, or store the transformed values as features. - Stale tables. A lookup returns whatever the table holds. If the pipeline stops refreshing, the model reads old values without any error. Schedule the pipeline and monitor freshness.
- Missing keys. A user absent from the feature table gets null feature values. Decide how the model should treat nulls, and check that the scored keys exist.
- Changed feature definitions. If you rewrite how
order_count_90dis computed and merge the new values, models trained on the old definition now see different inputs. Prefer adding a new column, such asorder_count_90d_v2, and retrain. - Online and offline copies. Online serving uses a separate low-latency store synchronized from the table. Sync delay creates a gap between the two.
Detecting skew you already have
Prevention is better, but you should also measure. A practical approach:
- Log the feature values your model receives at serving time, for example in an inference table.
- Compute summary statistics per feature, such as mean, null rate, and distinct count, on both training data and logged serving data.
- Compare them and flag features whose statistics differ beyond a threshold.
A simple check in PySpark:
from pyspark.sql import functions as F
def feature_stats(df, col):
return df.agg(
F.avg(col).alias("mean"),
F.stddev(col).alias("std"),
F.avg(F.col(col).isNull().cast("int")).alias("null_rate"),
).first()
train_stats = feature_stats(training_df, "order_count_90d")
print(train_stats)Run the same function on the serving log and compare the two results. A large gap in the mean or null rate points to a logic, timing, or data mismatch.
Exercise
A churn model was trained on order_count_90d from a feature table. In production, the application team computes order_count_90d with their own SQL and passes it to the model as an input. Offline accuracy was 0.91, but production results are much worse. Name the cause of the problem and describe how to fix it using feature lookups.
Show answer
The cause is training-serving skew from duplicated feature logic: the application's SQL likely differs from the Spark definition in window, filters, or null handling. To fix it, log the model with fe.log_model and the training set built from a FeatureLookup on main.ml.user_features. Then score with fe.score_batch, or serve the model online, passing only user_id. The model retrieves order_count_90d from the feature table, so both training and inference use the same stored values.
Exercise
You join the current values of a feature table to a year of historical labels and get excellent offline metrics that do not hold up after deployment. Which type of mismatch is this, and which feature of the feature table helps?
Show answer
It is a timing mismatch that causes label leakage. Each historical label is paired with feature values computed after the event. Declaring a time series column on the feature table and using a timestamp_lookup_key in the FeatureLookup performs a point-in-time lookup, so each label gets the feature values as of its own timestamp.