Platform Engineering · Lesson 323

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. A model can then be served two ways: batch inference scores everything on a schedule and writes the results to a table, and online inference scores one request at a time inside a latency budget. Most real systems use both, and both must read features built from one definition. This lesson follows one card payment through a fraud model's online path, which also reads last night's batch scores, and shows the two classic failures: a feature computed from raw data on every request, and a feature reimplemented by hand in the serving code.

Difficulty: Advanced · Know this first: Lesson 284, Lesson 322

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 milliseconds from the payment request to the fraud decision. It is a worked example, not a measurement. The online store and request transform hops decide whether the decision is fast and right.

Try it: where should each feature come from?

Pick how the 30-day spend feature is served, how the request-time amount transform is built, and how the model is served. The checkout's budget is 100 ms.

37 msdecision time
4 sfeature age
matches trainingfeatures

Check yourself

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

Basic to master

Production feature engineering grows in four levels: building good features, choosing the serving path, keeping paths consistent, and running both paths as one system.

Basic — Build good features

At the basic level you can turn raw data into useful, leak-free features.

  • Aggregates over windows, ratios, encodings, and flags.
  • Only data available at prediction time (no future information).
  • Units and time zones written into the definition.

Where it breaks: a feature that uses information the model will not have when it predicts.

Try it: Basic

A training feature uses the customer's total spend for the whole month, including days after the prediction date. What is wrong?

Now do it: Check one feature of yours for point-in-time correctness.

Intermediate — Choose the serving path

At the intermediate level you can decide batch, online, or both for each use.

  • Batch for answers that can be hours old; online for answers about this moment.
  • Precomputed aggregates in an online store; request-time features computed on the fly.
  • Timeouts, fallbacks, and score age as metrics.

Try it: Intermediate

Product recommendations shown on the home page are refreshed nightly. Batch or online?

Now do it: Classify three of your models as batch, online, or both.

Advanced — Keep the paths consistent

At the advanced level training and serving features match, measurably.

  • One definition per feature, materialised offline and online.
  • Shared request-time transform code, with parity tests in CI.
  • Per-feature comparisons between training and serving distributions, with alerts.

Try it: Advanced

How do you catch a serving transform that differs from training?

Now do it: Add a parity test for one request-time feature.

Master — Run both paths as one system

At the master level batch and online serving are one designed system.

  • Batch scores as fallbacks and inputs to online models.
  • Cost per thousand predictions for each path, and capacity for peak online traffic.
  • Feature ownership, deprecation, and reuse across teams.

Trade-off: online inference and streaming features cost more to run; batch is cheaper and can only be as fresh as its schedule.

Try it: Master

Batch and online scores for the same customer disagree widely. What do you check first?

Now do it: Compare batch and online scores for a sample of entities.

Go deeper

One feature definition served both ways, sketched with Feast (check the Feast documentation for your version; other feature stores have equivalent concepts):

# features.py: one definition, materialised to the offline and online stores
spend_30d = FeatureView(
    name="card_spend", entities=[card], ttl=timedelta(days=31),
    schema=[Field(name="spend_30d_eur", dtype=Float32), Field(name="payments_1h", dtype=Int64)],
    source=card_spend_stream_source)        # kept fresh by the streaming job

# batch inference: point-in-time features for every card, scored nightly
df = store.get_historical_features(entity_df=cards_as_of_now, features=["card_spend:spend_30d_eur"]).to_df()
scores = model.predict(transform(df))       # transform() is the shared package

# online inference: one key lookup per request, then the same transform
row = store.get_online_features(features=["card_spend:spend_30d_eur"], entity_rows=[{"card_id": card_id}]).to_dict()

Choosing the path: batch when predictions can be hours old, the entity set is known in advance, or the model is too slow for a request; online when the prediction depends on the request itself; both when an online model uses batch scores as features or as its fallback. Streaming features sit between them: computed continuously, read online.

Track, for each path: batch job success, duration, and score age at read time; online p99 latency, timeout and fallback rate; and per-feature distribution comparisons between training, batch, and online. A feature-level alert is usually the first signal of a broken transform, because outcome labels (fraud, churn) arrive days or weeks later.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. Two weeks of a fast, wrong model.

