Sub topic 17
Design and operating practices for feature tables
This chapter assumes you can create a feature table, merge data into it, build a training set, and log a model with fe.log_model. It collects the decisions that keep those pieces reliable once several teams and models depend on them.
Design features for reuse
A feature table is shared infrastructure. Design it so that a second team can use it without reading your notebook.
- One entity per table. Key a table by one entity, such as
user_idorproduct_id. A table that mixes user and product columns forces awkward keys and wasteful lookups. - Group features by refresh cadence. Features that update hourly and features that update monthly should live in separate tables. Otherwise the whole table must refresh at the fastest rate, or the slow features go stale unnoticed.
- Name by meaning and window.
order_count_90dstates the quantity and the window.count2states neither. Put the unit and window in the name because the name is what lookups and models store. - Keep tables narrow in purpose. A table of 400 loosely related columns is hard to document, hard to govern, and expensive to rewrite.
- Store raw-ish values, not model-specific transforms. Store
avg_order_amount_90d, not a version scaled to one model's training statistics. Scaling parameters belong to a model, so keep them inside the model pipeline.
Keep encoding and missing-value rules consistent
Many cases of training-serving skew come from a transformation applied in one place and not the other. Two rules help:
- Compute deterministic, model-independent transformations (aggregates, flags, buckets with fixed edges) once, in the feature pipeline. Every consumer then gets the same values.
- Fit anything learned from data (scalers, target encoders, category vocabularies) inside the model pipeline and log it with the model. Then batch scoring and serving apply the same fitted object.
Decide how missing values are represented and document it. A user with no orders in 90 days has no row in the aggregation shown earlier, so a lookup returns null. Writing an explicit zero count in the pipeline, instead of leaving it to each model, makes the meaning the same everywhere.
from pyspark.sql import functions as F
users = spark.table("main.sales.users").select("user_id")
# Every user gets a row. Users with no recent orders get an explicit 0 count.
complete_features_df = (
users
.join(user_features_df, on="user_id", how="left")
.withColumn("order_count_90d", F.coalesce("order_count_90d", F.lit(0)))
.withColumn("computed_at", F.current_timestamp())
)Leave avg_order_amount_90d null here. A zero average would claim that orders happened with zero value. Null says no data, and the model's imputer can handle it consistently.
Protect against label leakage
If a feature changes over time, a plain key lookup attaches today's value to a past label. The model then sees information from after the event.
- Use a time series column and
timestamp_lookup_keyfor any feature that changes after the event it describes. - Check the timestamp semantics. The feature timestamp must mean when the value became available, not when the period it describes began. A "weekly total" stamped at the start of the week leaks the future.
- Use plain lookups only for slowly changing attributes where leakage is not a concern, and say so in the table description.
Make writes safe to repeat
Scheduled pipelines fail, retry, and overlap. Design each write so a rerun produces the same table.
- Use
mode="merge"for incremental refreshes. Rerunning the same input updates the same rows instead of duplicating them. - Deduplicate the source on the primary key before merging. Two source rows with the same key make a merge ambiguous and can fail the job.
- Use overwrite only when you intend to replace the whole table, such as a full backfill. Overwriting a table that other models read changes their inputs immediately.
- Add a
computed_atcolumn so you can tell how old each row is.
from pyspark.sql import Window, functions as F
latest = Window.partitionBy("user_id").orderBy(F.col("computed_at").desc())
deduped_df = (
complete_features_df
.withColumn("rn", F.row_number().over(latest))
.filter("rn = 1")
.drop("rn")
)
fe.write_table(
name="main.ml.user_features",
df=deduped_df,
mode="merge",
)Monitor freshness
A feature table can be correct and still harmful if it stopped updating three weeks ago. Treat freshness as a service-level target. Choose a maximum age for each table, such as 26 hours for a daily job, and fail loudly when it is exceeded.
from datetime import datetime, timedelta, timezone
from pyspark.sql import functions as F
MAX_AGE = timedelta(hours=26)
newest = (
spark.table("main.ml.user_features")
.agg(F.max("computed_at").alias("newest"))
.collect()[0]["newest"]
)
# Spark returns a naive timestamp in the session time zone; compare in UTC.
newest_utc = newest.replace(tzinfo=timezone.utc)
age = datetime.now(timezone.utc) - newest_utc
if age > MAX_AGE:
raise RuntimeError(f"user_features is stale: newest row is {age} old")Run this check as a task after the refresh task in the same job. A failed check then triggers the same alerting as a failed refresh. If your cluster's session time zone is not UTC, adjust the conversion, or compute the age in SQL with current_timestamp().
Govern access and make features discoverable
Feature tables are Unity Catalog tables, so ordinary grants apply. Give readers the least they need, and keep write access with the pipeline's service principal.
GRANT USE CATALOG ON CATALOG main TO `data-scientists`;
GRANT USE SCHEMA ON SCHEMA main.ml TO `data-scientists`;
GRANT SELECT ON TABLE main.ml.user_features TO `data-scientists`;
GRANT MODIFY ON TABLE main.ml.user_features TO `feature-pipeline-sp`;Documentation is part of the design. Descriptions appear in Catalog Explorer, and lineage shows which models and notebooks consume a table.
COMMENT ON TABLE main.ml.user_features IS
'Per-user order features over the last 90 days. Refreshed daily by job user-features-daily. Owner: growth-ml.';
ALTER TABLE main.ml.user_features
ALTER COLUMN order_count_90d COMMENT 'Orders placed in the 90 days before computed_at. 0 if none.';
ALTER TABLE main.ml.user_features
SET TAGS ('owner_team' = 'growth-ml', 'refresh' = 'daily');Check lineage before you change a table. If a model depends on a column, dropping or renaming it breaks that model's scoring.
Change tables without breaking models
Models log their feature lookups by table and column name. That makes changes to a shared table risky.
| Change | Risk | Safer approach |
|---|---|---|
| Add a column | Low | Add it. Existing lookups ignore it. |
| Change a column's definition | High. Old models silently receive new meanings | Add a new column such as `order_count_90d_v2` and migrate models |
| Rename or drop a column | High. Scoring fails | Keep the old column until lineage shows no consumers |
| Change the primary key | High | Create a new table and migrate |
| Backfill with overwrite | Medium. Values change under live models | Write to a new table, validate, then switch |
Operating checklist
- Each table has an owner, a description, and a refresh schedule recorded in tags or comments.
- Refresh writes are idempotent and deduplicated on the primary key.
- Time-dependent features use a time series column and a timestamp lookup.
- A freshness check runs after each refresh and fails the job when data is too old.
- Readers hold
SELECT. Only the pipeline identity holdsMODIFY. - Column changes follow the table above, and lineage is checked first.
Exercise
A daily job merges into main.ml.user_features. Last night the job failed after the merge step but before the freshness check, and the orchestrator retried it. Why is the retry safe, and what could still go wrong that the freshness check would catch?
Show answer
The retry is safe because the write is a merge on the primary key after deduplication. Running it twice updates the same rows and creates no duplicates. What could still go wrong is a silent failure upstream, such as the source table not updating, so the merge succeeds but writes unchanged data. The freshness check reads the newest computedat and fails if it is older than the limit, so it catches a pipeline that runs but produces stale data. Note that computedat must reflect when the feature values were computed from fresh source data. If the pipeline stamps current_timestamp() on stale source data, the check will not detect the problem, so also monitor the source table's latest timestamp.