A feature is a value a model reads: "orders this customer placed in the last 7 days". A feature store computes it once and serves it twice: from an offline store (a warehouse or lake) for training, with correct values for every past moment, and from an online store (a key-value database such as Redis) for prediction, in milliseconds. When the two disagree, the model meets different numbers in production than it learned from, and accuracy drops with no error anywhere. That is training-serving skew. This lesson follows one feature from its definition to a prediction, and shows the two classic leaks: a feature computed twice in two languages, and a training join that peeks into the future.
Difficulty: Advanced · Know this first: Lesson 329, Lesson 198
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from a new feature definition to a prediction that uses it. It is a worked example, not a measurement. The point-in-time join and the request hops are where skew and leakage hide.
Pick how the training set is joined and where serving gets its features. Leakage makes offline scores look better than production; skew makes production worse than offline.
Consistent
Three questions. No score is saved anywhere — this is just you against the material.
Feature stores grow in four levels: reading features, defining and serving them, proving consistency, and running a feature platform.
At the basic level you can find a feature, read its definition, and look up its value now and in the past.
Where it breaks: treating the online store as the source of truth; it only has the latest values.
Try it: Basic
You need the value of orders_7d for customer 42 as it was last Tuesday at 14:03. Where do you look?
Now do it: Run an as-of query for one entity in your offline store.
At the intermediate level you add features without creating skew.
get_historical_features).get_online_features; request-time features through one shared library.Try it: Intermediate
The service team wants to compute a feature itself to save 3 ms. What do you say?
Now do it: Find one feature computed in two places in your systems.
At the advanced level consistency is measured, not assumed.
Try it: Advanced
How do you detect training-serving skew automatically?
Now do it: Write the skew query for one feature.
At the master level features are shared products with owners, SLOs, and lineage.
Trade-off: a shared store adds a platform to run and removes the most expensive class of silent model bugs.
Try it: Master
A source table will change its definition of "order". How do you find the affected models?
Now do it: Trace one source column to every model that depends on it.
A feature defined once in Feast, used for both training and serving. Check the current Feast documentation for exact parameters; the shape has been stable for several releases.
# features.py
from datetime import timedelta
from feast import Entity, FeatureView, Field, FileSource
from feast.types import Int64
customer = Entity(name="customer", join_keys=["customer_id"])
orders = FileSource(path="data/orders_7d.parquet", timestamp_field="event_timestamp")
orders_7d = FeatureView(
name="orders_7d", entities=[customer], ttl=timedelta(days=2),
schema=[Field(name="orders_7d", dtype=Int64)], source=orders, online=True,
)
# training: point-in-time correct values for each label row
training = store.get_historical_features(
entity_df=labels, # customer_id, event_timestamp, label
features=["orders_7d:orders_7d"]).to_df()
# serving: the latest value, from the online store
online = store.get_online_features(
features=["orders_7d:orders_7d"], entity_rows=[{"customer_id": 42}]).to_dict()
What a point-in-time join does, in SQL terms: for each label row, take the feature row with the greatest timestamp that is not after the label's timestamp.
SELECT l.*, f.orders_7d FROM labels l LEFT JOIN LATERAL ( SELECT orders_7d FROM orders_7d_history f WHERE f.customer_id = l.customer_id AND f.event_timestamp <= l.event_timestamp ORDER BY f.event_timestamp DESC LIMIT 1) f ON true;
Kinds of skew to look for: different code in two languages, different windows (rolling 7 days against calendar week), different defaults for missing values (0 against null), different time zones, stale online values past their TTL, and features read at different points in a request (before against after a basket update).
This is a composite of a failure pattern that keeps repeating; the details are illustrative. One feature, implemented twice.
orders_7d in their Java service from their own orders table. Their version counts the current calendar week.orders_7d matches 69% of the time; on Mondays almost never.Served feature vectors are sampled and logged with the model version, a daily skew job alerts below 99% match per feature, and any request-time feature must come from the shared feature library used in training.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A virtual environment for Python packages: python3 -m venv ~/mlops && . ~/mlops/bin/activate. Then pip install feast (it brings pandas and a local SQLite online store).
Type each one, read what it prints, and compare it with the note above it.
Create a local Feast project from its template.
mkdir -p ~/labs && cd ~/labs feast init feature_lab && cd feature_lab/feature_repo ls
Register the definitions: Feast reads the Python and writes its registry.
feast apply feast feature-views list
Copy the latest values into the online store (SQLite here; Redis or DynamoDB in production).
feast materialize-incremental "$(date -u +%Y-%m-%dT%H:%M:%S)"
Look at what the online store holds: tables of latest values, no history.
ls -la data/
python3 -c "import sqlite3,glob; c=sqlite3.connect(glob.glob('data/online*.db')[0]); print([r[0] for r in c.execute('select name from sqlite_master')])"feature_skew.pyThis program builds a training set two ways: with a point-in-time join (each label sees only orders before its own day) and with a leaky join (the feature counted at the end of the day, after the order it is meant to predict). Then it computes the same feature as training does (rolling 7 days) and as a rewritten service does (calendar week), and measures the skew between them. Save it as feature_skew.py, then run it.
# feature_skew.py
from datetime import date, timedelta
ORDER_DAYS = { # the days each customer ordered in November 2026
"c1": [2, 5, 9, 16, 17, 23], "c2": [3, 10, 18, 24], "c3": [1, 2, 20], "c4": [6, 13, 19],
}
ORDERS = [(c, date(2026, 11, d)) for c, days in ORDER_DAYS.items() for d in days]
def count(customer, start, end):
return sum(1 for c, d in ORDERS if c == customer and start <= d < end)
def orders_7d(customer, as_of):
"""Training's definition: orders in the 7 days before as_of; as_of itself is excluded."""
return count(customer, as_of - timedelta(days=7), as_of)
def leaky_orders_7d(customer, as_of):
"""The same count taken at the end of as_of's day, after any order that day happened."""
return count(customer, as_of - timedelta(days=7), as_of + timedelta(days=1))
def orders_this_week(customer, as_of):
"""The rewritten service: orders since Monday of as_of's week."""
return count(customer, as_of - timedelta(days=as_of.weekday()), as_of)
# label: did this customer order on this day? (what the model predicts)
labels = []
for c in ORDER_DAYS:
for day in range(15, 25):
d = date(2026, 11, day)
labels.append((c, d, int(d in [x for cc, x in ORDERS if cc == c])))
for name, feature in (("point-in-time", orders_7d), ("leaky", leaky_orders_7d)):
pos = [feature(c, d) for c, d, y in labels if y == 1]
neg = [feature(c, d) for c, d, y in labels if y == 0]
rule = sum(1 for c, d, y in labels if (feature(c, d) > orders_7d(c, d)) == bool(y))
print(f"{name:<14} mean feature: ordered {sum(pos) / len(pos):.2f}, did not {sum(neg) / len(neg):.2f};"
f" 'feature went up today' predicts the label {rule}/{len(labels)}")
print()
print("serving each day of one week: training's feature / the rewrite")
match = total = 0
for offset in range(7):
day = date(2026, 11, 23) + timedelta(days=offset)
cells = []
for c in ORDER_DAYS:
a, b = orders_7d(c, day), orders_this_week(c, day)
match += a == b
total += 1
cells.append(f"{c} {a}/{b}")
print(f" {day:%a %d} " + " ".join(cells))
print(f"match rate {match}/{total} = {match / total:.0%} (alert below 99%)")
Run it, and you should see this output:
$ python3 feature_skew.py point-in-time mean feature: ordered 0.86, did not 1.06; 'feature went up today' predicts the label 33/40 leaky mean feature: ordered 1.86, did not 1.06; 'feature went up today' predicts the label 40/40 serving each day of one week: training's feature / the rewrite Mon 23 c1 2/0 c2 1/0 c3 1/0 c4 1/0 Tue 24 c1 2/1 c2 1/0 c3 1/0 c4 1/0 Wed 25 c1 1/1 c2 2/1 c3 1/0 c4 1/0 Thu 26 c1 1/1 c2 1/1 c3 1/0 c4 1/0 Fri 27 c1 1/1 c2 1/1 c3 1/0 c4 0/0 Sat 28 c1 1/1 c2 1/1 c3 0/0 c4 0/0 Sun 29 c1 1/1 c2 1/1 c3 0/0 c4 0/0 match rate 14/28 = 50% (alert below 99%)
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/feature-stores-and-lineage && cd ~/labs/feature-stores-and-lineage) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Feature Stores, Online/Offline Consistency, and Lineage", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Create a local Feast project from its template.'
'Register the definitions: Feast reads the Python and writes its registry.'
'Copy the latest values into the online store (SQLite here; Redis or DynamoDB in production).'
'Look at what the online store holds: tables of latest values, no history.'
)
step_1() {
mkdir -p ~/labs && cd ~/labs
feast init feature_lab && cd feature_lab/feature_repo
ls
}
step_2() {
feast apply
feast feature-views list
}
step_3() {
feast materialize-incremental "$(date -u +%Y-%m-%dT%H:%M:%S)"
}
step_4() {
ls -la data/
python3 -c "import sqlite3,glob; c=sqlite3.connect(glob.glob('data/online*.db')[0]); print([r[0] for r in c.execute('select name from sqlite_master')])"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, ls, cd, If...Else.Five teams build models on the same customer and order data, each with their own feature code. Design a feature platform that removes skew and leakage without slowing them down.
Which features move first? How are features defined, reviewed, and owned? How do training sets get point-in-time values? How does serving read features, and what about request-time ones? How do you measure skew and freshness, and who is paged?
Say 300 features, 2 million customers, 40,000 predictions a second at peak with a 50 ms budget of which features get 8 ms, and hourly freshness for most features.
A feature store (Feast or a managed equivalent) with definitions in Git and owners; batch features computed hourly into the offline store and materialised to a Redis or DynamoDB online store; streaming features for the few that need seconds; get_historical_features for every training set; serving through get_online_features; a shared library for request-time features; sampled logging of served vectors; a daily skew job and freshness SLOs with alerts; lineage into the catalog.
A central store means one more platform to run and a migration for every team, and in return one definition per feature; online reads cost a few milliseconds on the critical path; streaming freshness costs far more than hourly batch, so use it only where it changes predictions.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Two implementations | Hop 8: Request | Breaks | To save a network call, the checkout team recomputes orders_7d in Java from their own orders table, counting the current calendar week instead of the last 7 days. On Mondays the value is close to zero. |
| The join leaks the future | Hop 4: Point-in-time join | Breaks | A notebook builds the training set with a plain join on customer_id to the current feature table. Customers who converted have more recent orders, so the feature includes the very order being predicted. Offline AUC is 0.97; in production it is 0.71. |
| The join leaks the future | Hop 5: Training set | Degrades | The run logs the features but not how the training set was joined. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.