Timeline

  • Day 0The checkout team moves fraud scoring into its own service and rewrites the feature transforms in the service's language to remove a dependency. Tests check that the endpoint answers in time.
  • Day 1–13Latency is excellent. The amount feature is in cents instead of euros; scores cluster near zero, and nearly everything is approved.
  • Day 14Chargebacks arrive from the card networks. The fraud loss for the fortnight is several times normal.
  • Day 14, 16:00A comparison of logged serving features with training shows amount_ratio a hundred times larger. The shared transform package is restored the same day.

What changed after

Request-time transforms live in one shared package used by training and serving, a parity test runs in both pipelines, per-feature distributions are compared daily with alerts, and the score distribution has its own alert.

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: Linux with sqlite3 (sudo apt install sqlite3) and Python 3.

1. Linux commands

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

  1. Make a transactions table: 300,000 payments over 30 days for 2,000 cards.

    mkdir -p ~/labs/features && cd ~/labs/features && rm -f pay.db
    sqlite3 pay.db "CREATE TABLE tx(card INTEGER, day INTEGER, amount REAL); WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<300000) INSERT INTO tx SELECT i % 2000, i % 30, (i * 37 % 9000) / 100.0 FROM n; SELECT count(*) FROM tx;"

    Options: The recursive query generates rows without any extra tool; amounts are deterministic.

    Expect: 300000.

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

  2. The per-request way: compute one card's 30-day spend from raw rows, and time it.

    printf '.timer on\nSELECT round(sum(amount), 2) FROM tx WHERE card = 42 AND day >= 0;\n' | sqlite3 pay.db

    Options: .timer on prints the run time of each statement; it only works when commands arrive on standard input, hence the printf pipe.

    Expect: The spend (6771.0) and a Run Time line of a few milliseconds; with no index, every request scans all 300,000 rows.

  3. The batch way: materialise the feature for every card once, then look it up by key.

    Changes a real system: On a production database, run aggregate scans on a replica or the warehouse, never on the primary in the request path.

    sqlite3 pay.db "CREATE TABLE card_spend AS SELECT card, round(sum(amount), 2) AS spend_30d FROM tx GROUP BY card; CREATE UNIQUE INDEX card_pk ON card_spend(card);"
    printf '.timer on\nSELECT spend_30d FROM card_spend WHERE card = 42;\n' | sqlite3 pay.db

    Options: The CREATE TABLE ... AS SELECT is the batch job; the indexed lookup is what the request does.

    Expect: The same spend, 6771.0, with a run time close to zero: one key lookup instead of a scan. A stream or scheduled job keeps such a table fresh.

2. Python: features.py

This program defines one feature as a function, shows the difference between a point-in-time value and a leaky one, scores a stolen card with batch features and with online features, counts the database work of computing an aggregate per request, and catches a serving transform that uses cents instead of euros by comparing feature distributions. Save it as features.py, then run it.

# features.py
PAYMENTS = []                                       # (day, card, amount in EUR)
for day in range(1, 31):
    PAYMENTS.append((day, "card-a", 20.0 + day % 5))
    if day % 2 == 0:
        PAYMENTS.append((day, "card-b", 60.0))
PAYMENTS += [(30, "card-c", 15.0), (30, "card-c", 480.0)]   # a stolen card, used twice today

def spend(card, as_of, days):                       # the one feature definition: EUR in the days before as_of
    return sum(a for d, c, a in PAYMENTS if c == card and as_of - days <= d < as_of)

print("card-a on day 10, point in time versus leaky:")
print(f"  spend before day 10 (what serving will know): {spend('card-a', 10, 30):7.2f} EUR")
print(f"  spend for the whole month (leaks the future): {sum(a for d, c, a in PAYMENTS if c == 'card-a'):7.2f} EUR")
print()

def decide(today_count, today_spend):               # a stand-in for the model
    return "decline" if today_count >= 2 and today_spend > 300 else "approve"
today = [a for d, c, a in PAYMENTS if c == "card-c" and d == 30]
paths = {"batch (02:00 run)": (0, 0.0), "online (streamed)": (len(today), sum(today))}
print("card-c, third payment today, 495 EUR:")
for path, (n, s) in paths.items():
    print(f"  {path:<18} payments today {n}, spend today {s:6.1f} -> {decide(n, s + 495)}")
print()

RPS, PER_CARD_PER_DAY = 3000, 8
print(f"per-request aggregate: {RPS * 30 * PER_CARD_PER_DAY:,} rows read per second; online store: {RPS:,} key lookups per second")
print()

def ratio_training(amount_eur, avg_eur):            # the shared transform
    return amount_eur / avg_eur
