Skip to content
Tech Interview Prep
Technical interview guide

Feature Engineering & Selection

Turning raw data into model-ready inputs, and choosing which ones actually help.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: scikit-learn stable preprocessing, composition, selection, and inspection guidance and Google ML Crash Course feature guidance accessed 2026-08-31..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

How do you choose transformations for numerical features?

Answer

The 90-second answer. The estimator decides most of this. If the model splits on thresholds (gradient-boosted trees, random forests) any monotone transform (standardize, log, clip) produces an identical fitted model, because only the ordering of values matters. So for trees I transform only for what the model can't do itself: encode missingness, or make a feature's effect readable. For linear models, neural nets, and distance-based methods (kNN, SVM-RBF, k-means), scale is load-bearing, so I standardize or robust-scale. Then I look at shape: right-skewed positive quantities get log1p; heavy tails with genuine outliers get a robust scaler or a quantile transform. Every learned statistic is fitted inside the pipeline on training folds only and reproduced at serving.

Why scale is load-bearing. Put a feature ranging 0–1e6 next to one ranging 0–1 and the design matrix condition number is ~1e6; gradient descent needs roughly that many more steps to converge, and an L2 penalty of λ=1 shrinks the small-scale feature's coefficient far harder than the large-scale one. Standardizing makes the penalty uniform across features. Trees are immune because a split at x > 40 is the same split at log1p(x) > 3.71.

Worked example. session_duration_seconds: median 40, mean 120, p99 3000, max 90000. log1p gives 3.71, 8.01, and 11.41. The raw max/median ratio is 2250; after log1p it is 3.08, so the tail stops dominating the gradient. For a linear model I then standardize the logged column.

Python
# scikit-learn 1.4
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
import numpy as np

log_then_scale = Pipeline([
    ("log", FunctionTransformer(np.log1p, feature_names_out="one-to-one")),
    ("scale", StandardScaler()),
])
TransformUse whenDon't use when
StandardizeLinear/NN/distance; roughly symmetricTrees; heavy outliers (mean/std get dragged)
RobustScaler (median/IQR)Outliers present, linear modelYou need bounded output
log1pRight-skewed, non-negative, multiplicativeValues can be negative; zeros are meaningful
QuantileTransformerArbitrary shape, want uniform/normalServing values fall outside training range
Clip at p1/p99Cap leverage of extreme pointsThe extremes are the signal

Failure modes and detection.

  • Leakage: fitting the scaler on all rows before splitting inflates validation. Detect by comparing fold-fitted vs global mean/std: a large gap means leakage.
  • log(0): yields -inf. Use log1p or clip at a floor; assert no -inf/NaN after the transform.
  • Serving drift: training median 40, serving median 400 shifts every standardized value. Monitor per-feature mean/std against training and alert on drift.
  • Quantile clipping: values beyond the training range collapse to the [0,1] edges, losing resolution. Track the fraction of serving values sitting exactly on a boundary.

I keep an ablation against the raw baseline and judge on validation metric, calibration, and subgroup stability, not on how the histogram looks.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Explain leakage-safe target encoding.

Answer

The 90-second answer. Target encoding replaces a categorical column with the mean of the target for that category. The leak is that a row's own label sits inside its own encoding, so the model can read the label back out: worst for rare categories, where the encoding is nearly the label itself. Leakage-safe means every training row's encoding is computed from rows excluded from that row's own estimate, and the exclusion respects the split structure: folds for i.i.d. data, groups for repeated entities, time for temporal data. Concretely, K-fold with K=5 or 10: for each fold, compute category means on the other K-1 folds and apply them to the held-out fold. Smooth rare categories toward a training-only prior, map unseen categories to that prior, and refit the mapping on all development data for serving.

Assumptions worth stating up front: the column is high-cardinality, there are enough rows per category to estimate a mean, the split unit matches the deployment unit, and the feature itself carries no target leakage.

Mechanism. Smoothing pulls small categories toward the prior:

enc(c) = (n_c * mean_c + m * prior) / (n_c + m)

m is the prior's weight in pseudo-rows; start at m=10 and tune it. Below roughly 20-50 rows, a category's estimate is mostly prior: that is the point, not a bug.

Worked trace. Binary target, prior 0.30, m=10. Category Firefox has 5 rows labelled 1,0,1,1,0, so mean_c = 0.60:

enc = (5*0.60 + 10*0.30) / 15 = (3.0 + 3.0) / 15 = 0.40

A category with a single row labelled 1:

enc = (1*1.0 + 10*0.30) / 11 = 4.0 / 11 = 0.36

Barely above prior. Without smoothing that row would encode as 1.0 and hand the model its own label.

Why leave-one-out is not enough: enc_i = (sum_c - y_i) / (n_c - 1). Take a category with two rows, labels 1 and 0. Row 1 gets (1-1)/1 = 0; row 2 gets (1-0)/1 = 1. The encoding is exactly 1 - y_i. A tree splits on it and recovers the label perfectly in training, then collapses on holdout. Subtracting your own row is not the same as excluding it.

Alternatives and when to pick.

approachleak riskwhen it wins
one-hotnonecardinality up to ~10-20, linear models, plenty of rows per level
out-of-fold target encodinglow if folds respect groups/timehundreds+ of categories, tree models, ~20-50+ rows per category
leave-one-outhigh: the encoding is invertibleessentially never for trees or NNs
CatBoost ordered target statisticslow, built inyou are already on CatBoost; it permutes rows and encodes each from predecessors only, with a prior weight

The deciding criterion is cardinality against rows-per-category. Stay on one-hot until the column is wide enough that trees stop finding splits; target-encode when it is, and only if you have the rows to estimate each level.

Failure modes and how to detect them.

  • Encoding fitted before the split, on train plus validation. Detect by shuffling the target and rerunning CV: if CV AUC stays well above 0.5, the encoding is leaking.
  • Group or time violation: the same user, or future rows, on both sides. Detect by comparing group/time-split CV against random-fold CV; a large gap is the tell.
  • Duplicate rows landing in both train and holdout. Deduplicate before folding.
  • Train/serve skew. Normalization (case, whitespace, unseen to prior) and the mapping version must match. Log the fraction of serving rows hitting the prior; a jump means the mapping is stale.

Refit the encoder inside each fold of the model-selection loop, not once outside it, or tuning leaks too.

Serving. After selection, refit the mapping on all development data, freeze it alongside the model version, and apply the same normalization. The test set is touched once, with the frozen mapping.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do you encode a high-cardinality categorical feature?

Answer

First I'd pin down three things: how many distinct values we're actually talking about, what model consumes the feature, and whether the value is available at serving time. A 50k-value user_id feeding a GBDT is a different problem from a 5M-value device_id feeding a linear model or a neural net. If the value isn't stable at serving, no encoding saves it: you're just moving the failure.

Assuming it is stable, my default for a tree model is out-of-fold smoothed target encoding. The mechanism: replace each category with the mean of the target over the rows in that category, shrunk toward the global prior so rare categories don't get extreme values. The shrinkage is (n_c * mean_c + m * prior) / (n_c + m), with m around 10–20 when you have a few hundred thousand rows. Here's the arithmetic on a toy frame:

Python
import pandas as pd
df = pd.DataFrame({"city": ["A","A","A","B","B","C"],
                   "y":    [ 1,  1,  0,  1,  0,  1]})
prior = df["y"].mean()          # 4/6 = 0.6667
m = 2
stats = df.groupby("city")["y"].agg(["sum", "count"])
stats["enc"] = (stats["sum"] + m * prior) / (stats["count"] + m)

Tracing it: prior is 4/6 = 0.6667. For A, sum=2, count=3, so (2 + 2*0.6667) / (3+2) = 3.3333/5 = 0.6667. For B, sum=1, count=2, so (1 + 1.3333)/(2+2) = 2.3333/4 = 0.5833. For C, sum=1, count=1, so (1 + 1.3333)/(1+2) = 2.3333/3 = 0.7778. Note C's raw mean is 1.0 and smoothing pulls it down to 0.78: that's the whole point.

The critical part is out-of-fold. If you compute those means on the same rows you train on, the model reads the label off the feature: a category with one row and label 1 gets encoded 1.0. Split into 5 folds, compute stats on 4, apply to the 5th, and fall back to the global prior for categories unseen in the training folds. The leak shows up as train AUC 0.99 against holdout 0.72: that gap is the tell, and it's the first thing I'd check.

Alternatives, and when each wins. Hashing maps hash(category) % 2**b into buckets; it's stateless, so it handles unseen values for free and is the right call for online linear models. With 1M distinct values into 2**18 = 262,144 buckets you average 3.8 values per bucket and about 98% of buckets are occupied. Collisions between rare values are harmless; two high-volume categories landing together destroys signal, so I check per-bucket target variance before trusting it. Frequency encoding replaces the category with its count: no leakage, cheap, but two categories with the same count become indistinguishable, so it only works alongside something that keeps identity. Minimum-frequency grouping folds everything under, say, 10 occurrences into OTHER: simple and interpretable, at the cost of the tail. For neural nets, learned embeddings with dimension around min(50, (cardinality+1)//2) are the standard, but they need enough rows per category to learn anything.

Failure modes I'd name: leakage from in-sample target encoding, caught by the train/holdout gap; drift, caught by watching serving OOV rate climb from 2% to 15%, which means the vocabulary is stale and needs a retrain; and collision damage on a hot key in hashing. If the feature is high-cardinality but low-signal, dropping it beats every encoder on this list.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How would you handle missing values in a production model?

Answer

Short answer: I don't have one missing-value strategy. I first ask what the absence means, because the meaning decides whether I impute, encode, or page someone. Then I make the imputation fold-safe and freeze the statistics into the model artifact so training and serving agree.

