Feature Engineering for ML Systems: Encoding, Scaling and Aggregates

Feature engineering for production ML: scaling, bucketing, one-hot and hashing, embeddings, feature crosses, windowed aggregates and training-serving skew.

Intermediate 3 min read · Updated

Feature engineering turns raw data (events, profiles, text, images) into the numbers a model consumes. In production systems the hard part isn't inventing clever features; it's computing them the same way in training and at serving time, fresh enough to matter, and cheap enough to fetch within a latency budget. This guide covers the transformations interviewers expect you to name and the system choices behind them.

Feature groups to name in an interview

GroupExamples (video recommender)Changes
UserAge bucket, country, languages, account age, long-term topic interestsSlowly
ItemCategory, duration, creator, upload age, global CTR, embeddingSlowly (stats daily)
ContextTime of day, day of week, device, network, pagePer request
User-itemHas the user watched this creator? Similarity of user and item embeddingsPer request
Real-time behaviourVideos watched in the last 10 minutes, current session topicsSeconds

Listing groups like this, then picking two or three high-value features per group, is clearer than a long flat list.

Transforming numeric features

  • Scaling: min-max to [0, 1] or z-score standardisation, so features with large ranges don't dominate gradient-based models. Tree models don't need it.
  • Log transform: for heavy-tailed counts (followers, views, price): log(1 + x).
  • Bucketing (discretisation): turn age or distance into ranges; useful for linear models and for crossing with other features.
  • Clipping: cap outliers at a percentile so one bot with a million clicks doesn't distort the feature.
  • Missing values: impute with a default or median and add an is_missing flag; missingness is often informative.

Encoding categorical features

Categorical featureFew valuesdevice typeThousandscity, categoryMillionsuser id, item idOne-hotHashing trickfixed bucketsLearned embeddingdense vector
Choosing an encoding by cardinality. Small sets can be one-hot encoded; large ones need hashing or learned embeddings to stay memory-efficient.
  • One-hot: one binary column per value. Simple, but the vector grows with cardinality.
  • Hashing trick: hash the value into a fixed number of buckets (say 2^20). Handles unseen values and bounded memory; collisions add a little noise.
  • Embeddings: a learned dense vector per value, trained with the model. The standard for ids with millions of values. See embeddings.
  • Target encoding: replace a category by its historical label rate (for example a merchant's past fraud rate). Powerful but leaks the label unless computed only from earlier data.

Feature crosses and interactions

A feature cross combines features, such as country × hour_of_day or user_language × video_language, so a linear model can learn interactions. Deep models and gradient-boosted trees learn many interactions themselves, but explicit crosses are still common in ad and recommendation models (the "wide" part of wide-and-deep models).

Aggregates over time windows

Many of the strongest features are counts and rates over windows: a card's transactions in the last hour, a video's CTR over the last day, a user's watches in the last 7 days. They are computed by batch jobs for long windows and by stream processors for short ones.

Event streamWarehouse / lakeStream job1 min - 1 h windowsBatch job1 - 90 day windowsOnline storems lookupsOffline storehistory for trainingPrediction service+ request featuresTraining
Where features are computed. Slow features come from batch jobs; fast ones from a stream; request-time features are computed in the service. All land in an online store for serving and an offline store for training.

Training-serving skew

Skew happens when a feature's value at serving time differs from its value in training for the same situation. Causes and fixes:

CauseExampleFix
Two implementationsSQL in training, Java in the service; they round differentlyDefine each feature once; generate both paths from it (a feature store)
Different freshnessTraining used end-of-day counts; serving reads counts 5 minutes oldLog served features and train on the logs
Future leakageTraining aggregates include events after the predictionPoint-in-time joins
Missing at servingA feature service times out and returns 0Explicit defaults and missing flags; monitor null rates

The strongest guarantee is log-and-train: record the exact feature vector used for every prediction, and build training data from those logs. What the model trains on is then exactly what it saw.

Feature selection and cost

  • Each feature costs storage, a lookup at serving time, and an on-call burden when its pipeline breaks.
  • Use feature importance and ablations to drop features that add little.
  • Prefer features you can compute for new users and items, or cold start gets worse.
  • Watch for features that encode protected attributes or their proxies; see fairness checks.

Where it’s used

Fraud detection

Velocity features (transactions per card per minute, new device, distance from the last transaction) from a stream, joined with long-term merchant risk from batch.

Ads ranking

Billions of sparse id features hashed or embedded, with crosses between user segments, ad categories and placements.

ETA prediction

Real-time traffic and restaurant load from streams, plus historical route and kitchen times from batch.

In an interview

  • Group features into user, item, context, interaction and real-time, with two examples each.
  • Choose encodings by cardinality: one-hot, hashing or embeddings.
  • Say which features come from batch, stream or the request, and their freshness.
  • Explain how you prevent training-serving skew (one definition, point-in-time joins, logged features).

Frequently asked questions

How do you encode high-cardinality categorical features?

Use the hashing trick to map values into a fixed number of buckets, or learn embeddings for each value. One-hot encoding is only practical for features with a small number of values.

What is training-serving skew?

A difference between a feature's value in training and at serving time for the same situation, caused by separate implementations, different freshness or future leakage. Prevent it by defining features once, using point-in-time joins, and training on logged serving features.

Further reading