def ratio_rewritten(amount_cents, avg_eur):         # the hand-written serving copy
    return amount_cents / avg_eur
sample = [(25.0, 22.0), (60.0, 60.0), (19.0, 21.5), (70.0, 58.0)]
train = sum(ratio_training(a, v) for a, v in sample) / len(sample)
serve = sum(ratio_rewritten(a * 100, v) for a, v in sample) / len(sample)
shift = serve / train
print(f"amount_ratio mean: training {train:.2f}, serving {serve:.2f}, shift {shift:.0f}x -> {'ALERT: skew' if shift > 3 or shift < 1 / 3 else 'ok'}")

Run it, and you should see this output:

$ python3 features.py
card-a on day 10, point in time versus leaky:
  spend before day 10 (what serving will know):  200.00 EUR
  spend for the whole month (leaks the future):  660.00 EUR

card-c, third payment today, 495 EUR:
  batch (02:00 run)  payments today 0, spend today    0.0 -> approve
  online (streamed)  payments today 2, spend today  495.0 -> decline

per-request aggregate: 720,000 rows read per second; online store: 3,000 key lookups per second

amount_ratio mean: training 1.06, serving 105.67, shift 100x -> ALERT: skew

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-engineering-batch-and-online-inference && cd ~/labs/feature-engineering-batch-and-online-inference) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Feature Engineering, Batch Inference, and Online Inference: One Definition, Two Serving Paths", 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=(
  'Make a transactions table: 300,000 payments over 30 days for 2,000 cards.'
  'The per-request way: compute one card'\''s 30-day spend from raw rows, and time it.'
  'The batch way: materialise the feature for every card once, then look it up by key.'
)

step_1() {
mkdir -p ~/labs/features && cd ~/labs/features && rm -f pay.db
sqlite3 pay.db "CREATE TABLE tx(card INTEGER, day INTEGER, amount REAL); WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<300000) INSERT INTO tx SELECT i % 2000, i % 30, (i * 37 % 9000) / 100.0 FROM n; SELECT count(*) FROM tx;"
}

step_2() {
printf '.timer on\nSELECT round(sum(amount), 2) FROM tx WHERE card = 42 AND day >= 0;\n' | sqlite3 pay.db
}

step_3() {
sqlite3 pay.db "CREATE TABLE card_spend AS SELECT card, round(sum(amount), 2) AS spend_30d FROM tx GROUP BY card; CREATE UNIQUE INDEX card_pk ON card_spend(card);"
printf '.timer on\nSELECT spend_30d FROM card_spend WHERE card = 42;\n' | sqlite3 pay.db
}

# 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

Your company runs fraud scoring at checkout, a nightly churn model, and home-page recommendations. Design the features and serving paths for all three.

Clarifying questions to ask

Which features does each model use, and which are aggregates, request-time features, or batch outputs? Which models are batch, online, or both? Where are aggregates computed and stored? How are transforms shared? What is logged and compared? What are the latency budgets and fallbacks?

Rough sizing

Say 3,000 payments per second at peak with a 100 ms budget, 20 million customers for churn, and 5 million daily home-page visits.

Shape of the answer

One feature repository with versioned definitions; a stream keeping card aggregates in an online store; fraud served online with batch risk tiers as features and as the fallback; churn as a nightly batch job writing to a table for the CRM; recommendations as batch candidates re-ranked online with session features; one shared transform package with parity tests; logged features with daily per-feature comparisons; score age, fallback rate, and p99 as SLOs.

Trade-offs to name

Streaming aggregates and online serving cost more than batch; batch is cheap and stale by design; sharing transform code adds a dependency between teams and removes the most common source of skew.

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
Aggregate computed per requestHop 3: Online storeBreaksspend_30d has no online value, so the serving code runs SELECT SUM(amount) over 30 days of the transactions table for this card. It takes 1,850 ms, and the database is now under load from every checkout.
Transform reimplementedHop 4: Request transformBreaksThe serving team rewrote the amount transform in the checkout service and used the amount in cents, as the payment API sends it. Training used euros.

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: Definitions → Batch scores → Online store → Request transform → Model server → Batching → Fallback → Decision → Logging. 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 324
Model Registry and Promotion: Tracking, Validation Gates, and Rollback

A trained model is an artifact, like a container image: it should be built reproducibly, recorded with everything that made it, tested before it ships, promoted through environments by a gate rather than by hand, and easy to roll…

Go to Lesson 324 →

Or browse the full course from the Lessons index.