Assumptions I'd state up front: a tabular model, batch-trained and served online, features from a warehouse table plus a real-time feature store. If this is a text or image model, most of what follows doesn't apply.

The taxonomy, and why each category behaves differently:

  • Not applicable: promo_code is null because the order had no promo. The null is the true value. Imputing a median promo code is nonsense; encode it as its own category.
  • Unmeasured: the field exists but the client didn't send it, usually an old app version. This is the only category where statistical imputation is defensible, because the value exists and is missing for a reason unrelated to itself.
  • Delayed: settlement amount, chargeback flag. The value will arrive, just after prediction time. Imputing it is fine; reading the eventual value during training is leakage. Use point-in-time joins.
  • Redacted: PII stripped by policy. Missingness is deterministic given the policy, so the indicator column leaks the policy, not the value.
  • Failed collection: the pipeline dropped the column. That's an incident, not a modeling problem. Alert, don't impute.

Mechanism: why fold-safe matters. If I compute the median over the whole dataset and then cross-validate, every validation fold has seen its own median. The AUC comes back optimistic and the model ships worse than the offline number. Fitting the imputer inside the training split is the fix:

Python
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

pipe = Pipeline([
    ("impute", SimpleImputer(strategy="median", add_indicator=True)),
    ("clf", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(pipe, X, y, cv=5, scoring="roc_auc")

cross_val_score clones and fits the whole pipeline per fold, so the median is computed on four folds and applied to the fifth. add_indicator=True appends one binary column per feature that had a NaN in that fold's training data: 20 features with 3 containing nulls becomes 23 columns after transform. That indicator is often the most predictive column in the model, which is itself a signal: if is_missing_device_age ranks high, the missingness is informative and I should treat it as MNAR rather than impute it away.

Trees vs linear. XGBoost and LightGBM route NaN down a learned default direction per split, so they need no imputation at all; sklearn's HistGradientBoostingClassifier does the same. Linear and neural models need an explicit value. I'd use native handling for the tree and still keep the indicator.

Failure modes I've actually hit:

  • Train/serve skew. The offline imputer fills with the training median; the online service fills with 0 because the feature store returns null. Fix: serialize the imputer into the model artifact and load it in the serving path. Test with a fixture that has a null in every column.
  • Silent pipeline break. device_age_days missingness jumps from 12% to 30% overnight. That's a client release or a broken join, not drift. Alert on per-feature missingness rate against a trailing 7-day baseline, and on imputed fraction separately: they move for different reasons.
  • Zero-fill. Only when zero is the documented meaning. Zero-filling a "days since last purchase" column makes every new user look like a same-day buyer.

Monitoring: missingness rate per feature per cohort, imputed fraction, and AUC/calibration sliced by missing cohort. If the missing cohort's calibration drifts while the overall number holds, the imputation is masking a population shift.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Compare filter, wrapper, and embedded feature selection.

Answer

Core answer

The three families differ in one thing: whether the model is in the loop when features are chosen.

  • Filter: score each feature with a statistic computed without the model: mutual information, ANOVA F, chi-square, variance threshold. One pass over the data, no fits. Model-agnostic, so it cannot see interactions or redundancy.
  • Wrapper: search subsets and refit the estimator to score each candidate (forward selection, RFE). Model in the loop, so it captures interactions, at the cost of many fits and selection overfitting.
  • Embedded: selection happens inside the fit: an L1 penalty drives coefficients to exactly zero, a tree only splits on features that reduce impurity. One fit, model-aware, but inherits the estimator's assumptions.
model in loop?costsees interactionsmain risk
FilternoO(n·d), one passnodrops jointly-useful features
Wrapperyes, refit per subsetfits × search stepsyesselection overfit
Embeddedyes, during one fitone fit + λ pathpartlyestimator assumptions

Why filters miss interactions. A filter scores each feature marginally, so a feature that only matters in combination scores zero. XOR is the clean case:

Python
# scikit-learn 1.4, Python 3.11
import numpy as np
from sklearn.feature_selection import mutual_info_classif
rng = np.random.default_rng(0)
n = 2000
x1 = rng.integers(0, 2, n)
x2 = rng.integers(0, 2, n)
y = x1 ^ x2                       # label depends on both, on neither alone
X = np.c_[x1, x2]
print(mutual_info_classif(X, y, discrete_features=True).round(4))
# -> [0. 0.]   both features look useless to a filter

A depth-2 tree or a wrapper finds the pair immediately. That is the whole argument for putting the model in the loop.

Why wrappers overfit. The subset is chosen on the same data used to score it, and you take the max over many candidates, so the winning score is optimistically biased. Cost is the other half. Forward selection to k=20 over d=200 features refits 200+199+…+181 = 3,810 times; with 5-fold CV inside each evaluation that is 19,050 fits. At 0.2 s per fit on 100k rows, ~63 minutes for one selection run.

Failure modes and how I detect them.

  • Filter drops jointly-useful features. Detect by comparing the filter's top-k against a wrapper or embedded top-k on a held-out set; a large gap means interactions matter here.
  • Wrapper selection overfit. Detect with nested CV: select inside the inner fold, score on the outer fold. If the inner score beats the outer by more than a couple of points, the subset is fitted to noise.
  • L1 instability under correlated features. Two near-identical columns get one coefficient zeroed essentially at random. Detect by re-running selection on bootstrap resamples and measuring Jaccard overlap of the selected sets; below ~0.6 the set is not stable enough to ship.

Embedded caveats. L1 is scale-sensitive, standardize first, and its strength is set by C (inverse of λ) in LogisticRegression(penalty='l1', solver='liblinear'), tuned by CV over the regularization path. Tree importances are biased toward high-cardinality and continuous features, so a categorical with many levels can outrank a genuinely stronger binary one.

What I do. Put every data-dependent selector inside the CV loop, tune its size there, and always compare against a no-selection baseline. Then report stability, latency, and interpretability before choosing a family.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How do you prevent feature selection from overfitting validation?

Answer

Core answer (first 90 seconds). The leak is that the selector sees the validation fold. Fix: wrap selection, preprocessing, and estimator in one Pipeline and fit it inside every training fold. Estimate generalization with nested CV: an inner loop selects features and tunes hyperparameters, an outer loop scores the whole procedure. Bound the search: cap k, use a univariate filter or L1 with fixed C, avoid wrapper methods that re-fit hundreds of times. Use group- or time-aware splits when samples are not i.i.d. Report selection stability across resamples (e.g., Kuncheva index) and score dispersion (mean ± std). Keep an untouched outer test set or a final holdout for the whole procedure. Compare against no selection and a simple baseline.

Mechanism. Selection is a fitting step: it uses labels to choose features. If it runs before the split, the validation fold's labels influence which features are kept, so the validation score is optimistic. Nested CV isolates that step: the inner loop only sees the outer training fold. The outer score is then an unbiased estimate of the pipeline's performance.

Named specifics. Selectors: SelectKBest(f_classif, k=20), SelectFromModel(LogisticRegression(penalty='l1', C=0.1, solver='liblinear')), mutual_info_classif. Folds: StratifiedKFold(n_splits=5, shuffle=True, random_state=0) repeated 10 times for stability; GroupKFold(n_splits=5) when groups exist; TimeSeriesSplit(n_splits=5) for temporal data. Stability metric: Kuncheva index between selected sets across repeats; values above ~0.6 indicate stable selection. Score dispersion: report mean ± std across outer folds.

Worked example (hypothetical). Dataset: 1,000 samples, 200 features, 20 informative, binary labels. Pipeline: SelectKBest(f_classif, k=20) → LogisticRegression. Outer: 5-fold stratified. Inner: 5-fold stratified, repeated 10 times.

procedureouter AUCselection stability (Kuncheva)
select on full data, then 5-fold CV0.92 ± 0.010.91
selection inside pipeline, nested CV0.81 ± 0.030.68

The leaky estimate is 0.11 AUC too high. The correct estimate is 0.81 ± 0.03. Stability 0.68 means the selected set overlaps substantially but not perfectly across resamples; if it were 0.3, the selection is too unstable to trust.

Trace of one split. Outer fold 1: training = 800 samples, validation = 200. Inner 5-fold on the 800: each inner training fold (640) fits SelectKBest, picks 20 features, fits logistic regression, scores on inner validation (160). Average inner score picks k=20 (or tunes C). Then the pipeline is re-fit on all 800 with those hyperparameters, and scored on the 200 validation samples. The validation labels never touched selection. Repeat for the other 4 outer folds; average the 5 outer scores.

Failure modes. (1) Selection before split: detected by comparing flat CV to nested CV; a large gap (e.g., 0.92 vs 0.81) is the signature. (2) Wrapper methods like RFECV inside the inner loop: each step re-fits the estimator; with 200 features and 5×5 folds this is thousands of fits, and the inner validation can overfit. Bound by using a filter or L1 with fixed C. (3) Time-series: random CV leaks future into past; use TimeSeriesSplit and select only on past data. (4) Group leakage: same patient in train and validation; use GroupKFold. (5) Repeated manual inspection: if you look at the outer test score and then change the selector, that test is consumed; log it as selection and get a new holdout.

Trade-offs. Filter methods are fast and stable but ignore feature interactions. Embedded L1 selects but drops correlated features arbitrarily. Wrapper methods are accurate but expensive and prone to overfitting inner folds. When n < 100, selection is unstable; prefer domain knowledge or stronger regularization over selection.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Design a point-in-time-correct feature pipeline for transaction risk.

Answer

What I'd say first

Assume the entity is the card, the decision time is the authorization timestamp, and the label is a chargeback filed within 120 days of the transaction. The action is allow / step-up / block, decided inside a 100 ms authorization budget.

The core answer: store every feature value twice-timestamped, when the event happened (event_time) and when the value became queryable (available_at), and make every training join select the latest row with available_at <= decision_time, not event_time <= decision_time. Training and serving read the same versioned feature definitions; the offline store materializes them in batch, the online store serves them from a low-latency KV store.

Why leakage happens, and how the join resolves it

A table that records only event_time cannot tell you whether a value was known at decision time. Backfills and corrections rewrite history. Trace:

cardfeatureevent_timeavailable_atvalue
4471merchant_category2024-02-01T00:00Z2024-02-01T03:00Zgrocery
4471merchant_category2024-03-01T00:00Z2024-03-20T09:00Zgambling

Authorization at 2024-03-11T14:02:07Z. Joining on event_time <= cutoff returns gambling: a value that did not exist until nine days after the decision. Joining on available_at <= cutoff returns grocery, which is what the model would actually have seen. That single predicate is the whole point-in-time guarantee.

Windows and label maturity

Velocity features: count of authorizations per card over 1 h, 24 h, 7 d and 30 d, each excluding the current event. Compute them in Flink over a Kafka auth stream so the online value is at most ~30 s stale; account age and BIN country are batch, refreshed daily, because they don't move.

Labels need the same discipline. A training set built on 2024-03-11 can only use authorizations from before 2023-11-12, 120 days earlier, or recent rows carry immature labels and look clean. Plot chargeback rate by label age; it flattens around day 110-120, and that is your cutoff.

Trade-offs

Batch vs streaming: a daily Spark job is cheaper and easier to backfill, but a 24 h-stale velocity count misses card-testing bursts that finish in minutes. Stream the features that decide the action; batch the rest.

Feature store vs ad-hoc joins: ad-hoc SQL re-implements the cutoff predicate per model and drifts. Feast (or Tecton) gives one definition and a point-in-time join, at the cost of another service to run and slower wide backfills.

Don't version everything. Account creation date and BIN are immutable; versioning them adds storage and join cost for nothing. Version what can be corrected: merchant category, device reputation, risk scores.

Failure modes

  • Backfilled merchant category leaking into training. Detect by replaying the online store at historical cutoffs and diffing against the training values. Cost: offline AUC reads ~0.05 higher than production (hypothetical figure).
  • Late-arriving authorizations (offline POS, retries). Measure the arrival-lag distribution; if p99 lag is 4 h, a 1 h streaming window silently drops them.
  • Training/serving skew. Sample entity-timestamps daily, compute the feature both ways, alert when the mismatch rate exceeds 0.1%.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How would you audit a feature set for leakage?

Answer

The 90-second answer

Pin the prediction event and the label window first. Everything else follows from those two timestamps: a feature is legal only if its value was knowable at the prediction cutoff, and the label is only knowable after the window closes. Write both times down before touching a single feature.

Then walk each feature's lineage back to its source and ask one question: at the prediction cutoff, would this value have existed in this form? Three things fail that test most often. A status field that only reaches its final value after the outcome: an order that becomes "delivered" or "refunded" only once you already know the label. A dimension joined without an as-of condition, so a January training row picks up the March balance. And preprocessing fitted before the split (target encoding, imputation, scaling, feature selection) where the test rows' own labels leak into their own encodings.

Then reproduce the rows with point-in-time joins and measure. I use importance scores to pick suspects, never as evidence.

Worked trace: target encoding

Take 10,000 rows and a merchant_id column with 5,000 distinct values, so about 2 rows per merchant. Compute the target encoding on the full dataset before splitting. For a merchant with two rows, one positive and one negative, the encoding is 0.5, and half of that 0.5 is the test row's own label. The model reads its own answer back. Smoothing shrinks the effect but doesn't remove it. Fix: fit the encoder inside each training fold, or use out-of-fold encoding. Detection: recompute the encoding per fold and diff against the full-data version; any row whose value moves is contaminated.

Worked trace: as-of join

Training row: user 42, prediction cutoff 2024-01-15. Feature account_balance joined on user_id alone returns the current value, say 900. Reconstruct as-of the cutoff from the balance history table and you get 120. The 900 is a March number. Detection: for a sample of training rows, recompute each feature as-of its cutoff and count mismatches; a nonzero rate means the join is wrong. merge_asof in pandas, ASOF JOIN in DuckDB or kdb+, or a feature store's point-in-time retrieval all enforce this.

Alternatives and when to pick them

  • Ablation vs. permutation importance. Ablation retrains and captures interactions but is expensive and confounded when features are correlated. Permutation importance is cheap but splits or inflates importance across correlated features. If features are correlated, use grouped permutation or conditional importance; if you need the true marginal contribution, retrain.
  • Time-based holdout vs. random split. Random split is fine when there's no temporal structure and no entity overlap. Time-based is required when features are time-dependent; the cost is less training data and higher variance in the estimate.
  • Remove the feature vs. fix the pipeline. Removing is fast and safe; fixing preserves signal but needs a backfill and re-validation. Under deadline, remove first, fix later.
  • Manual as-of joins vs. feature store. A feature store enforces point-in-time correctness by construction but adds infrastructure; manual joins are fine for a one-off audit.

Failure modes

  • Redundant features hide leakage: two copies of the same leaky signal, ablation drops one and AUC barely moves. Detect with grouped ablation.
  • Entity leakage: the same user in train and test. Detect by hashing entity IDs across splits and checking overlap; a random split on user-level data with repeated users will show it.
  • Silent backfill: the warehouse corrects a value after training. Detect by snapshotting the feature table daily and diffing.
  • Adversarial validation: train a classifier to separate train from test rows. AUC near 0.5 means the distributions match; a high AUC points at a shift, often a leak or drift.

Close

A single-feature model is the cheapest leak detector: if one feature alone gets AUC 0.9 on a problem with a 5% base rate, it's leaking. High importance is a clue, not proof.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do you engineer time-based features safely?

Answer

The 90-second answer. Time-based features leak whenever a value at time t is computed from anything that happened at or after t. So the whole job reduces to one rule: every feature for a row must be computable from data strictly before that row's cutoff, and the same rule must hold in training and in serving. I fix four clocks up front: event time (when the thing happened), processing time (when the pipeline saw it), the prediction cutoff (the instant I'm allowed to know up to), and the label horizon (how far forward I look for the outcome). Then I build features as trailing windows that end at the cutoff, exclusive of the row itself.

Why leakage happens. The classic bug is a trailing aggregate computed over the whole table. "Transactions by this card in the last 24 hours" run as a plain groupby counts the row itself and every later row. The model learns from the future, offline AUC looks great, and it collapses in production.

Worked trace.

Python
import pandas as pd

events = pd.DataFrame({
    "card": ["C1","C1","C1","C1"],
    "ts": pd.to_datetime(["2024-03-09 23:30","2024-03-10 00:15",
                          "2024-03-10 01:00","2024-03-10 02:30"], utc=True),
})
labels = pd.DataFrame({
    "card": ["C1"],
    "ts": pd.to_datetime(["2024-03-10 01:00"], utc=True),
})

def trailing_count(labels, events, window="24h"):
    out = []
    for _, r in labels.iterrows():
        lo = r.ts - pd.Timedelta(window)
        m = (events.card == r.card) & (events.ts > lo) & (events.ts < r.ts)
        out.append(int(m.sum()))
    return out

print(trailing_count(labels, events))  # [2]

For the label row at 2024-03-10 01:00 UTC the window is (2024-03-09 01:00, 2024-03-10 01:00). The 23:30 and 00:15 events fall inside; the 01:00 event is excluded by the strict upper bound; the 02:30 event is in the future. Count = 2. A naive same-day groupby returns 3.

Timezone and DST. US spring-forward on 2024-03-10 moves local 02:00 to 03:00, so a "previous local day" window is 23 hours, not 24. If training used local calendar days and serving used fixed 24h windows, counts differ by whatever lands in that missing hour. I store event time in UTC and define windows as fixed durations; when a business rule genuinely needs local days, I encode the timezone explicitly and test the transition dates.

Trade-offs. Batch recompute versus streaming. Batch is point-in-time correct, cheap and reproducible, but stale by the batch interval. Streaming is fresh, but you must handle out-of-order and late events. Late arrivals: drop (simple, biased), wait on a watermark (adds latency), or correct retroactively (accurate, but training data changes between runs, so the backfill must be versioned). Pick by how much a late event moves the feature.

Failure modes.

  1. Label-window overlap: a feature like "chargebacks in the last 30 days" when the label is "chargeback within 30 days" contains the answer. Detect: offline AUC far above online, or one feature dominating importance.
  2. Training/serving skew: offline pandas rolling on event time versus an online window on processing time. Detect: log feature values at serve time and compare distributions to the training snapshot.
  3. DST/timezone mismatch: counts jump on transition dates. Detect: diff feature values across 2024-03-10 and 2024-11-03.
  4. Late arrivals: a transaction arriving 3 hours late changes a past cutoff's count; if you backfill, yesterday's training row differs from today's. Detect: re-run the backfill and diff.

Splits. Rolling-origin validation, not random K-fold: random splits put future rows in training. As-of fixtures pin the boundary cases: exactly-at-cutoff, empty history, and the DST day.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design an entity-level rolling aggregate feature.

Answer

What I'd say first

An entity-level rolling aggregate is a point-in-time value: for entity u at cutoff t, it is agg over u's events with event_time in (t - W, t] and ingest_time <= t. Three choices decide whether it is correct: the window's boundary convention, which timestamp the window is built on, and what happens to events that arrive after the cutoff. Timezone, dedup and no-history behaviour are consequences of those three, not independent design axes.

Boundaries. Use half-open left, closed right: (t - W, t]. An event exactly at t counts; an event exactly at t - W does not, because it already counted in the window ending at t - W. A closed-left window double-counts every boundary event across consecutive cutoffs.

Two timestamps, two jobs. event_time defines the window; ingest_time defines availability. A training row for cutoff t may only use events with ingest_time <= t, or the model learns from the future. This is the most common source of train/serve skew in these features.

Worked trace. User u1, W = 7 days, cutoff t = 2024-03-10T00:00:00Z, so the window is (2024-03-03T00:00:00Z, 2024-03-10T00:00:00Z].

event_idevent_timeingest_timeamount
e103-03T00:00:00Z03-03T00:00:05Z10
e203-04T12:00:00Z03-04T12:00:03Z20
e2 (correction)03-04T12:00:00Z03-05T09:00:00Z25
e303-10T00:00:00Z03-10T00:00:02Z30
e403-09T00:00:00Z03-11T08:00:00Z40
  • e1: event_time == t - W → excluded by the open left edge.
  • e2: two rows share an event_id; dedup keeps the latest ingest_time <= t, so amount 25.
  • e3: event_time == t → included.
  • e4: ingest_time > t → excluded; it was not available at cutoff.

Result: count = 2, sum = 55, mean = 27.5. With a closed-left window you would get count = 3, sum = 65, and e1 would also be counted in the window ending 03-03.

Trade-offs.

  • Batch recompute vs streaming. Batch over the warehouse is exactly reproducible and cheap to backfill, but the freshest value is one run old: typically 1–24h. A Flink/Kafka job gives sub-minute freshness but needs a re-emit path for late events, and both paths must share one aggregation spec or they drift. Choose streaming only when the label arrives fast enough that a stale feature costs accuracy; otherwise batch plus a short online delta.
  • Event time vs ingestion time for the window. Event time is causally right but trusts client clocks; ingestion time is monotonic but wrong for backfilled events. If client clocks are unreliable, bound the window with ingestion time and keep event time only for ordering.
  • Tumbling windows vs rolling at cutoff. Tumbling windows are precomputable and cheap, but a prediction at 03:00 uses a window ending at midnight. Up to 24h stale. Rolling at cutoff is exact and costs a scan per prediction; precompute per entity at a coarse grain and refine only for entities that need it.

Failure modes.

  • Train/serve skew from late data. Offline backfill includes e4; online at cutoff did not. Detect by logging the served value and recomputing the point-in-time value offline; alert when more than ~1% of entities differ by more than a few percent of the feature's standard deviation.
  • Duplicate inflation. If dedup keys on (event_id, event_time) and the producer re-emits with a new ingest_time, counts inflate. Detect with a raw-stream duplicate ratio per event_id; alert above 1.001.
  • Hot entities. One entity with 10M events in the window makes the per-prediction scan dominate. Watch p99 events-per-entity; cap the window or switch that entity to incremental aggregation.
  • No history. An entity with zero events gets count = 0 but mean = NULL, not 0: a 0 mean is a claim the model will learn from. Emit a has_history flag alongside the aggregate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design a leakage-safe text feature pipeline.

Answer

Leakage in a text pipeline enters two ways: stateful transforms fitted on data the model shouldn't see, and tokens that encode the outcome. I'll assume a supervised classifier over short documents, a time-ordered corpus, and a batch-trained model served online.

The answer: split first, then fit every stateful text transform (vocabulary, IDF, n-gram range, dimensionality reduction, fine-tuned embeddings) on the training fold only, and freeze the result as a versioned artifact that online serving reuses. Stateless steps (Unicode NFKC, lowercasing, whitespace collapse) can run anywhere.

Why fitting IDF on all data leaks. IDF(t) = ln(N / df(t)) in the textbook form, where N is the document count and df(t) the document frequency. Both are computed over whatever corpus you hand the vectorizer. Fit on train+test and the vocabulary membership and every weight depend on held-out documents. Concretely, with N_train = 800, N_all = 1000, and a token t that appears in 0 training docs but 4 test docs:

  • Fit on all, min_df=1: df(t)=4, IDF = ln(1000/4) = 5.52, t is in the vocabulary, and the model scores on a token it never saw in training.
  • Fit on train: df(t)=0, t is dropped, and it contributes nothing at eval.

That is the whole leak: the feature space is defined by data the model is being evaluated on, so the held-out score is optimistic and the online model sees a different feature space than the one it was scored with. (scikit-learn's default smooth_idf=True uses ln((1+N)/(1+df))+1, which shifts the numbers but not the argument.)

Python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

pipe = Pipeline([
    ("tfidf", TfidfVectorizer(ngram_range=(1, 2), min_df=2,
                              max_features=50_000, sublinear_tf=True)),
    ("clf", LogisticRegression(max_iter=1000)),
])
pipe.fit(train_texts, train_labels)               # vocab + IDF from train only
val_scores = pipe.predict_proba(val_texts)[:, 1]  # frozen vocab; OOV ignored

Trace: fit builds the vocabulary from train_texts, drops terms in fewer than 2 training docs, and computes IDF over training docs. predict_proba transforms val_texts with that frozen vocabulary; unseen terms are ignored. No validation statistic enters the fit.

Trade-offs. The artifact choice is real, not obvious:

choiceleak-safecostpick when
fit vectorizer per CV foldyesk× fithyperparameter search
fit once on train, reuseyes1× fitfinal model, fixed hyperparameters
fit on all datano1×never
hashing vectorizeryes (stateless)collisions, no IDFstreaming, no-fit constraint
feature store, point-in-timeyesinframany models share features

Deciding criterion for the last row: how many models consume the features and whether training needs point-in-time joins. One model, batch scoring: a versioned joblib artifact is enough. Several models with online serving and time-travel: a feature store earns its cost.

Failure modes and detection.

  • Post-outcome tokens ("discharged", "refund issued"): train a unigram model on suspect tokens alone; AUC above ~0.8 means the text encodes the label. One extra training run.
  • Temporal drift: compare random-split AUC against time-split AUC; a gap above ~0.05 means the random split is leaking future vocabulary.
  • Duplicate leakage: MinHash near-duplicate check across splits; report overlap percentage.
  • OOV at serve: monitor OOV rate. Train 1.2% versus serve 7% means the vocabulary is stale: retrain.

Evaluation. Calibration (reliability curve, Brier score), language and cohort slices, adversarial text, and a lexical baseline (TF-IDF + logistic regression) that any embedding model must beat. Version the artifact and log its hash with every prediction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

When are feature crosses useful, and how do you control them?

Answer

The 90-second answer

Crosses are worth adding when you have a specific hypothesis that the effect of one categorical feature depends on the value of another, and the model you're using can't represent that interaction on its own. The canonical case is a linear or logistic model over one-hot categoricals: category=shoes and region=DE each get their own weight, and the model can only add them. If shoes sell unusually well in Germany, no additive combination of those two weights captures it. Crossing them, category=shoes AND region=DE, gives that cell its own weight. Google's Wide & Deep is the standard reference: the wide side crosses installed-app and impression-app so the model can memorize specific pairs.

If you're already on a GBDT or a deep net with embeddings, you get interactions from tree depth or from embedding dot products, so crosses buy you much less and cost you the same cardinality. I'd only add them there to memorize high-frequency pairs.

How I control them

Four levers, in order.

  1. Hypothesis and a cardinality budget. I write down the interaction I expect and the maximum number of cross values I'm willing to carry, say 200k, before I build anything. Cross cardinality is the product of the parts: 500 categories × 40 regions = 20,000. Add device with 5 values and the three-way is 100,000. That number decides whether this is a feature or a memory problem.

  2. Minimum support. I drop cross values with fewer than roughly 100 training examples. Below that the weight is fit on a handful of rows and memorizes noise. That's a starting threshold, not a law: I tune it against a holdout.

  3. Hashing when support filtering isn't enough. The hashing trick maps the cross into a fixed bucket count. With 100,000 distinct cross values into 2^20 = 1,048,576 buckets, about 9% of values share a bucket with another (1 − e^(−100000/1048576) ≈ 0.091). Drop to 2^18 = 262,144 buckets and that jumps to about 32%. Collisions blend two unrelated cells' weights, so I size the space to keep the collision rate under roughly 10%.

  4. Regularization. L1 on the cross weights, which is what FTRL-Proximal does for ad CTR: it drives rare crosses to zero and keeps the model sparse. L2 alone shrinks but doesn't remove.

Train/serve consistency is the part that bites. The hash function, seed, and feature ordering must be identical in training and serving, and unseen cross values at serving time must map to a stable default bucket rather than being dropped. If they're dropped, the model sees a different feature vector than it was trained on.

Failure modes I check for:

  • Gain that comes from a handful of rare entities: I look at the support distribution of the crosses that picked up large weights.
  • Leakage: crossing with a feature that isn't available at decision time.
  • Temporal drift: a cross that helps on last month's data and not this month's. I run ablations across time windows and cohorts, not just a random split.

When not to use them: when the interaction is already captured by the model class, or when the cross's cardinality is a large fraction of your training rows. At that point you're memorizing the training set.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do correlated features affect selection and explanation?

Answer

What a strong candidate says first. Correlated features don't change how much signal the model has; they change how that signal is credited. Two columns at r=0.95 carry nearly the same information, so any procedure that scores one column at a time: L1 coefficients, tree impurity, single-column permutation importance, univariate SHAP: is free to hand the credit to either one. The group is real; the member is arbitrary. So I group substitutable features, evaluate the group, and report the group.

Why it happens. With L1, the loss surface is flat along the correlation direction and the penalty has a corner, so the optimum lands on whichever feature the solver reaches first: a coin flip that flips again on the next bootstrap. With trees, two correlated columns produce near-tied split gains, and the tie-break is by column order. With single-column permutation, permuting feature A leaves feature B intact, so the model recovers the signal and the measured drop is near zero for both.

Concrete failure modes, detection, cost.

failuredetectioncost
L1 selector picks one of a correlated pair arbitrarilyrun selection on 100 bootstrap resamples; the pair swaps, each chosen roughly half the timea weekly retrain churns half the "top 20" list; downstream dashboards and cached feature stores break
Single-column permutation importance reports ~0 for both twinsgrouped permutation (permute both together) vs single-column; in a worked example grouped drops AUC 0.85 → 0.62 while each single drop is <0.01you delete a jointly important feature and lose 0.2 AUC in production
Coefficient signs flip between correlated columnsVIF > 10, or design-matrix condition number > 30explanation says "more A raises risk" while the model does the opposite when A moves alone
SHAP splits credit across twinscompare interventional vs conditional SHAP; rankings disagreestakeholder acts on a proxy, not a lever

What I do. Cluster columns at |r| ≥ 0.9 (or VIF > 10), keep one representative per cluster for the model, and evaluate the cluster as a unit with grouped permutation (sklearn.inspection.permutation_importance, n_repeats=5, on the grouped block). For linear models, ElasticNet with l1_ratio=0.5 keeps correlated groups in together instead of dropping one. For selection stability, run stability selection (100 subsamples of 50%, keep features selected in ≥70%) and report the selection frequency, not a single winner. For explanations, use conditional SHAP (shap.TreeExplainer(model, data, feature_perturbation="interventional")) and say "this group of features" rather than naming one cause.

Where this fails. Correlation clustering merges features with different operational costs: a cheap cached column and an expensive real-time lookup can be r=0.95 and still not interchangeable. Stability selection with 20 subsamples has a standard error wide enough to flip the answer; 100 is the floor. And grouping by correlation alone misses non-linear redundancy (two features independent marginally but redundant jointly), which needs a model-based check.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How should feature importance be interpreted?

Answer

Interpret feature importance as a diagnostic of the model's behavior, not as a causal effect. It's conditional on the model, the data, and the metric you choose, so the first thing I ask is: importance for what? For predicting the target, for explaining the model's decisions, or for causal inference? The method and the interpretation change with the answer.

For a linear model, coefficients are importance only if features are on the same scale and uncorrelated. Standardize first. With collinearity, coefficients become unstable: a small change in the data can flip signs, because the model can trade weight between correlated features.

For tree ensembles, scikit-learn's default feature_importances_ is mean decrease in impurity (Gini importance): the total reduction in node impurity, weighted by the fraction of samples reaching that node, averaged over all trees. It's biased toward high-cardinality features, because a feature with many distinct values offers more split points that reduce impurity, and toward correlated features, because the tree may split on either one and split the credit between them.

Permutation importance, sklearn.inspection.permutation_importance, is more model-agnostic. It shuffles a feature's values and measures the drop in a scoring metric. The default is n_repeats=5, and it returns the mean and standard deviation over repeats. Its failure mode is correlation: permuting one feature creates unrealistic rows, age 20 with income $200k, and the model can still predict from the correlated feature, so both get low importance. Grouped permutation permutes a set of correlated features together; conditional permutation permutes a feature within strata of the correlated ones.

MethodWhat it measuresFailure mode
Linear coefficientsChange in log-odds per unit changeScale-dependent; unstable with collinearity
Tree impurityMean decrease in Gini impurityBiased toward high-cardinality and correlated features
PermutationDrop in score when a feature is shuffledCreates unrealistic rows; hides redundant features
SHAPAdditive feature contributionMode-dependent; interventional needs background data
Python
from sklearn.inspection import permutation_importance
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42).fit(X_train, y_train)
result = permutation_importance(model, X_test, y_test, n_repeats=10, random_state=42, scoring='roc_auc')
print(result.importances_mean)

I use n_repeats=10 rather than the default 5 to get a more stable estimate. The output is one mean drop in ROC AUC per column of X_test.

SHAP values are another tool: they're additive and give local explanations. For tree models, shap.TreeExplainer has two modes. feature_perturbation="tree_path_dependent" walks the tree paths and is the faster mode; it needs no background dataset. feature_perturbation="interventional" requires a background dataset and marginalizes over it, which is slower but is the recommended mode when you have background data to pass. Pick the mode deliberately, because the attributions differ.

A worked check with illustrative numbers: take two features where x2 = x1 + small noise. Train a random forest. Impurity importance might give roughly 0.5 to each. Permutation importance might give roughly 0.1 to each, because permuting x1 leaves x2 to compensate. Group them and permute both together, and the importance jumps to roughly 0.8. That tells me the pair is important, but neither alone is. I also check stability across folds: if the ranking flips between folds, I don't trust it.

Failure modes: importance is misleading if the model is overfit, so compute it on held-out data. It hides redundant features, so use grouped or conditional methods. It's unstable on small data, so use repeats and report the standard deviation. And it does not establish causality, fairness, or approval to use a sensitive proxy: for that you need causal inference or domain review.

So my interpretation: importance is a diagnostic of the model's behavior, not a causal truth. I triangulate with multiple methods, check stability, and always ask what decision the importance will inform.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How do you use ablation studies for feature decisions?

Answer

First I pin down what "better" means, because ablation only answers a question you have already fixed. I freeze the split, the pipeline, the metric, the seeds, and the decision threshold, then remove one semantically coherent feature group at a time and re-measure. What comes back is a marginal contribution: how much the model loses when that group is gone and everything else stays put.

The mechanism decides how to read it. A model reallocates weight to whatever else carries the same signal, so ablation measures a group's contribution given the rest of the feature set, not the information it contains. Two features correlated at 0.9 each look worthless alone (remove either and the model leans on its twin, delta near zero) while removing both drops the metric hard. So I ablate groups, not columns: cluster by correlation and by provenance (everything sourced from the same upstream table), and ablate the cluster.

Concretely, on a churn model: 12M rows, 4% positive rate, time-based split (train months 1–9, validate 10, test 11–12): I use PR-AUC because the class is imbalanced, and I also report recall at the deployed threshold (precision floor 0.70), because a ranking metric hides threshold-level damage. Five time-based folds, same seeds, paired deltas so the comparison shares fold noise. Figures below are illustrative.

configPR-AUCrecall @ P=0.70p99 latencyread
full0.4120.58120 ms—
minus ticket-sentiment group (3 feats)0.3980.5195 ms−0.014 PR-AUC, −7 pts recall
minus ticket group, refit on 3 windows0.398 ± 0.006——sign stable
minus browser-version group0.4110.57588 msdelta 0.001, fold σ 0.003

The ticket group's delta is 0.014 against a fold σ of 0.004: about 3.5σ, and it moves recall 7 points at the operating point, so it stays. Browser version is inside the noise and costs a join, so it goes. That is the whole decision: keep what clears both a statistical bar and a business bar, drop the rest.

Failure modes I watch for, each with a detection signal:

  • Correlated masking. A useful feature looks useless because a twin absorbs it. Detect by checking pairwise correlation and permutation importance on the group before trusting a near-zero delta; ablate the whole cluster.
  • Leakage. A feature that encodes the label shows a huge drop when removed, but the gain evaporates in production. Detect by confirming the feature is available at prediction time and checking train/serve skew.
  • Threshold blindness. PR-AUC flat while the feature moves the operating point. Detect by reporting precision/recall at the deployed threshold, not just the ranking metric.
  • Noise-chasing. With 40 groups at α=0.05 you expect two false positives. Detect with paired folds and a policy of delta > 2σ, or Benjamini–Hochberg across the sweep.
  • Distribution shift. The feature helps on the training window and hurts on the next. Detect by refitting on several time windows and checking the delta's sign holds.

I do not call any of this causal. Removing a feature is not intervening on it in the world; it is a statement about this model on this data. The decision rule I state up front is: keep a group only if its paired delta clears 2σ across folds, it moves the deployed operating point, and its latency, freshness, and upstream-availability cost is worth that move.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How do you evaluate sensitive attributes and proxy features?

Answer

Core answer (first 90 seconds)

Two separate questions, and conflating them is the usual failure. First: which columns are sensitive or legally protected, and should they be in the feature set at all? Second: given what remains, how much of the sensitive attribute can still be reconstructed? The second decides the design, because dropping a column almost never removes the information.

Assumptions I'd state out loud: the protected attribute is available at evaluation time (not necessarily at scoring time), I have legal and privacy sign-off to hold it, and the decision is high-stakes enough to justify the cost of the audit.

Why proxies leak

Features correlate with each other and with the attribute. Zip code, first name, device type, credit utilization and employment gaps each carry a slice of it. A model with 40 features does not need the race column if twelve of them jointly predict it. So the test is not "is the column present" but "what is the AUC of a classifier trained to predict the attribute from the remaining features?" 0.5 means no signal; 0.7 is a real proxy; 0.85+ means removal bought you almost nothing.

What I measure

CheckMetricRough threshold
Direct presencecolumn audit against the protected-class listany hit → legal review
Proxy strengthprobe AUC, mutual information>0.7 investigate, >0.8 treat as proxy
Outcome gapdemographic parity difference and ratioratio <0.8 (four-fifths rule, 29 CFR 1607)
Error gapequalized odds difference (TPR/FPR gap)>0.1 needs an explanation
Calibrationper-group Brier score, calibration curvecurves must overlap
RedundancyVIF, Cramér's VVIF >10 flags collinearity

Worked trace (hypothetical figures)

200k loan applications, group A 62%, group B 38%, 40 features. Baseline: AUC 0.81, approval 71% for A vs 52% for B → parity difference 0.19, ratio 0.73. Equalized odds difference 0.11.

Probe: logistic regression predicting group from the 40 features → AUC 0.79. Permutation importance on the probe: zip code 0.09, income 0.05, utilization 0.03, everything else under 0.01.

Drop zip code, retrain. Probe AUC 0.76 (down 0.03), model AUC 0.79 (down 0.02), parity difference 0.17. Removing the single most obvious proxy moved the gap two points. That is the finding to report: the leak is distributed, not localized.

Python
# fairlearn 0.10, scikit-learn 1.4
from fairlearn.metrics import MetricFrame, demographic_parity_difference
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score, roc_auc_score

mf = MetricFrame(metrics={"tpr": recall_score}, y_true=y, y_pred=pred, sensitive_features=group)
print(mf.by_group)
print(demographic_parity_difference(y, pred, sensitive_features=group))

probe = LogisticRegression(max_iter=1000).fit(X_train, group_train)
print("proxy AUC", roc_auc_score(group_test, probe.predict_proba(X_test)[:, 1]))

Failure modes

  • Fairness gerrymandering: dropping the attribute hides harm in intersectional subgroups (older disabled applicants, Black women) that the marginal gap averages away. Check the smallest subgroup with n≥100.
  • Removal that hurts the group: if the attribute is genuinely predictive of the outcome, dropping it can raise error for that group. Measure before and after; do not assume.
  • Small subgroups: a 0.15 gap on n=40 is noise. Report confidence intervals.
  • Parity and calibration pull against each other; you generally cannot have both exactly. Pick based on the cost asymmetry of the decision and say why.
  • Feedback loops: if decisions feed future training data, today's proxy becomes tomorrow's label.

When not to remove

Keep the attribute for auditing and monitoring behind access control, used only at evaluation time. If the model drives remediation (targeted outreach, benefit enrollment) the attribute may be a legitimate input. That is a documented policy call, not a modeling one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you guarantee offline-online feature parity?

Answer

Parity means one thing: for the same entity and the same event time, the value the model trained on and the value served at request time are equal. "Same code" is one route to that, not the definition. Pick the route by your online latency budget and whether one team owns both paths.

routemechanismcostfails when
Shared artifactOne Python or SQL module; Spark/Flink runs it in batch, the serving process imports the same moduleOnline pays Python/UDF cost; both sides must pin the same library versionsA heavy UDF pushes p99 past budget; Spark executors and serving hosts drift on numpy/pandas
Dual implementationBatch in Spark SQL, online in Go or JavaFastest online path, no shared runtimeEvery logic change is two changes; drift stays silent until the model degrades
Feature store (Feast, Tecton)Store owns materialization, point-in-time joins, and the offline/online splitInfra and vendor lock; on-demand transforms limited to what the store can expressYour transform needs a library the store can't run online

dbt defines batch features well but stops at the warehouse: it doesn't give you the online side, so it's a component of route 1, not a route.

Now the failure modes that actually bite, each with a signal:

Salted hashing. Python's hash() on a str is randomized per process unless PYTHONHASHSEED is fixed. hash(user_id) % 1024 buckets the same user differently in the Spark worker and in the serving process, so the model sees a feature that means two things. Signal: a CI golden fixture that runs both paths on the same input and diffs. Fix: murmurhash3 or md5, never builtin hash.

Point-in-time leakage. The offline table is usually keyed by when the batch ran, not by event time. A daily 23:59 run gives a training row for a 09:30 label a feature that already contains the 09:58 and 10:04 events. The model trains on the future. Signal: log (entity, feature, value, event_time) on every served request, recompute offline as of that event_time nightly, alert when the mismatch rate exceeds 0.1% of feature-values over 24h.

Null and default divergence. Batch COALESCE(x, 0.0) against an online -1 sentinel teaches the model that missing is a real value. The same fixture catches it.

Timezone and window boundaries. Batch truncates to UTC days, online to local; or a 7-day window anchored at midnight versus at request time. Signal: a fixture with events at 23:59:59 and 00:00:00.

Freshness. Signal: p99 age of the online value per feature; alert above 2x the materialization interval.

Worked trace (hypothetical figures). Entity u_42 has orders at 09:20, 09:58 and 10:04 on 2024-03-05. A click at 09:30 is the label. Materialization runs hourly at :00, and the online store is pushed on the same cadence. Online at 09:30 reads the 09:00 push, which covers orders up to 09:00, so orders_7d = 0. The training join picks the latest materialization at or before the label time, also 09:00, so offline is 0. Parity holds, at the cost of up to 59 minutes of staleness. Now the nightly 23:59 run writes orders_7d = 3 for u_42. If training joins that row to the 09:30 label, offline is 3 and online was 0: the model learns from a feature that already knows about the 09:58 and 10:04 orders. Fix: join on materialization_time <= label_time, and read the online store at the same boundary. Pushing every 5 minutes while training on hourly boundaries reintroduces the skew.

Rollout: shadow-score the new path against the live one for a week, then canary 1% of traffic, rolling back automatically when the mismatch rate crosses the alert threshold.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

What problem does a feature store solve, and what does it not solve?

Answer

The 90-second answer

A feature store owns the pipeline between raw data and model inputs: it defines a feature once, computes it, keeps historical values for training, keeps the latest value for serving, and returns either by entity key. The problem it solves is duplication and skew. Without one, every team re-implements "user's 30-day order count" in Spark for training and in Java for serving, and the two drift. With one, that definition lives in one place, gets backfilled consistently, and is retrievable point-in-time.

What it does not solve: it does not make the definition correct, it does not stop target leakage, it does not fix bad source data, and it does not remove online/offline skew unless the transformation code is actually shared.

Mechanism: point-in-time correctness is the whole point

Training on a label at time T needs feature values as they existed at T, not as they exist now. The store does this with an as-of join: for each (entity, label_timestamp) row, take the latest feature row with feature_timestamp <= label_timestamp.

Worked trace. Label table:

user_idlabel_tschurned
72024-03-101

Feature table orders_30d:

user_idfeature_tsorders_30d
72024-03-014
72024-03-096
72024-03-1511

The as-of join picks 6 (2024-03-09). A naive join on user_id that takes the newest row picks 11: computed five days after the label, from orders placed after the churn. That is the classic leak: offline AUC comes out around 0.94 and production lands near 0.61 (illustrative figures).

Feast does the join in one call:

Python
store.get_historical_features(
    entity_df=labels,   # user_id, event_timestamp, churned
    features=["orders:orders_30d"],
).to_df()

Serving reads the materialized latest value:

Python
store.get_online_features(
    features=["orders:orders_30d"],
    entity_rows=[{"user_id": 7}],
).to_dict()

feast materialize-incremental pushes offline rows into Redis or DynamoDB so the online value matches the offline value at the same timestamp. Tecton and Vertex AI Feature Store do the same job with a managed control plane; Vertex pairs BigQuery as the offline source with Bigtable for online serving.

What it does not solve

  • Definitional leakage. As-of joins fix time leakage only. If support_tickets_30d predicts churn and the ticket was filed because the user is churning, the store serves the leak faithfully. No store detects that; a feature review does.
  • Source quality. Late events, duplicates and nulls pass straight through. A streaming aggregation with a 5-minute watermark drops events a nightly batch includes, so online and offline counts differ by exactly the late fraction.
  • Skew from separate code paths. Tecton's and Feast's on-demand feature views exist to run one transformation at request time, but if you compute in SQL offline and in Python at serving, the store cannot reconcile them.
  • Privacy and deletion. Immutable offline history makes erasure hard: deletes must propagate to the online store and to every materialized training set.
  • Backfills. Changing a definition invalidates history. You need versioned feature views and a backfill, which on a two-year, 10^9-row table is a real cost.

Detection

Log the feature vector at serving, join it back to the offline value for the same entity and timestamp, and track PSI per feature. Track feature_timestamp lag p50/p99 for freshness. In CI, build the training set twice (once with the naive join, once with the as-of join) and fail the build if AUC moves more than a set threshold. That gap is the leak.

When not to use one

Under about ten features and one model, a dbt model plus a Redis write is cheaper to run. Adopt a store when reuse across teams and point-in-time correctness justify the extra operational surface.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

What should be monitored for production features?

Answer

Core answer. Monitor features in three layers, in this priority order: did the value arrive correctly, did its distribution move, and did the model's behavior change. Pipeline health comes first because a stale feature is worse than a drifted one: it is silently wrong and the job still reports green. Distribution second, because it is the earliest signal you get before labels mature. Impact third, because it is the only layer that proves the feature still matters. I set thresholds from each feature's contract, not from one global rule, and I rank alerts by how many predictions the feature touches.

Layer 1: arrival. Per feature: a freshness watermark (max event timestamp in the served data), null rate, min/max, and a schema/type check. The watermark is the one that matters. A daily batch feature with a 2-hour SLA should alert when now - watermark > 2 * cadence, not when the job exits non-zero: the common failure is a job that succeeds writing yesterday's partition. Null rate: a jump from 0.3% to 12% on a feature the model weights heavily is a page; the same jump on a tail feature is a ticket.

Layer 2: distribution. For numerics, PSI against the training distribution; for categoricals, OOV rate against the training vocabulary and, if you hash, collision rate. PSI is cheap and interpretable:

Python
import numpy as np

def psi(expected, actual, bins=10):
    edges = np.quantile(expected, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    e = np.histogram(expected, edges)[0] / len(expected)
    a = np.histogram(actual, edges)[0] / len(actual)
    e, a = np.clip(e, 1e-6, None), np.clip(a, 1e-6, None)
    return np.sum((a - e) * np.log(a / e))

Trace: when actual equals expected, a == e, every term is zero, PSI is 0. The 0.1 / 0.25 cut points (stable / moderate / significant) are the convention from credit-risk scorecard monitoring; treat them as a starting point, not a law.

Layer 3: impact. Join feature alerts with model version, prediction distribution, calibration, and mature labels. This is what separates a real break from noise: a PSI of 0.3 on a feature the model barely uses is not worth waking anyone.

Failure modes and how you catch them.

FailureDetection signal
Silent stalenessFreshness watermark age > 2× cadence while job is green
Training/serving skewLog online feature vectors, recompute offline, compare per feature; offline AUC 0.82 vs online 0.71
Alert stormAlert volume itself: 400 features × daily PSI at 0.25 trips ~20/day on seasonality alone
Seasonality false positiveCompare against same weekday baseline, require two consecutive days

Trade-offs. Fail-open vs fail-closed on a stale feature: fail-closed (drop the feature, serve a default) when the feature is high-importance and the prediction carries money or risk; fail-open (serve the last good value) when importance is low and staleness is bounded. The deciding criteria are feature importance × staleness bound × cost of a wrong prediction. Per-feature alerting vs aggregate: per-feature catches narrow breakage but storms; aggregate is quiet but misses single-feature failures. Use per-feature for the top-N by importance, aggregate for the tail.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

How do you detect, isolate, and mitigate training-serving skew in online feature pipelines?

Answer

Training-serving skew occurs when the distribution of features or target semantics fed to the model at inference diverges from what was seen during training. It stems from three distinct root causes: discrepancies between online and offline transformation logic, time-travel data leakage during training set generation, and asynchronous pipeline latencies.

1. Detection

To detect skew before downstream business metrics degrade, compute statistical divergence between logged online feature payloads and training baseline distributions:

  • Numerical features: Run two-sample Kolmogorov-Smirnov (KS) tests or track Population Stability Index (PSI). A feature PSI $> 0.2$ indicates significant distributional drift requiring investigation, while $0.1 \le \text{PSI} < 0.2$ warrants monitoring.
  • Categorical features: Monitor Jensen-Shannon divergence (JSD), out-of-vocabulary (OOV) rates, and unmapped string rates.
  • Direct Log-and-Wait Parity Audits: Sample 1% of live inference requests, log the exact feature vectors emitted by the serving layer, wait for ground-truth arrival, and reconstruct the training vector offline using historical batch pipelines. Compute exact feature-by-feature diffs (e.g., zero tolerance on categorical equality, epsilon $| ext{feat}{\text{online}} - \text{feat}{\text{offline}}| < 10^{-5}$ on float transforms).

2. Isolation

When skew is detected, trace the divergence to a specific stage across the pipeline boundaries:

[Client Request] ---> [Online Feature Service] ----(Log Vector)----> [Parity Audit]
      |                        |                                           |
 (Payload Data)       (Redis / Online KV)                                  |
      |                        ^                                           |
      v                        | (Streaming Sync: Flink/Kafka)             v
[Raw Event Stream] ---> [Feature Store / Lakehouse] --(as-of join)--> [Diff Check]
Pipeline BoundaryDiagnostic CheckCommon Failure Signature
Logic DiscrepancyRun identical raw inputs through both Python/C++ serving transforms and PySpark/SQL training transforms.Systematic offsets in floating-point operations, discrepancies in string trimming/case folding, or different null imputation values (e.g., 0 vs median).
Time Travel / LeakageCompare event timestamp $t_e$ against partition cutoff timestamp $t_{\text{cutoff}}$.Feature values at training contain information from events where $t_e > t_{\text{inference}}$ (e.g., daily aggregates computed including the current day's events).
Materialization LagCompare online_write_timestamp - event_timestamp at serving time.Feature distributions shift toward default/imputed values during peak ingress due to Kafka consumer lag or Redis sync backpressure.

3. Structural Mitigation

  1. Unified Transform Graph: Discard dual-implementation stacks (e.g., pandas offline, Go/Java online). Compile feature transformations into a single portable definition (such as serializing scikit-learn ColumnTransformer pipelines, ONNX computation graphs, or shared C++ libraries via foreign function interfaces) deployed to both online microservices and batch training jobs.
  2. Point-in-Time Correct As-Of Joins: Avoid naive table joins for label construction. Offline pipelines must enforce strict as-of window joins: every feature value must satisfy $\text{timestamp}{\text{feature}} \le \text{timestamp}{\text{label_trigger}}$.
  3. Log-to-Train Architecture: Instead of recomputing feature values retrospectively from raw data lakes when generating training sets, write the logged online inference feature vectors directly to a historical partition. Training directly on logged features eliminates serving-time reconstruction skew by design.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How should a feature be retired?

Answer

What I'd say first

"Retire" is two migrations, not one: first make the old path unreachable, then delete the code and the data. I'd assume the feature sits behind a flag, has a named owner, emits per-caller telemetry, and its data has a retention obligation. If any of those is missing, adding it is the first task: you cannot retire what you cannot measure.

The decision that shapes the rest is hard cutover versus a shadow period. Hard cutover when you can enumerate every caller and rollback is a flag flip. A shadow period when callers are external or unknown, because the only way to find them is to watch real traffic.

The sequence

PhaseActionExit criterionRollback
0 AnnounceDeprecation notice with owner and dateNo new callers for 14 daysn/a
1 DarkFlag off for 1% → 100%; old path still deployedError rate flat, no unexpected 404sFlip flag back
2 Delete codeRemove handler and routes; keep the tableDeploy clean, no references in the repoRevert the commit
3 Delete dataDrop the table after the retention windowBackup has expiredRestore from backup

Why the order matters

Phase 1 exists because a flag flip is reversible in seconds and a code delete is not. Keeping the old path deployed while the flag is off costs nothing and buys you the rollback. Deleting code before the flag has been off at full traffic for a full business cycle (a week, so weekly cron jobs fire) is how you discover a consumer you never knew about.

Phase 3 is separate from phase 2 because code deletion is reversible and data deletion is not. The gap between them is the retention window, and it is the only thing standing between a mistake and a restore-from-backup incident.

Worked example (figures illustrative)

A legacy CSV export endpoint runs at 40 rps, 0.3% of API traffic, backed by a 1.2 TB table. At $0.023/GB-month that table costs about $28/month, so deleting it is a compliance decision, not a cost one, and there is no urgency argument for skipping the retention window. The 40 rps figure is also misleading: aggregate QPS hides the weekly cron that calls it once. Log caller identity (service account, user-agent) for 30 days before flipping, not just request counts.

Failure modes and how I'd catch them

  • Silent periodic consumer. A nightly job calls the endpoint; a 1% canary never sees it. Detected by per-caller logs, not aggregate metrics. Cost: a broken batch job discovered at 02:00.
  • Stale config in one region. The flag default flips in code but one region's config store still serves the old value. Detected by splitting the error-rate metric by region; a global average hides it.
  • Deleting data under a legal hold. Detected by checking the retention policy against the table's hold flag before the drop, not after.

The criterion

I retire on a hard cutover when blast radius is small and rollback is a flag flip; I take the long shadow when I cannot enumerate callers. Either way, the feature is gone only when the code is deleted and the data has passed its retention window, not when the flag is off. The flag being off is the start of the clock, not the end of the work.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How do you backfill a corrected feature without corrupting experiments?

Answer

Clarify, then answer

The first question is whether anything has already consumed the feature. If no logged experiment or deployed model has read it, overwrite in place: a corrected backfill is just a normal job. If something has, mutating the old values silently breaks reproducibility: experiment E42's recorded AUC no longer corresponds to any data you can regenerate. So the rule is append, don't overwrite.

Assumption: the feature table is bitemporal. Each row carries event_time (when the fact happened) and knowledge_time (when the pipeline wrote it). Feast, Tecton and Databricks Feature Store all model this; a plain warehouse table gets it by adding a knowledge_time column.

Mechanism

The backfill writes corrected rows under a new feature_version with knowledge_time = now(). Nothing is deleted. Reads are point-in-time: for each label, take the feature row with the greatest knowledge_time that is still <= the run's cutoff.

SQL
-- BigQuery / Snowflake dialect
SELECT l.user_id, l.event_date, f.value
FROM labels l
JOIN feature_user_click_rate f
  ON  f.user_id    = l.user_id
  AND f.event_date = l.event_date
  AND f.knowledge_time <= l.cutoff_ts
QUALIFY ROW_NUMBER() OVER (
  PARTITION BY l.user_id, l.event_date
  ORDER BY f.knowledge_time DESC) = 1;

Trace it on two rows:

user_idevent_datevalueversionknowledge_time
72024-03-010.40v12024-03-02
72024-03-010.25v22024-04-10

Run R1 with cutoff_ts = 2024-03-15 → only the v1 row qualifies → 0.40, the old metric reproduces. Run R2 with cutoff_ts = 2024-04-15 → v2 wins → 0.25. Same query, different cutoff, both correct. That is the whole trick: the cutoff, not the table, decides which truth you see.

Alternatives and when to pick them

  • Overwrite in place: cheapest, no query change. Only safe before any experiment has consumed the feature.
  • Shadow feature (user_7d_click_rate_v2): old experiments literally cannot see the new column, so isolation is free. Costs feature-name sprawl and a consumer migration. Pick this when the store isn't bitemporal and you can't add the column.
  • Versioned append (above): preserves both truths in one table. Costs storage and forces every reader to pass a cutoff.

Storage is the real bill. A 400M-row daily feature at ~40 bytes/row is ~16 GB/day; two versions for a year is ~11 TB. Keep v1 only for the reproducibility window, 90 days is typical, then drop it.

Failure modes

  • Leakage via backfilled labels. If you backfill a label with knowledge_time = now() but join on event_time alone, training sees outcomes it couldn't have known. Detect: a train/val AUC gap that widens only after the backfill.
  • Silent metric drift. If the experiment registry doesn't pin feature_version, re-running E42 after the backfill quietly reports a different number. Detect: a CI job that re-runs one pinned experiment and asserts the metric matches.
  • Non-idempotent backfill. Re-running duplicates rows and inflates counts. Key on (user_id, event_date, feature_version) and upsert.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How do privacy and latency constraints shape feature engineering?

Answer

Assumptions first: this is a real-time scoring path with a p99 SLO (say 200 ms end-to-end, of which I'll allow 50 ms for feature retrieval) and the raw data includes regulated PII (user location, transaction history). If either is false, the answer changes.

Core answer. Privacy constrains what you may compute and how long you may keep it; latency constrains when and where you compute it. They meet at the same design move: push computation offline, onto coarser data, and keep raw PII out of the online path. Concretely, I precompute aggregates over cohorts rather than per-user rows, store them in a low-latency KV store, and serve a single lookup per request.

Why aggregation helps both. Collapsing a user into a group is what buys privacy, a cohort of k≥10 makes re-identification from the feature alone hard, and it also shrinks cardinality, so the online lookup is smaller and faster. Zip code 60614 becomes state IL; exact age becomes a decade bucket. The cost is signal: neighborhood-level effects vanish. I measure that as an AUC delta on a held-out slice, not as a vibe.

Why caching shifts the distribution. A cache hit is one Redis GET, sub-millisecond in-AZ; a miss recomputes, tens of milliseconds. So the hit rate, not the mean, sets your tail. With a 95% hit rate, 5% of requests take the miss path, and p99 is the miss path. To make p99 equal the hit path you need a miss rate under 1%. That's the number I'd put in the design doc, because it decides whether a 50 ms feature budget is even reachable.

Trade-offs and deciding criteria.

  • Granularity vs privacy: coarser cohorts are safer and faster but lose signal. Decide by the AUC delta you'll pay for a given k.
  • Precompute vs on-the-fly: precomputed features are stale by the refresh interval (an hourly job is up to 60 min stale) but cost one lookup; on-the-fly is fresh but adds compute to the critical path. Decide by how fast the signal decays.
  • DP noise vs accuracy: an ε budget bounds re-identification; larger ε means less noise and more utility. Decide by the regulator's tolerance, not by lift.

Failure modes, with detection.

  • Training/serving skew: offline features built from full history, online from a truncated window, so distributions diverge. Detect by comparing online feature distributions to offline (PSI or KS) and alerting on drift.
  • Cache stampede: a cold or expired key gets hit by many requests at once, recomputing in parallel and spiking p99. Detect via miss-rate and backend CPU; mitigate with request coalescing or jittered TTLs.
  • Proxy leakage: a "neutral" feature like zip code reintroduces a protected attribute. Detect by measuring its correlation with the protected attribute and the disparate-impact ratio.
  • Residency breach: a feature replicated to a region outside the allowed boundary. Detect with a data-flow audit, not a code review.

Artefact: the decision table.

Feature formRe-id riskOnline costSignal
Raw per-user eventhighcompute on pathbaseline
Precomputed per-userhigh~1 ms lookupbaseline
Cohort aggregate (k≥10)low~1 ms lookupAUC drop
DP-noised aggregateε-bounded~1 ms lookupnoise

The rule I'd state to the team: privacy sets the floor on aggregation, latency sets the ceiling on freshness, and the feature you ship is whatever survives both.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you generate and prioritise candidate features (domain hypotheses, error analysis on failures, automated synthesis) and decide which are worth the engineering and serving cost before committing?

Answer

A strong candidate answers in three moves: name the discovery funnels, say they all land in one triage queue, and give the gate that decides what ships.

Candidates come from domain hypotheses, error analysis on the current model, and automated synthesis. Domain hypotheses are written as falsifiable mechanisms tied to the decision, not as column names: "a card's distinct-merchant count in the last 10 minutes at authorization time separates card-testing bursts from genuine travel." Error analysis is where most of the value is: slice validation by residual and cohort, then read the raw events behind the worst rows. Permutation importance and partial dependence (sklearn.inspection) show where the model is blind, but the candidate comes from looking at the events, not the importance chart. Automated synthesis: numeric ratios and differences, categorical crosses, aggregations, target encoding, embeddings: is a generator, not a selector; it produces hundreds of candidates that must be pruned before training.

Worked trace: a fraud model misses 12% of fraudulent authorizations. Slicing false negatives shows 40% of them are 6-12 rapid small authorizations on one card across different merchants. The model has amount, merchant category, and card age, but no card-level velocity. Candidate: distinct merchants per card in a 10-minute window, computed point-in-time. That is a domain hypothesis confirmed by error analysis, the strongest kind.

Prioritisation is expected lift per unit of serving cost, measured on a locked split with the same pipeline and seeds. I keep a triage table:

candidatemechanismPR-AUC delta (95% CI)p99 added latencysource costdecision
card velocity 10mburst detection+0.031 (0.024-0.038)6 ms (Redis)1 lookupship
amount / card agenormalisation+0.002 (-0.001-0.005)0 ms0reject, inside noise
merchant x hour crossseasonality+0.009 (0.004-0.014)0 ms0ship if drift stable
400 synthesized crosses—best +0.0040 ms0reject, multiple comparisons

The gate: a candidate ships only if its lift clears the metric's noise band (here ~0.003 PR-AUC), its marginal p99 latency fits the remaining budget (say 20 ms total, 6 ms used), and it survives grouped ablation against correlated features. Synthesized candidates get a cheap filter first (variance, mutual information, correlation with existing features) so I train tens, not hundreds.

python

scikit-learn 1.5

from sklearn.feature_selection import mutual_info_classif, SelectKBest from sklearn.inspection import permutation_importance

X_synth = build_candidates(events) # 400 columns mask = SelectKBest(mutual_info_classif, k=30).fit(X_synth, y).get_support() X_train = X_synth[:, mask]

r = permutation_importance(model, X_val, y_val, scoring="average_precision", n_repeats=10)

Failure modes and detection: leakage from synthesis (target encoding or aggregates computed before the split) shows as a candidate that lifts offline and collapses online. Detect with a time-split holdout and an online A/B. Correlated candidates that add nothing: grouped ablation. Cost creep: track feature count and p99 per model, alert on regression. Drift in synthesized features: monitor distribution and importance. Proxy discrimination: review synthesized crosses against sensitive attributes.

When not to synthesize: small data, regulated decisions needing per-feature explanation, or a latency budget already spent. Then domain hypotheses and error analysis alone are the right funnel.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design a feature platform for multiple real-time models.

Answer

Assumptions I'd state first: ~40 models, ~200 shared features, 50M entities, a 100 ms p99 decision budget, and a hard requirement that any training row can be reproduced. If those numbers are wrong the design shifts, so I'd confirm them before drawing boxes.

The core answer. A feature platform is one registry of versioned definitions compiled to two execution backends that must agree: a batch backend (Spark over Iceberg/Parquet on S3) that materializes training sets and backfills, and a streaming backend (Flink or Kafka Streams) that keeps an online store (Redis cluster) fresh. A gRPC feature server reads the online store at request time. The registry is the single source of truth; the two backends are generated from it, not hand-written twice.

Why point-in-time correctness is the whole game. Training joins labels to features as of the label's event time. Take user u1, feature purchases_7d:

event timevalue
09:003
09:585
10:056

A label stamped 10:00 must see 5. A naive join on the latest value gives 6: the model trains on data it could not have had, and offline AUC looks great while production tanks. The batch backend therefore does an as-of join on event time, not a GROUP BY on load time.

How online/offline skew arises. The two backends are different code paths: Spark windows over full history in event time; Flink windows incrementally, often in processing time, with different defaults for missing keys. Same definition, two answers. The fix is to log the online feature vector per request, recompute it offline for the same (entity, timestamp) nightly, and alert when more than ~1% of entities diverge. That comparison is the only honest skew metric.

Trade-off: precompute vs. streaming vs. on-demand.

approachfreshnessp99 fetchbackfill
batch precomputehours~2 mstrivial
streamingseconds~2 msreplay the log
on-demand (compute at request)real-time20–80 msnone needed

Deciding criterion: if the feature needs sub-second freshness and the raw events are already in the online store, compute on demand; otherwise precompute. On-demand eats the decision budget, so I'd cap it at one or two features per model.

Sizing. 50M entities × 200 features × 8 bytes ≈ 80 GB: one Redis cluster with replicas, not a per-model store. Per-model stores duplicate 80 GB forty times and drift.

Failure modes and detection.

  • Stale features: per-feature event-time watermark; alert when lag exceeds the feature's TTL (e.g. 15 min for a 5-min feature).
  • Skew: the nightly online-vs-offline diff above.
  • Backfill clobbering online: backfills write to the offline store only; online is rebuilt by replaying the stream, never by a batch overwrite.
  • Hot key on rollout: a new model warms the same entity keys; pre-warm the online store before canary and watch Redis p99.

Release path. Definitions are reviewed like code, canaried to one model, and rolled back by pinning the previous registry version: the online store keeps both versions' keys during the canary so rollback is a pointer flip, not a rebuild.

What I'd say if pushed: the registry and the skew check are the two things that make this a platform rather than forty pipelines. Everything else is plumbing.

Curated: · Written: · Reviewed:

Difficulty: Hard