Metric Hierarchies & Leading/Lagging Indicators Questions
Learn the difference between lagging indicators (revenue, retention cohorts) and leading indicators (signups, feature adoption, content views). Understand that leading indicators enable faster feedback loops. Practice building metric cascades: how does North Star break down into team-level metrics? How do leading metrics predict lagging outcomes?
HardTechnical
31 practiced
For a subscription business, propose a method to forecast cohort LTV accounting for right-censoring and churn hazard rates. Discuss model choices (Kaplan-Meier, Cox proportional hazards, parametric), how to integrate recurring revenue amounts, and how to implement the pipeline combining SQL for cohort aggregation and Python for modeling.
Sample Answer
Clarify objective & data:- Forecast cohort LTV = expected discounted future revenue per user in a cohort, accounting for right-censoring (users still active) and time-varying churn hazard.- Required raw data: event-level subscriptions/charges with user_id, event_date, amount, status (cancel/active), plan info. Cohort = e.g., signup month.Model choices (tradeoffs):- Kaplan–Meier (non-parametric): good for estimating survival function S(t) (probability a user is still active at t). Handles right-censoring simply. No covariates; good baseline.- Cox proportional hazards: semi-parametric; estimates hazard ratio by covariates (plan, region, acquisition channel). Does not require baseline hazard parametric form; good when covariates matter.- Parametric survival (Weibull/Exponential/Log-logistic): gives explicit hazard function allowing extrapolation beyond observed period; useful for longer-horizon LTV. Choose after checking fit (AIC, log-likelihood, QQ plots).Integrating recurring revenue:- Model revenue as expected amount conditional on survival. Two common ways: 1) Assume fixed average revenue per active period per user (ARPA) by cohort/time-since-signup; then LTV = sum_t S(t) * E[revenue_t | active] * discount^t. 2) Model revenue with two-part model: probability of being active (survival model) * conditional payment size (regression or empirical mean). For variable billing schedules, model payment timing with recurrent-event models or treat discrete periods (monthly).SQL cohort aggregation pipeline (example):- Step 1: Build user cohort and event timeline (first_seen, last_event, event_date, amount, censored flag).- Example SQL (Postgres):- Export aggregated table: one row per user-month with revenue and censor flag (if last observed month < observation window end, mark censored).Python modeling & pipeline:1. Load aggregated table (pandas).2. Create survival table per user: duration (in months), event_observed (1 if churned, 0 if censored).3. Fit models using lifelines or scikit-survival:4. If using Cox:5. Estimate E[revenue_t | active] by cohort and month_since_signup (rolling averages or GLM for payment size):6. Compute cohort LTV:- For t=0..H: LTV = sum_t S(t) * ARPA(t) / (1+r)^(t) where S(t) from model and ARPA(t) from revenue estimates. If using Cox, S(t) is cohort-specific using covariates.7. Uncertainty & validation:- Bootstrap individuals to get CI on survival and LTV.- Backtest: fit on initial window, compare predicted vs observed retention/revenue.Practical notes:- Handle left truncation if signups before observation window.- Choose discrete period (monthly) for simplicity in BI dashboards.- Automate: SQL step writes aggregated table to a data warehouse; scheduled notebook/job runs model, writes LTV estimates to analytics DB for dashboards.- Document assumptions (discount rate, horizon, extrapolation method) in dashboards.
sql
WITH events AS (
SELECT user_id, event_date::date AS dt, amount
FROM payments
),
cohort AS (
SELECT user_id, MIN(dt) AS signup_date, DATE_TRUNC('month', MIN(dt)) AS cohort_month
FROM events GROUP BY user_id
),
timeline AS (
SELECT c.user_id, c.cohort_month, e.dt,
DATE_PART('month', AGE(e.dt, c.signup_date))::int AS month_since_signup,
e.amount
FROM cohort c JOIN events e USING (user_id)
)
SELECT cohort_month, user_id, month_since_signup,
SUM(amount) AS revenue
FROM timeline
GROUP BY cohort_month, user_id, month_since_signup;python
from lifelines import KaplanMeierFitter, CoxPHFitter
kmf = KaplanMeierFitter()
kmf.fit(durations, event_observed)
surv_probs = kmf.survival_function_at_times(range(0, horizon_months))python
cph = CoxPHFitter()
cph.fit(df[['duration','event','plan','channel']], duration_col='duration', event_col='event')
# baseline survival:
base_surv = cph.baseline_survival_
# get predicted survival for cohort covariate profilepython
# compute mean revenue per active user per month
rev_by_month = df_active.groupby('month_since_signup')['revenue'].mean()MediumTechnical
33 practiced
Design a KPI scorecard for a quarterly executive review focused on growth. Include six KPIs (mix of North Star, leading and lagging indicators), a target-setting approach, visualization ideas for progress, and governance for who owns updates.
Sample Answer
Situation: For a quarterly executive review focused on growth, build a concise KPI scorecard that highlights the North Star, leading indicators that predict near-term acceleration, and lagging metrics that show realized outcomes.Scorecard (six KPIs):1. North Star — Monthly Active Paying Users (MAPU) — core growth measure tying engagement to revenue.2. Leading — New Paid Trials Started (quarterly sum) — signals funnel inflow.3. Leading — Activation Rate (trial → paid within 30 days) — quality of onboarding.4. Lagging — Quarterly Revenue (ARR change) — realized financial growth.5. Lagging — Net Revenue Retention (NRR) — expansion + churn impact.6. Leading/Lagging hybrid — Pipeline Conversion Velocity (avg days from lead→paid) — operational efficiency.Target-setting approach:- Use historical rolling 12-quarter baseline + seasonality adjustment.- Apply SMART targets: stretch = 15% upside, expected = median growth, floor = -5% tolerance.- Calibrate leading-to-lagging translation model (e.g., 3-month conversion coefficients) so targets are internally consistent.Visualization ideas:- Single-page scorecard: KPI tiles with current vs. target, delta %, sparkline (last 8 quarters).- Waterfall for Quarterly Revenue drivers (new, expansion, churn).- Funnel visualization for trials → activation → paid with conversion rates annotated.- Trend charts with confidence bands and forecast overlay; tooltip drilldowns for cohort-level detail.Governance / ownership:- KPI owner (RACI): Product Ops owns MAPU & Activation; Marketing owns New Trials; Sales Ops owns Pipeline Velocity; Finance owns Revenue & NRR; BI Analyst (you) maintains data pipelines, dashboard, automated quarterly pack and validates metrics.- Cadence: weekly health checks by owners; formal quarterly sign-off 1 week before review. Changes to definitions require documented change request approved by Product + Finance and logged in metric glossary.This scorecard balances predictive signals with outcome measures, provides clear targets and traceable ownership to drive accountable growth discussions.
MediumTechnical
56 practiced
Outline a step-by-step plan, including Python/pandas pseudocode, to build a simple OLS regression that predicts weekly revenue from leading metrics (weekly signups, 7-day active users, feature_adoption_rate). Discuss train/test split, time-series cross-validation, feature engineering (lags/rolling), and evaluation metrics.
Sample Answer
Approach overview:1) Prepare weekly time-series dataset, create lag and rolling features, then fit OLS (with regularization if needed). Use time-aware train/test split and time-series cross-validation. Evaluate with RMSE/MAE/MAPE/R² and residual diagnostics.Pseudocode (pandas + statsmodels/sklearn):Time-series cross-validation:- Use sklearn.model_selection.TimeSeriesSplit(n_splits=5). For each split, train on earlier folds, validate on next contiguous fold; collect metrics to assess stability.Key considerations / best practices:- Avoid leakage: always shift/roll then split.- Stationarity: check trends/seasonality; include week-of-year or trend term if needed.- Multicollinearity: check VIF, drop or regularize (Ridge/Lasso) if high.- Feature selection: compare with stepwise or L1 regularization.- Residual diagnostics: plot residuals over time, autocorrelation (ACF); if autocorrelation present, consider AR terms or SARIMAX.- Deployment: retrain weekly, store model coefficients for interpretability in dashboards.Edge cases:- Sparse data / outliers: winsorize or robust regression.- Zero revenue impacting MAPE: use smape or avoid dividing by zero.
python
import pandas as pd
from sklearn.model_selection import TimeSeriesSplit
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import mean_squared_error, mean_absolute_error
import numpy as np
# load data: cols = ['week_start','revenue','signups','active_7d','feature_adopt_rate']
df = pd.read_csv('weekly.csv', parse_dates=['week_start']).sort_values('week_start').set_index('week_start')
# feature engineering: lags and rolling windows
for col in ['signups','active_7d','feature_adopt_rate']:
df[f'{col}_lag1'] = df[col].shift(1)
df[f'{col}_lag2'] = df[col].shift(2)
df[f'{col}_roll3'] = df[col].rolling(window=3).mean().shift(1) # avoid leakage
df = df.dropna()
# train/test split (time-aware)
split_date = df.index[int(len(df)*0.8)]
train = df.loc[:split_date]
test = df.loc[split_date + pd.Timedelta(days=7):]
X_cols = [c for c in df.columns if c != 'revenue']
X_train, y_train = train[X_cols], train['revenue']
X_test, y_test = test[X_cols], test['revenue']
# baseline OLS
model = LinearRegression()
model.fit(X_train, y_train)
pred = model.predict(X_test)
# evaluation
rmse = mean_squared_error(y_test, pred, squared=False)
mae = mean_absolute_error(y_test, pred)
mape = (np.abs((y_test - pred) / y_test)).mean() * 100
r2 = model.score(X_test, y_test)HardSystem Design
52 practiced
Design an experiment-validation pipeline that ensures leading metrics used as early signals are robust. Include pre-registration, automated checks for metric correctness inside the experiment platform, bias detection (non-random assignment), and post-experiment validation comparing early signals with lagging outcomes.
Sample Answer
Requirements & constraints:- Verify leading metrics (early signals) are reliable predictors of lagging outcomes.- Integrate with experiment platform, BI stack (warehouse, Looker/Tableau), and version control.- Automate checks, detect non-random assignment, support pre-registration, and enable post-hoc validation.High-level architecture:Experiment Platform → Event/feature tracking → Data Warehouse (partitioned) → Validation Pipeline (Airflow) → BI Layer (Looker/Tableau) + AlertsCore components & responsibilities:1. Pre-registration service- Template (hypothesis, primary/secondary metrics, analysis plan, minimum detectable effect, sample size, stop rules).- Store signed JSON/YAML in Git or DB with timestamp and experiment id.2. Automated metric-correctness checks (run at ingestion & periodically)- Schema & cardinality validation, definitions matched vs canonical metric registry.- Sanity checks: plausible ranges, monotonicity, duplicate events.- Delta-checks vs baseline: abrupt jumps trigger warnings.- Implemented as SQL tests + dbt tests executed in Airflow.3. Bias / randomization detection- Randomization audit: check balance on covariates (user age, geography, pre-period metrics) using standardized mean differences; flag SMD > 0.1.- Assignment drift detection: time-series of assignment ratios; detect correlation with external signals.- Entropy checks for bucketing keys; verify hash uniformity.4. Post-experiment validation- Compare early signals to lagging outcomes via pre-registered models: correlation, precision/recall for binary outcomes, calibration plots.- Build uplift models and mediation analysis to assess whether early metric mediates final outcome.- Produce automated report: pass/fail, effect sizes, CI, power post-hoc, and recommended action (promote, iterate, discard).Data flow:- Events → warehouse (cdc) → dbt models produce canonical metrics → validation DAG runs tests, bias audits → results stored; dashboard auto-updates; slack/email alerts for failures.Scalability & reliability:- Partitioned tables, incremental dbt runs, parallel Airflow tasks.- Keep metric registry small-good-practice; sample-based audits for very large experiments.Trade-offs:- Strict pre-registration reduces flexibility—allow versioned amendments with justification.- Automated checks may produce noisy alerts; tune thresholds and include human review.Metrics of success:- Reduction in promoted features that later fail (tracking over time), % experiments with balanced assignment, time-to-detect metric-definition drift.This pipeline ensures early signals are validated, randomization integrity is enforced, and decisions are grounded in reproducible, pre-registered analysis.
HardTechnical
28 practiced
A core leading metric's baseline shifted immediately after a product redesign. How would you detect whether this is metric drift versus true behavioral change, quantify impact on historical comparisons, and update dashboards and metric cascades to preserve business continuity? Outline SQL checks, statistical tests, and governance steps.
Sample Answer
Clarify scope and window: confirm redesign launch timestamp and affected cohorts (platform, country, user segments). Aim: determine if observed baseline shift is metric drift (data/collection change) or true behavioral change, quantify the effect size for historical comparisons, and update dashboards/metrics with governance to preserve continuity.Detection — SQL checks (examples)- Verify event counts and data completeness pre/post:- Check instrumentation changes (schema/etl): compare column existence/types:- Compare sampling or pipeline flags:Statistical tests & change-point detection- Aggregate metric by user-day pre/post window (use at least 2–4 weeks):- Test distribution shift: Kolmogorov–Smirnov (KS) to detect distributional change; Mann–Whitney U if non-parametric; two-sample t-test if approx normal.- Test sudden change: Bayesian online change point detection or CUSUM to detect abrupt shifts.- Example: compute user-level metric M; run: - KS test between pre and post M samples - Bootstrap difference-in-means to get 95% CI and p-value- If there’s confounding (e.g., different user mix), run stratified tests or propensity-score weighting / regression: - logistic or linear regression: metric ~ post_flag + covariates (device, country, new_ui_flag). If coefficient on post_flag significant after controls, evidence for behavioral change.Quantify impact on historical comparisons- Compute absolute and relative lift and uncertainty:- Use bootstrap or regression to estimate adjusted lift and 95% CI.- Backfill strategy: produce two views — "as-observed" and "adjusted-for-comparison" (apply adjustment factor or model-based normalization). Document conversion factor and uncertainty for historical trend lines.Dashboard & metric cascade updates- Short term: add annotations and toggle to switch between "pre-merge" and "post-merge" baselines; keep both series visible.- Implement versioned metrics (metric_v1, metric_v2) and a canonical metric view that applies normalization when comparing across the redesign boundary.- Update alerts thresholds: avoid noisy alerts by temporarily relaxing thresholds or using anomaly-detection that is redesign-aware.- Update downstream calculations (OKRs, funnels): evaluate propagated impact and recalculate or annotate historical targets.Governance steps- Runbook: create an incident runbook for redesign launches (instrumentation checklist, smoke tests, sample queries).- Stakeholder sign-off: require PM/Engineering/Data Engineering confirmation that instrumentation changed or not.- Data contract & schema registry: record changes, add migration notes and expected behavior.- Audit and validation: schedule 1-day smoke, 1-week sanity, and 30-day review with owners; publish a change log and “what changed” doc.- Permanent controls: add post-deploy monitoring dashboards (event volume, null rates, sample rates) and automated alerts to detect future drift.Example end-to-end sequence1. Run SQL completeness checks + instrumentation diff.2. If instrumentation changed: classify as metric drift, stop using post-launch data for comparisons until backfill/adjustment; perform backfill or map new fields.3. If instrumentation unchanged: run KS + bootstrap/regression to quantify true behavioral change; produce normalized historical comparison and update dashboards with annotations and versioned metrics.4. Apply governance: communicate, document, and add monitoring to prevent recurrence.This approach combines concrete SQL validation, robust statistical testing, transparent dashboarding, and governance to ensure business continuity and trust in metrics.
sql
SELECT date(day) AS day,
COUNT(*) AS events,
COUNT(distinct user_id) AS users,
COUNT(case when event_prop IS NULL then 1 end) AS null_props
FROM events
WHERE event_name = 'target_event'
AND day BETWEEN '2025-01-01' AND '2025-02-28'
GROUP BY day
ORDER BY day;sql
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name='events' AND column_name IN ('event_prop','platform');sql
SELECT day, SUM(CASE WHEN sampled=1 THEN 1 ELSE 0 END) AS sampled,
SUM(CASE WHEN processed=0 THEN 1 ELSE 0 END) AS failed
FROM events_raw GROUP BY day;sql
-- user-level metric averages
SELECT 'pre' AS period, AVG(M) AS mean_m, STDDEV_POP(M) AS sd, COUNT(*) AS n FROM user_metrics WHERE day < '2025-01-15'
UNION
SELECT 'post', AVG(M), STDDEV_POP(M), COUNT(*) FROM user_metrics WHERE day >= '2025-01-15';Unlock Full Question Bank
Get access to hundreds of Metric Hierarchies & Leading/Lagging Indicators interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.