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're asked to create a clear, auditable definition for the metric 'Active User (DAU)' for an e-commerce web and mobile product used by both signed-in and anonymous users. Specify: the user identifier(s) to use, which events count as activity, the time window, deduplication rules (e.g., same user across devices), how to treat bots/test accounts, and how to document the definition so stakeholders can reproduce it.
Sample Answer
Direct answer: Define DAU as the count of distinct canonical users (coalescing signed-in user_id with an anonymous anon_id where no login exists) with at least one qualifying activity event in a UTC calendar day, after excluding bots and internal/test accounts and after deduplicating a user's activity across web and mobile into one canonical identity.
Structured elaboration, as the documentation would read:
- User identifier: use
user_idwhen signed in; when anonymous, use a durableanon_id(cookie/device ID), and if the same person later signs in, that is a KNOWN identity-merge event, not a new user, so historical anonymous activity should be attributable to the merged identity for retention analyses (though for a same-day DAU count, this rarely changes the number, since it's about distinctness within one day). - Qualifying events: name the specific event types that count (e.g.,
page_view,search,add_to_cart,purchase) rather than "any event," because some events (heartbeat pings, background sync) are not genuine activity and would inflate the count if included by accident. - Time window: a UTC calendar day, explicitly, with a documented note that this differs from "the user's local day" (see the timezone trade-off below).
- Cross-device dedup: if a signed-in user is active on both web and mobile the same day, they count once; this requires the canonical-identity join described above, keyed on
user_id, not on device or session. - Bots/test accounts: exclude via an explicit
is_botflag or a maintained internal-account allowlist, reviewed periodically since bot patterns change. - Documentation for reproducibility: publish the exact event-type list, the identity-merge rule, and one worked day's number with a manual audit trail so a stakeholder can re-derive it by hand on a small sample.
Worked example: a user signed in on mobile at 9am (a search event) and, later that same UTC day, browses anonymously on a shared work computer (a page_view event under a different anon_id, no login) would, under a naive identifier-per-row count, appear as two distinct "users" that day. The canonical definition above only merges them if there's an actual identity-linking signal (e.g., the anon_id was later associated with that account via a login on that device); absent such a signal, they are correctly counted as two different activity instances because the system genuinely cannot tell they're the same person from data alone; documenting that limitation explicitly (rather than silently overcounting or undercounting) is part of an auditable definition.
Trade-offs & pitfalls: UTC day boundaries are simpler to implement and keep partitioning simple, but they split a user's late-evening local activity across two UTC calendar dates for large parts of the world, understating single-day engagement for those users; user-local-day boundaries are more accurate to lived experience but require a timezone dimension on every event and complicate partition pruning. Pick one, document the choice, and don't silently switch mid-series (a switch changes the historical trend line's meaning without warning).
You must choose between COUNT(DISTINCT user_id) and approximate distinct algorithms like HyperLogLog (HLL) for unique-user counts in dashboards. Explain the trade-offs in accuracy, memory and compute cost, mergeability across partitions, and scenarios where HLL is appropriate. Provide thresholds or heuristics you would use in a production environment.
Sample Answer
Direct answer: Use exact COUNT(DISTINCT user_id) when correctness at exact precision genuinely matters (financial reporting, small-to-moderate data volumes) and switch to HyperLogLog (HLL) when the query needs to merge distinct counts ACROSS many partitions cheaply, or when the exact computation's memory/compute cost becomes prohibitive at scale, accepting a small, bounded error (typically under ~2%) in exchange.
Structured elaboration:
- Accuracy: exact
COUNT(DISTINCT)has zero error by definition; HLL trades a small, characterizable relative error (tunable via its precision parameter, at the cost of more memory for lower error) for speed and mergeability. - Memory/compute cost: exact distinct counting over a huge cardinality requires materializing (conceptually) every distinct value seen, which can be memory- and shuffle-heavy in a distributed engine; an HLL sketch uses a small, FIXED amount of memory (a few KB) regardless of how many distinct values it's summarizing, which is the core efficiency win.
- Mergeability: this is the decisive practical advantage of HLL: two HLL sketches (e.g., one per day) can be MERGED into a combined sketch representing the union's distinct count, without re-scanning either day's raw data; an exact
COUNT(DISTINCT)cannot be merged this way at all (you cannot combine two days' exact distinct-user counts into a 2-day distinct count without re-scanning both days' raw user IDs together, since the same user could appear in both days and a naive sum would double count). - When HLL is appropriate: high-cardinality unique-count dashboards refreshed frequently across many partitions/dimensions (e.g., "unique visitors per hour, mergeable up into daily/weekly/monthly totals" without rescanning raw data for each rollup level); NOT appropriate when the number feeds an audited financial or legal report, where the small approximation error, however characterized, is unacceptable.
- Production heuristic: a reasonable starting rule is to use exact
COUNT(DISTINCT)below roughly tens of millions of distinct values per query where compute cost is still acceptable, and switch to HLL above that threshold or whenever the SAME dashboard needs the distinct count rolled up across many overlapping dimension combinations (which would otherwise require re-scanning raw data for every combination).
Worked example: a "unique visitors" metric computed hourly and rolled up to daily/weekly views is a strong HLL candidate: maintain an hourly HLL sketch per relevant dimension, and compute daily/weekly unique visitors by MERGING the relevant hourly sketches, rather than re-scanning raw events at every rollup level; a monthly financial "unique paying customers" number feeding revenue recognition should stay exact.
Trade-offs & pitfalls: The mergeability property is the real reason to reach for HLL, more than the raw compute savings on a single query; if a use case never needs to merge sketches across partitions (a one-off query on a single day's data), the memory/compute case for HLL over exact COUNT(DISTINCT) is much weaker, and the added complexity (a less-familiar data structure, an approximation error to explain to stakeholders) may not be worth it.
Write SQL to compute time-decay multi-touch attribution over the last 30 days. Schema: touches(user_id, touch_time TIMESTAMP, channel STRING, is_conversion BOOLEAN, conversion_time TIMESTAMP). Assign weight to each touch for a conversion as exp(-lambda * days_before_conversion) and normalize weights per conversion. Provide the SQL approach and explain normalization.
Sample Answer
Direct answer: Weight each touch for a conversion by exp(-lambda * days_before_conversion), then normalize by dividing each touch's raw weight by the sum of raw weights across all touches for that same conversion, so the weights for one conversion always sum to 1.
Structured elaboration and executable SQL:
WITH weighted AS (
SELECT t.user_id, t.channel, t.touch_time, t.conversion_time,
EXP(-:lambda * (julianday(t.conversion_time) - julianday(t.touch_time))) AS raw_weight
FROM touches t
WHERE t.is_conversion = true AND t.conversion_time IS NOT NULL -- is_conversion flags which touch rows anchor a conversion
AND t.touch_time >= t.conversion_time - INTERVAL '30 days'
),
totals AS (
SELECT user_id, conversion_time, SUM(raw_weight) AS total_weight
FROM weighted GROUP BY user_id, conversion_time
)
SELECT w.channel, w.raw_weight / t.total_weight AS normalized_weight
FROM weighted w
JOIN totals t ON t.user_id = w.user_id AND t.conversion_time = w.conversion_time;
Normalization matters because the raw exponential weights alone don't sum to a meaningful "1 conversion's worth of credit"; without dividing by the per-conversion total, a conversion with many touches would distribute MORE than one conversion's worth of credit across channels in aggregate.
Worked example (executed): for one conversion with three touches: display 9 days before conversion, search 5 days before, email 1 day before, with lambda=0.3, running this exact query in SQLite gives raw weights of approximately 0.067 (display), 0.223 (search), 0.741 (email), normalizing to about 6.5%, 21.6%, and 71.8% respectively (they sum to 1.0 after normalization, confirmed by execution). Email, the most recent touch, correctly receives the largest share of credit, and the shares sum to exactly one conversion's worth.
Trade-offs & pitfalls: The choice of lambda directly controls how sharply recency is rewarded: a small lambda approaches even-split multi-touch (all touches matter comparably regardless of recency), while a large lambda approaches last-touch (only the most recent touch gets meaningful credit); lambda should be a documented, deliberately chosen parameter, not a default nobody remembers picking. The 30-day lookback window is itself an attribution-window choice (a touch 31 days before conversion gets zero credit, not a small nonzero weight), and that hard cutoff should be stated alongside the decay function, since together they define the full attribution model, not the decay formula alone.
You are designing a minimal 'metrics' registry table to store canonical metric definitions and metadata for cross-team use. Provide a sample schema (columns and types) and explain three additional fields you would add to support lineage, ownership, and versioning. You may use SQL-style column definitions in your answer.
Sample Answer
Direct answer: A minimal metrics registry table needs, at least: a stable metric ID, canonical name, plain-language definition, the calculation SQL/reference, an owner, and a last-updated timestamp; add lineage (upstream table dependencies), a version number, and a status field (draft/approved/deprecated) to make it production-grade.
Structured elaboration, sample schema:
CREATE TABLE metric_registry (
metric_id TEXT PRIMARY KEY,
canonical_name TEXT NOT NULL,
plain_definition TEXT NOT NULL,
calculation_ref TEXT NOT NULL, -- pointer to the versioned SQL/model, not a copy of it
owner_team TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('draft','approved','deprecated')),
created_at TIMESTAMP NOT NULL,
last_updated_at TIMESTAMP NOT NULL,
version INTEGER NOT NULL DEFAULT 1
);
Three additional fields for lineage, ownership, and versioning:
upstream_dependencies(lineage): an array or a linked table listing the source tables/models this metric reads from, so a schema change upstream can be traced to every metric it might silently break, before the breakage is discovered by a confused stakeholder.approver/last_reviewed_by(ownership, distinct fromowner_team): the specific individual who last signed off on the current definition, since a team-level owner alone doesn't tell you WHO to ask when the definition seems wrong, and accountability diffuses without a named individual.superseded_by/deprecated_at(versioning): when a metric is deprecated in favor of a new definition, this field points forward to its replacement, so a consumer who finds the old, deprecated entry is routed to the current one rather than left with a dead end.
Worked example: a weekly_active_users entry: metric_id='wau_v2', canonical_name='Weekly Active Users', plain_definition='distinct users with >=1 qualifying event in the trailing 7 days, excluding bots', calculation_ref='dbt://models/metrics/wau.sql', owner_team='product-analytics', status='approved', upstream_dependencies=['events','bot_allowlist'], superseded_by=NULL (this is the current version; an OLDER wau_v1 entry would have status='deprecated' and superseded_by='wau_v2').
Trade-offs & pitfalls: Storing calculation_ref as a POINTER to the versioned SQL model (not a copy of the SQL text inline in the registry) avoids the two ever drifting apart; if the registry entry and the actual running pipeline logic diverge because someone updated one without the other, the registry becomes actively misleading rather than merely incomplete, which is worse than having no registry at all.
Propose an approach to attribute conversions across devices using deterministic and probabilistic matching. Identify the signals you would use for each approach and why, outline matching algorithms, confidence scoring, privacy implications, and validation methods for matching accuracy.
Sample Answer
Direct answer: Use deterministic matching (a shared login, a hashed email, an explicit account link) wherever it's available, since it's exact and needs no confidence scoring; fall back to probabilistic matching (IP + user-agent proximity, timing patterns) only for the remaining unmatched traffic, always attaching a confidence score so downstream consumers can decide their own tolerance for false merges.
Structured elaboration:
- Deterministic signals: a login event linking a device to a
user_idis the strongest signal (a real, authenticated identity link); a hashed email appearing on two devices (e.g., the same email used at checkout on both) is a strong secondary deterministic signal, since hashing preserves exact-match capability while limiting raw PII exposure. - Probabilistic signals: IP address + user-agent pattern proximity within a short time window suggests, without proving, the same physical household/device; probabilistic matches should always carry a confidence score (e.g., a Jaccard-similarity or logistic-regression-based match probability) rather than a binary yes/no, because unlike deterministic matches, these are inherently uncertain.
- Matching algorithm structure: run deterministic matching FIRST across the whole dataset (cheap, exact, resolves the majority of cases in most consumer products where login is common); only feed the REMAINING unmatched pairs into the probabilistic matcher, which is more expensive and less certain, so it's applied only where it's actually needed.
- Confidence scoring: publish the score alongside the match, and let downstream consumers set their own threshold (e.g., a high-stakes personalization decision might require a high-confidence match; a low-stakes marketing-frequency-capping use case can tolerate a looser threshold), rather than baking one global threshold into the matching pipeline itself.
- Privacy implications: hash PII (emails, phone numbers) before they ever enter the matching pipeline, never match on raw PII directly; document a retention policy for match data, since identity-linking data is itself sensitive regardless of whether the underlying PII was hashed.
- Validation: hold out a sample of KNOWN true matches (e.g., users who explicitly logged into the same account on two devices, so the ground truth is certain) and measure the probabilistic matcher's precision/recall against that held-out ground truth, rather than assuming the matcher's internal confidence scores are well-calibrated without ever checking.
Worked example: a user on mobile logs in (deterministic match to user_id=42); the same user later browses anonymously on a shared home Wi-Fi network from a laptop; a probabilistic matcher flags the laptop session as a candidate match to user_id=42 at 70% confidence based on IP+timing proximity, but a SIBLING'S laptop session on the same Wi-Fi network the same evening might ALSO get flagged at 65% confidence, illustrating the real risk of a household-sharing false merge that a purely deterministic approach would never produce and never need to.
Trade-offs & pitfalls: The biggest risk with probabilistic matching is a shared-device/shared-network false merge (multiple real people mistaken for one), which silently UNDERCOUNTS true unique users; validating against a held-out deterministic ground-truth sample is the only way to catch this systematically rather than anecdotally, and that validation should be repeated periodically as network/device-sharing patterns shift.
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.