Platform Engineering · Lesson 330

Feature Stores, Online/Offline Consistency, and Lineage

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: does production see what training saw?

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.

0.83offline AUC
0.82production AUC

Consistent

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Feature stores grow in four levels: reading features, defining and serving them, proving consistency, and running a feature platform.

Basic — Read a feature and its history

At the basic level you can find a feature, read its definition, and look up its value now and in the past.

  • Entity, value, timestamp: the three columns behind every feature.
  • Offline (history, for training) and online (latest, for serving).
  • The TTL: how long an online value is served before it counts as missing.

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.

Intermediate — Define once, serve twice

At the intermediate level you add features without creating skew.

  • Definitions in Git (a Feast FeatureView or equivalent) with owner, window, and TTL.
  • Training sets built with point-in-time joins (get_historical_features).
  • Serving through 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.

Advanced — Prove consistency

At the advanced level consistency is measured, not assumed.

  • Log served feature vectors (sampled) with the model version and request time.
  • A daily skew job: recompute offline for the same entities and times; alert when the match rate drops.
  • Freshness SLOs on materialisation and stream lag; alerts before the TTL expires.

Try it: Advanced

How do you detect training-serving skew automatically?

Now do it: Write the skew query for one feature.

Master — Run a feature platform

At the master level features are shared products with owners, SLOs, and lineage.

  • A catalog: who owns each feature, which models use it, its freshness SLO and cost.
  • Column-level lineage from source to feature to model, so a source change lists the models it affects.
  • Deprecation: features unused for 90 days are flagged; removing one checks the model registry first.

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.

Go deeper

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).

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. One feature, implemented twice.

Timeline

  • Week 0The checkout team, to save a network call, computes orders_7d in their Java service from their own orders table. Their version counts the current calendar week.
  • Week 0–3Conversion drifts down about 4%. Offline evaluation of the model is unchanged; dashboards show no errors.
  • Week 3A data scientist logs the served feature vectors for a day and compares them with the store. orders_7d matches 69% of the time; on Mondays almost never.
  • Week 3 + 2 daysThe service reads the feature from the online store again. Conversion recovers within a day.

What changed after

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.

Try it yourself, from scratch

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).

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Create a local Feast project from its template.

    Reversible

    mkdir -p ~/labs && cd ~/labs
    feast init feature_lab && cd feature_lab/feature_repo
    ls

    Options: feast init NAME writes an example repository: feature_store.yaml (where the stores are) and an example definitions file.

    Expect: A feature_store.yaml, a definitions .py file, and a data/ folder with example Parquet.

    Clean up: rm -rf ~/labs/feature_lab.

  2. Register the definitions: Feast reads the Python and writes its registry.

    Read-only

    feast apply
    feast feature-views list

    Options: apply registers entities and feature views; feature-views list shows them.

    Expect: One or more feature views with their entities, from the template.

  3. Copy the latest values into the online store (SQLite here; Redis or DynamoDB in production).

    Read-only

    feast materialize-incremental "$(date -u +%Y-%m-%dT%H:%M:%S)"

    Options: The timestamp is "up to now"; Feast remembers where the last run stopped.

    Expect: A progress line per feature view and the number of rows written.

    Clean up: The online store is a SQLite file under data/ inside the lab folder.

  4. Look at what the online store holds: tables of latest values, no history.

    Read-only

    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')])"

    Expect: One table per feature view: the online store keeps only the latest value per entity.

2. Python: feature_skew.py

This 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%)

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

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.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Two implementationsHop 8: RequestBreaksTo 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 futureHop 4: Point-in-time joinBreaksA 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 futureHop 5: Training setDegradesThe run logs the features but not how the training set was joined.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Definition → Transformation → Offline store → Point-in-time join → Training set → Materialisation → Online store → Request → Skew check. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 331
Feature Engineering, Batch Inference, and Online Inference: One Definition, Two Serving Paths

Feature engineering turns raw events into the numbers a model actually reads, and the same feature must mean the same thing in training and in production.

Go to Lesson 331 →

Or browse the full course from the Lessons index.