Metric Definition and Implementation Questions
Defining and computing business metrics correctly: single-source-of-truth metric definitions, handling edge cases (dedup, attribution windows, timezones), and reconciling real-time vs batch metric values. Covers metric governance and translating business questions into precise, reproducible calculations. A high-frequency analytics-interview topic.
You discover two teams calculate 'conversion rate' differently: Team A divides purchases by visitors, Team B divides purchases by sessions. Design a test and a decision process to reconcile these definitions and advise which is preferable for product A's growth dashboard. Include how to present the impact of each definition using sample data.
Sample Answer
Direct answer: Run both definitions side by side on the same historical data, quantify how much they diverge and why, and recommend based on what the growth dashboard's audience actually needs to decide, not on which is more "standard."
Structured elaboration: Purchases-per-visitor (user-level) answers "what fraction of PEOPLE convert," which is the more intuitive number for growth/marketing audiences and is comparable across channels with different session behavior. Purchases-per-session (session-level) answers "how efficient is a given VISIT at converting," which is more useful for UX/product teams optimizing a specific flow, since a single highly-engaged user with many short sessions would deflate the session-level rate relative to the user-level one even with identical actual purchasing behavior.
Test and decision process:
- Compute both definitions over the same 4-8 week window and show the numeric gap (e.g., "Team A's number is 15% higher than Team B's").
- Decompose WHY they diverge: check the average sessions-per-user for converting vs non-converting users; if converters average far more sessions than non-converters, purchases-per-session will read systematically lower than purchases-per-visitor for the same underlying behavior, which is the actual mechanism producing the gap, not a data error.
- Present both to stakeholders with the mechanism explained, and recommend purchases-per-visitor (user-level) as the growth dashboard's headline number, since a growth dashboard is about reach and conversion of PEOPLE, while offering purchases-per-session as a secondary, clearly labeled metric for product/UX use.
Worked example: the three valid granularities for "conversion rate" more generally are event-level (any purchase event / any view event, which double counts repeat viewers), session-level (purchases / sessions with a qualifying view), and user-level (unique purchasers / unique visitors). Present all three on a small sample: if a product has 1,000 unique visitors generating 1,500 sessions and 100 purchases, user-level gives 10%, session-level gives 6.7%, and event-level (if visitors view multiple pages) would be lower still; showing this side by side on real numbers turns an abstract disagreement into a concrete, resolvable choice.
Trade-offs & pitfalls: Don't present this as "Team B is wrong"; both are internally consistent, correctly computed metrics answering different questions, and forcing a single company-wide "the" conversion rate risks papering over a real difference in what the two teams need. The resolution is picking ONE default for THIS growth dashboard specifically, documenting both alternatives and why the other wasn't chosen, and leaving the door open for a differently-scoped dashboard to use the other definition explicitly, by name, rather than silently.
Advanced retention: compute conditional retention where a user is considered 'retained' in week t only if they had at least N qualifying events in the prior week(s) (e.g., at least 2 opens in previous week). Provide an efficient SQL approach for cohorts up to 26 weeks that accounts for censoring and users who churn. Explain the implications for survival analysis.
Sample Answer
Direct answer: Compute conditional retention as a per-user-per-week flag that checks the PRIOR week's qualifying-event count against the threshold N (not the current week's), joined against an explicit calendar spine so weeks with zero activity appear as real zero rows rather than silently missing; handle up to 26 weeks efficiently with an incremental per-user-per-week activity table rather than re-scanning raw events per cohort; treat weeks a cohort hasn't reached yet as CENSORED (excluded), not as failures.
Structured elaboration and SQL approach (verified by executing against constructed test data in sqlite3):
WITH user_first_event AS (
SELECT user_id, MIN(event_time) AS first_event_time
FROM events GROUP BY user_id
),
weekly_activity AS (
SELECT e.user_id,
CAST((julianday(e.event_time) - julianday(f.first_event_time)) / 7 AS INTEGER) AS week_offset,
COUNT(*) AS event_count
FROM events e JOIN user_first_event f ON f.user_id = e.user_id
GROUP BY e.user_id, week_offset
),
spine AS ( -- explicit week_offset 0..25 per user, recursive CTE, so gap weeks are real 0 rows
SELECT f.user_id, s.week_offset, f.first_event_time
FROM user_first_event f
CROSS JOIN (WITH RECURSIVE seq(week_offset) AS (
SELECT 0 UNION ALL SELECT week_offset+1 FROM seq WHERE week_offset < 25
) SELECT * FROM seq) s
),
spine_with_counts AS (
SELECT sp.user_id, sp.week_offset,
COALESCE(wa.event_count, 0) AS event_count,
(julianday(sp.first_event_time) + sp.week_offset*7) <= julianday(current_date) AS is_observable
FROM spine sp
LEFT JOIN weekly_activity wa ON wa.user_id = sp.user_id AND wa.week_offset = sp.week_offset
),
with_prior AS (
SELECT user_id, week_offset, event_count, is_observable,
LAG(event_count) OVER (PARTITION BY user_id ORDER BY week_offset) AS prior_week_count
FROM spine_with_counts
),
flagged AS (
SELECT user_id, week_offset,
CASE WHEN is_observable AND prior_week_count >= 2 THEN 1 ELSE 0 END AS eligible,
CASE WHEN is_observable AND prior_week_count >= 2 AND event_count >= 1 THEN 1 ELSE 0 END AS retained
FROM with_prior
)
SELECT week_offset,
SUM(eligible) AS eligible_denominator,
SUM(retained) AS retained_numerator,
ROUND(1.0*SUM(retained)/NULLIF(SUM(eligible),0), 3) AS conditional_retention_rate
FROM flagged GROUP BY week_offset ORDER BY week_offset;
The key correction versus a naive version: prior_week_count comes from LAG(event_count) over the FULL spine (so a gap week correctly reads as 0, not a skipped row), and both eligible and retained gate on prior_week_count (week t-1), never on the current week's own count for the threshold check. week_offset is computed from julianday differences against each user's own first_event_time rather than a calendar strftime('%Y-%W', ...) bucket, which avoids the ISO-week/year-boundary discontinuity a naive week-string grouping would introduce.
Verified execution result: on a 3-user test set (user A: 3 events at signup, 0 events week 1 [churn gap], 1 event week 2; user B: 1 event at signup [below N=2], 3 events week 1; user C: 3 events at signup only 4 days before 'today', too recent to have reached week 1 yet), running this query correctly produced: week 1 has eligible_denominator=1 (user A, whose week-0 count of 3 met N=2), retained_numerator=0 (A had 0 events in week 1 itself, so did not return despite qualifying) -- correctly distinguishing 'qualified but churned' from 'qualified and retained'; user B is correctly excluded from week 1's denominator (B's own week-0 count of 1 never met N=2, so B is never eligible for week-1 conditional retention, regardless of B's high week-1 count); user C contributes to no week beyond week 0, because is_observable correctly evaluates false for weeks not yet reached given the current date -- confirming both the prior-week conditioning and the censoring logic behave as specified, not just as claimed in prose.
Censoring and churned users: a cohort from week 20 cannot yet have a valid week-26 observation if the current week is only 24; that (cohort, week) cell is excluded from eligible_denominator via is_observable, not shown as a 0% conditional-retention rate. A user who churns (their raw events simply stop) correctly reads as event_count = 0 for every subsequent spine row via the COALESCE, distinct from censoring (not yet observable), which is excluded rather than counted as a failure.
Survival-analysis implications: this curve is structurally a discrete-time survival curve conditioned on a prior-period engagement covariate: 'probability of remaining retained past week t, given the subject cleared a qualifying bar in week t-1.' The same right-censoring discipline applies: a cohort too young to have reached week t is right-censored at t, not a failure event; treating it as a failure would bias the curve downward specifically for the most recent, most interesting cohorts.
Trade-offs & pitfalls: the single most damaging bug in a homegrown version of this metric is exactly the one this correction targets: silently checking the CURRENT week's count against the threshold instead of the PRIOR week's, which computes an entirely different (and much simpler, already-well-known) metric while claiming to answer the conditional-retention question. Always unit-test the prior-week join against a synthetic fixture with a deliberate gap week before trusting the aggregate curve.
Outline a reconciliation process to validate metrics between the data warehouse and BI dashboard. Include the specific checks you would run and why each catches a different failure mode, acceptable tolerances, automated jobs, owner assignments, and a runbook describing investigative steps for mismatches.
Sample Answer
Direct answer: Run a tiered reconciliation: a cheap, fast check (row counts and sums matching between the warehouse and the dashboard's serving layer) on every refresh, and a deeper check (partition-level hashes, sampled row-by-row comparison) on a scheduled cadence or when the cheap check flags a discrepancy.
Structured elaboration:
- Tier 1, fast/every-refresh: compare total row count and a key aggregate (e.g.,
SUM(revenue)) between the warehouse table and what the dashboard's BI layer reports for the same filter; a mismatch here, even a small one, is worth flagging immediately since it's cheap to check and catches the majority of real breakages (a failed refresh, a filter applied inconsistently). - Tier 2, deeper/scheduled: partition-level hashes (a checksum per date partition) let you localize a discrepancy to a SPECIFIC day without a full row-by-row scan; once localized, a sampled row-by-row comparison on just that partition finds the actual differing rows efficiently.
- Acceptable tolerances: define a tolerance (e.g., <0.1% deviation) as expected noise from things like in-flight late-arriving data at the moment of comparison, and treat anything beyond that as investigation-worthy; a zero-tolerance rule will constantly false-alarm on inherently ok timing noise.
- Automated jobs and ownership: the tier-1 check runs as part of every dashboard refresh pipeline automatically; the tier-2 deep check runs on a schedule (e.g., nightly) and its results are owned by a named person who triages any flagged partition.
- Runbook for mismatches: first check for a timing/freshness gap (was the warehouse table refreshed after the dashboard cache?), then check for a filter/definition mismatch (does the BI tool apply an extra WHERE clause the warehouse query doesn't?), then check for an actual data-pipeline bug (a failed incremental load), in that order, since the first two are far more common than genuine data corruption.
Worked example: a 30-minute quick check comparing SELECT COUNT(*), SUM(revenue) FROM warehouse.orders WHERE date = today against the dashboard's own displayed total for today catches most real breakages immediately; a deeper check running partition-hashes over the last 90 days and flagging any day whose hash changed unexpectedly (a day that should be immutable, already fully arrived, but whose hash changed) surfaces a much rarer but more concerning class of issue: a retroactive, undocumented edit to historical data.
Trade-offs & pitfalls: Running the deep, expensive check on every refresh is wasteful; running only the cheap check misses subtle single-partition corruption that a coarse aggregate comparison can average out and hide. The tiered approach is the resolution: cheap checks catch most problems fast and cheaply, and the expensive check exists specifically to catch what the cheap one structurally cannot.
You need to compute user-level monthly revenue where some orders are refunded later. Propose a reproducible approach to attribute refunds: should refunds be subtracted from the month of original purchase, the refund date, or both? Explain trade-offs and how to implement each choice in your ETL.
Sample Answer
Direct answer: Attribute the refund to the ORIGINAL purchase month by default (so a month's revenue reflects net revenue for purchases made that month, a "vintage" view), and additionally expose a refund-date view for operational/cash-flow purposes; doing both, clearly labeled, resolves the trade-off rather than forcing a single choice that serves one audience and misleads another.
Structured elaboration:
- Attribute to original purchase month (vintage/net-revenue view): answers "how much revenue did purchases made in June ultimately generate, after all refunds," which is the more meaningful number for evaluating a specific month's SALES quality and for financial metrics like LTV that need to reflect true net value per acquisition cohort. Cost: this view changes RETROACTIVELY as later refunds come in, so "June's revenue" reported today may differ from "June's revenue" reported a month from now as more refunds land, which needs to be documented as an expected property of this view, not a bug.
- Attribute to refund month (cash/operational view): answers "how much net cash moved this month," which is what an operational cash-flow dashboard cares about; this view is stable once a month closes (refunds affect the month they occur in, not a past month), but conflates "how good was June's sales" with "how much refund activity happened in whatever month that activity landed."
- Recommendation: implement BOTH as separate, clearly named metrics (
monthly_revenue_by_purchase_vintagevsmonthly_net_cash_by_transaction_month) rather than picking one and hoping it serves every audience; most disputes here come from two teams silently assuming different conventions while calling the result by the same ambiguous name ("monthly revenue").
Worked example: a $100 purchase in June refunded in August: the vintage view attributes -$100 back to June (so June's TRUE net revenue, once fully settled, is 0 for that purchase), which is the right number for evaluating June's cohort quality; the cash view attributes -$100 to August (June showed +$100 at the time, August shows the -$100 offset), which is the right number for August's actual cash-flow statement.
Trade-offs & pitfalls: The vintage view requires the ETL to support RETROACTIVE updates to a previously-published month's number as refunds continue arriving (which needs the same versioned/data_version discipline discussed for other retroactively-adjusted metrics in this topic, so consumers can tell a "final" June number from a "still settling" one); implementing the vintage view without that retroactive-update discipline, and instead freezing June's number the day the month closes, silently produces an inaccurate vintage number that never gets corrected, which is arguably worse than not offering the vintage view at all.
Write a SQL (or pseudocode) to compute weighted conversion rate when users have unequal sampling weights (weight column in users table). The metric should return weighted_conversion_rate and an approximate standard error for confidence intervals.
Sample Answer
Direct answer: Compute the weighted conversion rate as the weight-adjusted sum of conversions divided by the weight-adjusted sum of totals, and approximate its standard error using a weighted-variance formula (a design-effect-adjusted version of the standard binomial proportion standard error), since unequal weights inflate variance beyond what an unweighted formula would suggest.
Structured elaboration and SQL/pseudocode:
WITH weighted AS (
SELECT
user_id, converted, weight,
weight * converted AS w_conv,
weight * weight AS w_sq
FROM users
),
agg AS (
SELECT
SUM(w_conv) / SUM(weight) AS weighted_conversion_rate,
SUM(weight) AS sum_w,
SUM(weight*weight) AS sum_w_sq,
COUNT(*) AS n
FROM weighted
)
SELECT weighted_conversion_rate,
-- approximate standard error via an effective-sample-size adjustment (design effect)
SQRT( weighted_conversion_rate * (1 - weighted_conversion_rate)
/ (sum_w * sum_w / sum_w_sq) ) AS approx_std_error
FROM agg;
The term sum_w * sum_w / sum_w_sq is the EFFECTIVE sample size under unequal weighting (Kish's effective sample size), which is always less than or equal to the raw count n when weights vary; using the raw n in a standard proportion standard-error formula instead of this effective sample size UNDERSTATES the true standard error whenever weights are unequal, since a few high-weight observations effectively carry more influence (and thus more sampling variability) than an equal-weighted average of the same count would.
Worked example: with weights ranging from 1 to 5 (some users representing 5x the population weight of others) and a raw sample size of 1,000, the effective sample size after this adjustment might be closer to 700-800 depending on the weight distribution's spread, meaning the true standard error is LARGER than a naive unweighted calculation on 1,000 observations would suggest; ignoring this adjustment would produce an artificially narrow, overconfident confidence interval.
Trade-offs & pitfalls: this design-effect approximation is itself an approximation (a more rigorous approach for a genuinely complex sampling design would use full survey-statistics methods, e.g., a Taylor-series linearization or replication-based variance estimator), but it is a substantial improvement over ignoring the weighting altogether, which is the far more common and more damaging mistake in practice; always confirm the weight column's actual distribution (a few extreme weights can dominate the effective-sample-size calculation) before trusting the resulting interval at face value.
Unlock Full Question Bank
Get access to all Metric Definition and Implementation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.