Conversion Funnel Optimization Questions
Analyzing and improving a bounded, ordered conversion path: mapping the sequence of steps a user takes from acquisition through one terminal conversion or activation event (signup, first purchase, first paid order, trial-to-paid, onboarding to first-success), computing step-to-step and overall conversion rates and drop-off, and diagnosing where and why users fall out. Covers the SQL and query techniques for computing funnel metrics at scale (stage-by-stage conversion tables, time-to-conversion and time-to-first-value, cohort LTV measured within a funnel window, path analysis across non-linear user journeys, event instrumentation and data-quality practices for funnel tracking), attribution modeling for crediting conversions across channels and touchpoints (first-touch, last-touch, linear, time-decay, Markov-chain, and Shapley-value approaches) and customer acquisition cost by channel, and the experiment design and statistics used to validate funnel changes (A/B and multi-armed-bandit test design, sample-size and power calculations, quasi-experimental methods such as difference-in-differences and synthetic control when randomization is not possible, and testing whether a single funnel-stage drop is a real, statistically significant shift rather than noise). Also covers diagnosing UX and flow friction that causes drop-off (checkout, signup, and onboarding friction points) and prioritizing a program of funnel-improvement experiments (impact and effort frameworks such as RICE or ICE, guardrail metrics, roadmap sequencing). Distinct from User Retention and Engagement, which covers what an already-converted or already-activated user does afterward: repeat usage over time, cohort retention curves, DAU/WAU/MAU, churn, and reactivation. A question belongs here if it concerns a user's first, bounded pass toward one conversion or activation event; it belongs to User Retention and Engagement if it concerns recurring behavior after that event. General-purpose rolling-window anomaly and change-point detection techniques (CUSUM, Bayesian change-point, seasonality-aware baselines) for monitoring any metric over time belong to the companion topic Advanced SQL: Metric Monitoring, Anomaly Detection, and Data Correctness at Scale, not here.
Design a data-driven multi-touch attribution model for channel credit allocation. Compare heuristic (linear/time-decay), regression-based (e.g., logistic regression or conversion modeling), Shapley value, and Markov chain approaches. Discuss data needs, computational cost, interpretability, and which you would recommend for quarterly marketing reports versus real-time optimization.
Sample Answer
Direct answer
No single attribution model is right for every use case, so the actual deliverable is a decision: heuristic models (linear, time-decay) are cheap, transparent, and good enough for a quarterly report a non-technical stakeholder needs to trust at a glance; regression-based and Shapley-value models are data-driven and defensible under scrutiny but expensive to build and maintain, appropriate when real budget decisions ride on channel comparisons; and Markov chain modeling sits in between, data-driven and computationally tractable enough to refresh frequently, which makes it the strongest candidate for near-real-time optimization despite giving up some of Shapley's theoretical guarantees.
Structured elaboration
| Approach | Data needs | Computational cost | Interpretability |
|---|---|---|---|
| Heuristic (linear / time-decay) | Just the touchpoint sequence and timestamps per conversion; no conversion outcome modeling required at all. | Trivial, a single pass computing weights per touch, no fitting or optimization step. | Highest. The rule ("every touch gets equal credit" or "credit decays exponentially with recency") is stated in one sentence and anyone can verify a specific credited number by hand. |
| Regression-based (e.g. logistic regression over touch sequences) | Needs converted AND non-converted (null) paths, encoded as features (channel presence/count/recency per path), and a large enough sample per channel combination for the model to estimate stable coefficients. | Moderate: a single model fit (seconds to minutes depending on feature count and data volume), but the feature engineering and encoding work up front is real, ongoing effort. | Moderate. Coefficients give a directional, statistically-grounded read on each channel's association with conversion, but "association" is not causal, and interaction effects between channels are only visible if explicitly modeled. |
| Shapley value | Needs the same converted/non-converted path data as regression, but computes credit game-theoretically: for every possible subset (coalition) of channels, the marginal contribution of adding one more channel to that subset, averaged over all orderings. | Highest. Exact computation is O(2k) in the number of distinct channels k, since every subset must be evaluated; in practice this is only tractable with k kept small (channel-group-level, not raw campaign-level) or approximated via Monte Carlo sampling over orderings. | High once computed: Shapley values have a clean theoretical guarantee (they are the unique allocation satisfying efficiency, symmetry, and additivity axioms from cooperative game theory), but the computation itself is opaque to a non-technical audience compared to a heuristic rule. |
| Markov chain | The touchpoint sequence and outcome (Convert or Null) per user, used to estimate a transition matrix empirically; no separate feature engineering step, the sequence data itself is the input. | Moderate: building the transition matrix is a single pass over the data, and the core computation (a matrix inversion over the transient states, detailed below) is O(k3) in the number of transient states k, fast enough to refresh on a daily or even more frequent cadence for a realistic channel count. | Moderate to high: the transition matrix itself is directly inspectable (a stakeholder can read "40% of Email-touched users next go to Social" directly off the matrix), and the removal-effect credit it produces has an intuitive causal-style framing ("credit reflects how much conversion probability would drop without this channel"), even though it still relies on the first-order Markov assumption. |
Recommendation. For a quarterly marketing report, where the audience needs to trust the number quickly and the cost of a slightly less statistically rigorous credit split is low, a heuristic model (time-decay, since it at least reflects recency better than pure linear credit) is the right default: it is fast to produce, easy to explain and defend in the room, and does not require maintaining a fitted model across reporting periods. For real-time bidding or budget-reallocation optimization, where the credit split directly drives a repeated, automated decision and the cost of a systematically biased heuristic compounds every cycle, the Markov chain approach is the strongest fit: it is genuinely data-driven (unlike the heuristic), fast enough to refresh on the cadence an optimization loop needs (unlike Shapley at meaningful channel-set sizes), and its removal-effect credit responds to real shifts in user behavior automatically as the transition matrix is re-estimated. Regression-based and Shapley-value models are best reserved for a periodic, deeper validation exercise, run quarterly or less often, to check whether the operational Markov-based credit split still roughly agrees with a more rigorous method, rather than as the always-on production system themselves.
Markov chain attribution, in depth
The model. Represent every distinct marketing channel as a state, plus a Start state and two absorbing states, Conversion and Null (drop-off without converting). Estimate the transition matrix P directly from observed touchpoint sequences: Pij is the empirical fraction of times a user at state i moved next to state j.
Absorption probability via the fundamental matrix. Partition P into the transient states (Start plus every channel) and the two absorbing states, giving the standard block form
P=(Q0RI)where Q is the transient-to-transient sub-matrix and R is the transient-to-absorbing sub-matrix. The fundamental matrix
N=(I−Q)−1gives, entry by entry, the expected number of visits to each transient state before absorption, and
B=NRgives, for every transient state, the probability of eventually being absorbed at Conversion versus Null. The overall baseline conversion probability is B's entry for the Start state and the Conversion column.
Removal effect: turning absorption probability into channel credit. To credit channel c, rebuild the transition matrix with every transition that would have gone INTO c redirected instead to Null (the touch simply does not happen, so that user falls out of the funnel at that point), recompute the Start-state conversion probability under this modified chain, and take the difference from the baseline. Formally, if p∗ is the baseline conversion probability and p−c∗ is the conversion probability with channel c removed, channel c's removal effect is p∗−p−c∗. Normalizing every channel's removal effect to sum to 1 and multiplying by the total observed conversions gives each channel's credited conversion count, which is the standard way this method is applied in practice.
Sparse-channel handling. A channel with very few observed touches produces an unstable transition-probability estimate (a handful of paths through it can push its outgoing probabilities to extreme, noisy values), and removing it can produce an unrealistically large or small removal effect purely from sampling noise. Two practical fixes: apply additive (Laplace-style) smoothing to the raw transition counts before normalizing into probabilities, which pulls a sparse channel's estimated transitions toward the overall average rather than trusting a handful of observations completely, or group genuinely low-volume channels into a single "Other" state before estimating the chain at all, sacrificing per-channel granularity for a materially more stable estimate on the channels that matter.
Algorithmic complexity. Building the transition-count matrix is a single linear pass over the touchpoint data, O(total touches). The fundamental-matrix computation is a k×k matrix inversion, O(k3) with standard dense linear algebra, where k is the number of transient states (channels plus Start); computing the removal effect for every channel means repeating this inversion once per channel, so the full removal-effect attribution run is O(k4) in the worst case. This stays entirely practical for a realistic channel count (tens of channels, not thousands), which is exactly why the Markov approach can be refreshed far more often than a Shapley computation whose cost grows exponentially in the same k.
Worked example
Ten pinned synthetic user paths across three channels (Search, Social, Email), actually computed with numpy linear algebra rather than hand-derived:
import numpy as np
paths = [
(["Search", "Social"], "Conversion"), (["Search"], "Conversion"),
(["Social", "Email"], "Conversion"), (["Email"], "Conversion"),
(["Search", "Social"], "Null"), (["Social"], "Null"),
(["Search", "Email"], "Conversion"), (["Email", "Social"], "Conversion"),
(["Search"], "Null"), (["Email"], "Null"),
]
STATES = ["Start", "Search", "Social", "Email", "Conversion", "Null"]
idx = {s: i for i, s in enumerate(STATES)}
n = len(STATES)
counts = np.zeros((n, n))
for seq, outcome in paths:
prev = "Start"
for ch in seq:
counts[idx[prev], idx[ch]] += 1
prev = ch
counts[idx[prev], idx[outcome]] += 1
P = counts.copy()
row_sums = P.sum(axis=1, keepdims=True)
for i in range(n):
P[i, i] = 1.0 if row_sums[i] == 0 else P[i, i]
if row_sums[i] > 0:
P[i] = P[i] / row_sums[i]
def conversion_probability(P):
transient = [i for i, s in enumerate(STATES) if s not in ("Conversion", "Null")]
absorbing = [idx["Conversion"], idx["Null"]]
Q = P[np.ix_(transient, transient)]
R = P[np.ix_(transient, absorbing)]
N = np.linalg.inv(np.eye(len(transient)) - Q)
B = N @ R
return B[transient.index(idx["Start"]), 0]
baseline = conversion_probability(P)
print(f"Baseline P(eventually Convert | Start) = {baseline:.4f}")
def remove_channel(P, channel):
P2 = P.copy()
c = idx[channel]
for i in range(n):
if i != c and P2[i, c] > 0:
P2[i, idx["Null"]] += P2[i, c]
P2[i, c] = 0.0
return P2
removal_effects = {}
for channel in ["Search", "Social", "Email"]:
p_removed = conversion_probability(remove_channel(P, channel))
effect = baseline - p_removed
removal_effects[channel] = effect
print(f"Remove {channel}: P(Convert) drops to {p_removed:.4f}, removal effect = {effect:.4f}")
total_conversions = sum(1 for _, outcome in paths if outcome == "Conversion")
sum_effects = sum(removal_effects.values())
print()
print("Normalized channel credit (removal effect / sum of removal effects):")
for channel in ["Search", "Social", "Email"]:
norm = removal_effects[channel] / sum_effects
credited = norm * total_conversions
print(f"{channel}: normalized credit = {norm:.4f} -> credited conversions = {credited:.2f}")
Output (actually executed):
Baseline P(eventually Convert | Start) = 0.6000
Remove Search: P(Convert) drops to 0.3208, removal effect = 0.2792
Remove Social: P(Convert) drops to 0.3400, removal effect = 0.2600
Remove Email: P(Convert) drops to 0.2600, removal effect = 0.3400
Normalized channel credit (removal effect / sum of removal effects):
Search: normalized credit = 0.3175 -> credited conversions = 1.91
Social: normalized credit = 0.2957 -> credited conversions = 1.77
Email: normalized credit = 0.3867 -> credited conversions = 2.32
The baseline conversion probability of 0.6 exactly matches the raw empirical rate (6 of the 10 pinned paths converted), which is the expected sanity check for a first-order Markov chain estimated directly from this data. Email receives the highest removal effect and the highest credited-conversion share (2.32 of the 6 total conversions), consistent with Email appearing in three of the six converting paths including as the sole touch in one of them, while still discounting for the fact that Search and Social also carry real, non-zero contribution.
Trade-offs and pitfalls
- The Markov chain's removal effect is a modeled counterfactual estimated from observational data, not a causal experiment; a channel that happens to be touched mostly by users who were already likely to convert for unrelated reasons will still show a large removal effect, since the model has no way to separate correlation from causation on its own.
- Shapley's exponential cost is a real, not theoretical, blocker at scale: attributing credit across dozens of individual campaigns rather than a handful of channel groups makes exact Shapley infeasible, and Monte Carlo approximation trades exactness for tractability in a way that needs its own convergence checking, which is easy to skip under time pressure.
- A common wrong turn is picking one model and reporting its output as ground truth rather than as one estimate among several reasonable ones; running two different models (a heuristic and the Markov chain, for example) side by side and treating a large disagreement between them as a signal worth investigating, rather than picking whichever number is more convenient, is closer to how a senior analyst actually uses these outputs.
- The first-order Markov assumption (the next state depends only on the current state, not the full history) is a real approximation; a channel that behaves very differently depending on what came before it (a retargeting ad that only works after an initial organic visit, for instance) will not be captured correctly without moving to a higher-order chain, which increases both data requirements and the state-space size sharply.
Define a conversion funnel for signup → onboarding → activation → paid subscription for a consumer app. Provide clear definitions for each funnel step, sample SQL-friendly column/event names you would rely on, and describe how you would compute step-to-step conversion rates and overall funnel conversion.
Sample Answer
Direct answer
A signup to paid funnel for a consumer app is signup (account created), onboarding (the user completes the guided setup that makes the product usable), activation (the user reaches the product's core "first value" moment), and paid (the user converts to a paying plan). Model each step as a distinct, timestamped event tied to a user_id, then compute conversion as the ratio of distinct users reaching one step over the distinct users who reached the step before it, and overall conversion as the final step's users over the first step's users.
Structured elaboration
Step definitions, one clear sentence each:
- Signup: the user submits valid credentials (email/password, or an OAuth provider) and an account record is durably created. This is the funnel's entry point; everything downstream is measured relative to it.
- Onboarding: the guided, in-product setup that gets a new account into a usable state (verifying email, completing a profile, connecting an integration, picking a workspace). Onboarding is a checkpoint of readiness, not yet a sign the user has gotten value.
- Activation: the user reaches a defined "aha moment," the first meaningful use of the product's core value proposition (creating a first project, sending a first message, importing a first dataset). This is the terminal event of the funnel's bounded first pass: what happens to the user AFTER this point (do they come back next week, do they stay active) is retention territory, not this funnel.
- Paid: the user converts to a paying subscription or one-time purchase.
Sample SQL-friendly column and event names:
| Step | Event name | Key event properties |
|---|---|---|
| Signup | signup_completed | user_id, signup_ts, signup_channel |
| Onboarding | onboarding_completed | user_id, onboarding_ts, onboarding_variant |
| Activation | activation_completed | user_id, activation_ts, activation_action |
| Paid | subscription_started | user_id, paid_ts, plan_id, mrr_amount |
These sit naturally in a generic events table, events(user_id BIGINT, event_name VARCHAR, event_timestamp TIMESTAMP, properties JSON), one row per event, with event_name taking one of the four values above (or, for onboarding, optionally a finer-grained onboarding_step_completed event with a step_name property if onboarding itself has multiple sub-steps worth tracking individually).
Computing conversion rates (approach). For a cohort of users who entered the funnel in a given window (typically anchored to signup date, so you are comparing users who had a comparable amount of time to progress), compute the count of distinct users who fired each step's event, then:
step-to-step conversionN=distinct users at step N−1distinct users at step N overall conversion=distinct users at the first stepdistinct users at the final stepThe SQL-heavy part is dedup and time-windowing: handling users who fire the same event more than once (count them once per step), anchoring the cohort window so users near the report boundary are not unfairly penalized for "not converting yet," and joining across steps without inflating counts. That full ANSI SQL implementation, with the deduplication logic spelled out in comments, is worth building as its own artifact; this answer stays at the definitional and approach level so it does not duplicate that query line for line.
Conversion rate versus transition probability, a distinction worth making explicitly. A reported "conversion rate" (8% of June signups converted to paid by July 31) is a descriptive statistic computed over an actual historical cohort within a fixed observation window; it necessarily blends together users who are still mid-journey (right-censored, since some of them might still convert after the window closes) with users who have fully resolved (converted or clearly churned). A "transition probability," in the sense used by a Markov-chain style model of the funnel, is a modeling primitive: the probability that a user currently AT one state moves to a specific next state, treated as a stationary property assumed to hold for future users too. The practical difference: a conversion rate tells you what happened to a specific cohort; a transition probability is what you would use to PROJECT forward (if 1,000 more users reach activation next month, how many will likely reach paid), and that projection is only as good as the assumption that the transition probabilities are stable, which breaks the moment the product, pricing, or onboarding flow changes.
Macro-conversions versus micro-conversions. The macro-conversion is the primary business outcome the funnel exists to drive, paid conversion here, the event tied directly to revenue. Micro-conversions are the smaller, earlier actions along the way (completing onboarding, connecting an integration, inviting a teammate) that signal forward progress and often correlate with eventual macro-conversion. Micro-conversions matter operationally because the macro-conversion is frequently too rare, too delayed, or too influenced by factors outside the product (sales cycles, budget approval) to optimize against directly; a team will often set a micro-conversion (activation rate) as its primary internal KPI (key performance indicator) precisely because it is a faster, more controllable proxy for the macro-conversion that ultimately matters.
An alternate, broader model worth knowing. The four-step signup-to-paid funnel above is an analytics-native model, scoped to what happens once someone reaches the product. Marketing teams more often use a broader seven-stage model spanning the entire customer journey: awareness, interest, consideration, intent, evaluation, purchase, and loyalty/advocacy. That model is useful when you need to reason about PRE-signup stages (how someone first hears about the product, what makes them consider it), which the analytics funnel above deliberately does not model since it starts at signup. Neither model is "more correct"; they answer different questions, and conflating them (for example, trying to compute a SQL conversion rate for "awareness," which usually has no clean event) is a common source of confused funnel definitions.
Worked example
A cohort of 10,000 users who signed up in a given month, tracked to a fixed observation window:
- Signup: 10,000 users (the cohort's definition).
- Onboarding completed: 7,000 users. Step conversion: 7,000/10,000=70%.
- Activation completed: 4,000 users. Step conversion: 4,000/7,000≈57.1%.
- Paid: 800 users. Step conversion: 800/4,000=20%.
- Overall conversion, signup to paid: 800/10,000=8%, which also equals the product of the three step rates: 0.70×0.571×0.20≈0.08.
SaaS trial-to-paid extension: leading versus lagging indicators. A weekly operating report for a self-serve SaaS trial would track three numbers: weekly trial signups, weekly activation rate (of that week's new trials), and weekly trial-to-paid conversion rate (of trials that started their trial window roughly N weeks ago, once their trial has had time to resolve). Signup count and activation rate are LEADING indicators: they move first and predict future paid conversions before those conversions actually happen, since paid conversion typically lags activation by days or weeks. Trial-to-paid conversion rate itself is a LAGGING indicator: it only confirms what has already happened, and it cannot be computed at all until a trial cohort's window has closed. A team that watches only the lagging trial-to-paid number finds out about a problem (say, a broken onboarding step introduced two weeks ago) two to four weeks late, once enough trials have failed to convert; a team also watching the activation rate sees the drop within days, before the paid-conversion damage has fully materialized.
Trade-offs and pitfalls
- Where you draw the activation line changes everything downstream. Too broad a definition (any in-app click) inflates activation and makes the activation-to-paid step look artificially weak; too narrow a definition (a rare, deep feature) deflates activation and hides real engagement. Activation should be validated against actual paid-conversion correlation, not picked by intuition alone.
- Onboarding is rarely strictly linear in practice. Some users skip onboarding steps entirely and reach activation anyway; treating the funnel as a rigid sequence rather than checking which steps are truly prerequisite versus optional can misattribute drop-off to a step that was never actually blocking anyone.
- Cohort censoring near the report boundary. Users who signed up three days ago have not had a fair chance to reach paid yet; including them in this week's cohort denominator without accounting for that understates the true eventual conversion rate. Anchor the window consistently (for example, only include cohorts old enough that most conversions would have already happened) or report conversion as a function of days-since-signup rather than a single point estimate.
- Event name and property drift over time. If
onboarding_completedis redefined mid-quarter (a new onboarding flow ships with different steps), a naive step-over-step trend comparison silently mixes two different definitions of the same event name; version the schema or track the change explicitly rather than assuming event semantics are stable forever.
Write an ANSI SQL query to compute 'time to first value' (TTFV) where TTFV = time difference between the 'sign_up' event and the first 'key_action' event for each user. Table: events(user_id, event_name, event_timestamp). Describe how you will treat users who never perform the key action and how you compute median TTFV across the user base.
Sample Answer
Direct answer
Compute time to first value (TTFV, the elapsed time between a user's sign_up event and their FIRST key_action event) with a join between each user's earliest sign_up and their earliest key_action, treat users who never fire a key_action as right-censored (they have no observed TTFV, not a TTFV of infinity or zero), and compute the median only over the uncensored users, since the censored users' true (eventual, or never) conversion time is unknown and including them would require an assumption the data does not support.
Structured elaboration
Right-censoring, defined precisely for this case. A user is right-censored when the event that would let you measure their TTFV (the key_action) has not happened by the time you are looking at the data, and might never happen, or might still happen later; you cannot distinguish "will never convert" from "hasn't converted YET" purely from the absence of a key_action event. This is the same right-censoring problem that shows up whenever a metric is measured against an event that has not necessarily resolved yet.
Two defensible ways to handle censored users, and why "drop" is the simpler default here. Option 1: exclude censored users entirely from the median calculation, computing median TTFV only over users who HAVE converted. This is simple, always well-defined, and answers "for users who do eventually get to value, how long does it typically take," a genuinely useful operational question (does onboarding get people to value fast). Option 2: treat censored users' TTFV as right-censored data in a formal survival-analysis sense (Kaplan-Meier estimation), which can estimate a median time-to-event even in the presence of censoring, PROVIDED enough of the censored users would eventually convert; if a large fraction never will, a survival-analysis median may not even exist (the survival curve never crosses 50%). For most product-analytics reporting, Option 1 (drop and report the censoring rate alongside the median) is the more interpretable and more commonly used default; Option 2 is worth reaching for when the actual question is closer to "estimate the true underlying time-to-convert distribution accounting for the fact that some of today's non-converters will convert tomorrow," a more specialized ask.
Computing median TTFV. Extract each user's TTFV (as a numeric delta, hours or days) via SQL for only the users who have a key_action event, then compute the median in application code (Python's statistics.median, or an equivalent) over that list; this is simpler and equally legitimate compared to a SQL-native percentile function, and avoids relying on a warehouse-specific percentile syntax that varies across engines.
Worked example
Schema: events(user_id, event_name, event_timestamp). Seven synthetic users: five convert at varying speeds (2, 5, 10, 26, and 100 hours), one (u2) fires key_action TWICE (the query must use the FIRST occurrence, not a later duplicate), and two (u5, u7) never fire key_action at all, right-censored.
CREATE TABLE events (user_id TEXT, event_name TEXT, event_timestamp TIMESTAMP);
INSERT INTO events VALUES
('u1','sign_up','2026-07-01 00:00:00'),
('u1','key_action','2026-07-01 02:00:00'),
('u2','sign_up','2026-07-01 00:00:00'),
('u2','key_action','2026-07-02 02:00:00'),
('u2','key_action','2026-07-03 02:00:00'), -- duplicate, later occurrence; must NOT be used
('u3','sign_up','2026-07-01 00:00:00'),
('u3','key_action','2026-07-01 05:00:00'),
('u4','sign_up','2026-07-01 00:00:00'),
('u4','key_action','2026-07-05 04:00:00'),
('u5','sign_up','2026-07-01 00:00:00'), -- never fires key_action: right-censored
('u6','sign_up','2026-07-01 00:00:00'),
('u6','key_action','2026-07-01 10:00:00'),
('u7','sign_up','2026-07-01 00:00:00'); -- never fires key_action: right-censored
-- One row per user: sign_up_ts, first_key_action_ts (NULL if never performed,
-- i.e. right-censored), and ttfv_hours (NULL for censored users).
WITH signups AS (
SELECT user_id, MIN(event_timestamp) AS sign_up_ts
FROM events
WHERE event_name = 'sign_up'
GROUP BY user_id
),
first_key_action AS (
-- MIN() here is the dedup: a user who fires key_action multiple times
-- (u2) only has the EARLIEST occurrence counted toward TTFV.
SELECT user_id, MIN(event_timestamp) AS key_action_ts
FROM events
WHERE event_name = 'key_action'
GROUP BY user_id
)
SELECT
s.user_id,
s.sign_up_ts,
k.key_action_ts,
CASE WHEN k.key_action_ts IS NOT NULL
THEN ROUND((julianday(k.key_action_ts) - julianday(s.sign_up_ts)) * 24, 2)
ELSE NULL
END AS ttfv_hours,
CASE WHEN k.key_action_ts IS NULL THEN 1 ELSE 0 END AS is_censored
FROM signups s
LEFT JOIN first_key_action k ON k.user_id = s.user_id
ORDER BY s.user_id;
Output (actually executed against SQLite; julianday() is SQLite's date-arithmetic function, the equivalent of TIMESTAMP_DIFF in BigQuery):
user_id sign_up_ts key_action_ts ttfv_hours censored
u1 2026-07-01 00:00:00 2026-07-01 02:00:00 2.0 0
u2 2026-07-01 00:00:00 2026-07-02 02:00:00 26.0 0
u3 2026-07-01 00:00:00 2026-07-01 05:00:00 5.0 0
u4 2026-07-01 00:00:00 2026-07-05 04:00:00 100.0 0
u5 2026-07-01 00:00:00 NULL NULL 1
u6 2026-07-01 00:00:00 2026-07-01 10:00:00 10.0 0
u7 2026-07-01 00:00:00 NULL NULL 1
u2's key_action_ts correctly resolves to 26 hours (the FIRST occurrence), not a later duplicate the raw event log also contains.
import statistics
ttfv_hours = [2.0, 26.0, 5.0, 100.0, None, 10.0, None] # u1..u7, in that order (None = censored)
uncensored_deltas = [v for v in ttfv_hours if v is not None]
censored_count = sum(1 for v in ttfv_hours if v is None)
median_ttfv = statistics.median(uncensored_deltas)
print(f"Uncensored users: {len(uncensored_deltas)}, censored (never converted): {censored_count}")
print(f"Uncensored TTFV values (hours), sorted: {sorted(uncensored_deltas)}")
print(f"Median TTFV (uncensored only): {median_ttfv} hours")
print(f"Right-censoring rate: {censored_count / len(ttfv_hours):.2%}")
Output (actually executed):
Uncensored users: 5, censored (never converted): 2
Uncensored TTFV values (hours), sorted: [2.0, 5.0, 10.0, 26.0, 100.0]
Median TTFV (uncensored only): 10.0 hours
Right-censoring rate: 28.57%
With an odd count of 5 uncensored values, the median is simply the middle value once sorted, 10.0 hours; reporting the 28.57% right-censoring rate ALONGSIDE the median is what keeps this number honest, since a median TTFV computed only over the 71% who converted says nothing about the users who have not, and a reader seeing "median TTFV = 10 hours" without that context could wrongly assume most users convert quickly.
Complexity
Both CTEs are O(n) single-pass aggregations over the events table (one GROUP BY each), so the SQL portion is O(n) in the number of relevant sign_up and key_action rows; the LEFT JOIN is O(n) given an index or hash join on user_id. Computing the median in Python over the extracted per-user deltas is O(mlogm) for a sort-based median (statistics.median) where m is the number of uncensored users, negligible compared to the SQL aggregation at realistic scale, but note that this only works when the number of uncensored users is small enough to comfortably extract to application memory; at very large scale, a SQL-native approximate-percentile function is the better choice.
Edge cases
- A user who fires
key_actionbefore ever firingsign_up(a data-quality anomaly, perhaps a pre-signup guest action logged under the same eventual user_id): the query as written would still compute a negativettfv_hours, since it takes a raw difference without a floor at zero; a production version should validatekey_action_ts >= sign_up_tsand flag or exclude violations rather than silently reporting a negative TTFV. - A user with NO
sign_upevent at all (perhaps a data-pipeline gap): absent entirely from thesignupsCTE and therefore absent from the whole result, which is correct, since TTFV is undefined without a sign_up anchor. - Ties in the median calculation with an EVEN count of uncensored users:
statistics.medianaverages the two middle values, standard practice, worth confirming your chosen median implementation does the same rather than picking one of the two arbitrarily.
Trade-offs and pitfalls
- Common mistake: computing "median TTFV" over ALL users, including censored ones, by substituting some large sentinel value (or the observation-window length) for their missing TTFV. This silently biases the median toward whatever sentinel was chosen and produces a number that changes depending on an arbitrary implementation detail rather than reflecting anything real about user behavior.
- Reporting the median alone without the censoring rate is incomplete. A median TTFV of 10 hours over a 95%-converted population tells a very different story than the same 10-hour median over a 30%-converted population; the censoring rate is not optional context, it changes what the median-TTFV number is even evidence OF.
- A near-identical generic 'median time from first touch to purchase' variant of this same question, without the TTFV/key-action framing specifically, uses the identical dedup-and-censoring technique, only the two event names change (first touch, purchase, instead of sign_up, key_action); nothing about the right-censoring handling or the median computation needs to change for that variant.
SQL diagnostic (medium): Given daily funnel counts for the past 8 weeks, write a SQL query (or describe the approach) to detect whether the increase in drop-off between Step X and Step Y in the last 7 days is statistically significant compared to the prior 3 weeks. Explain which statistical test you would use and why.
Sample Answer
Direct answer
Aggregate step-X-to-step-Y drop-off into two windows, the last 7 days and the prior 3 weeks (21 days), then run a two-proportion z-test comparing the drop-off RATE (not the raw count) between the two windows: if the p-value falls below your alpha and the confidence interval for the difference excludes zero, the increase is statistically significant, not just noise. A two-proportion z-test is the right test here because drop-off is a binary per-user outcome (did they proceed or not) aggregated into a rate, which is exactly the shape a two-proportion test is built for; a chi-square test of independence on the same 2x2 table would give an equivalent conclusion, since a two-sided two-proportion z-test and a 2x2 chi-square test are algebraically the same test viewed two ways.
Structured elaboration
Why a two-proportion test, and why not something else. Daily funnel counts give, for each day, how many users reached step X and how many of those reached step Y; aggregated over a window, this is a count of successes (reached Y) out of a count of trials (reached X), a binomial-shaped quantity. Comparing two such rates (recent window vs. prior window) for a real difference is precisely the two-proportion z-test's use case. This is deliberately narrower than general time-series anomaly or change-point detection (control charts, CUSUM, cumulative sum control charting that tracks a running sum of deviations from a baseline to catch a sustained small shift, and Bayesian change-point models): those tools are built to monitor an arbitrary metric continuously over time and flag a shift wherever it occurs, appropriate general-purpose monitoring infrastructure for ANY metric. This question is scoped tighter: one specific step-pair, one specific recent-window-versus-baseline comparison, already identified as the thing to check, which is exactly what a single hypothesis test is for, no continuous monitoring machinery required.
The two windows. Recent: the last 7 days. Prior baseline: the 3 weeks (21 days) immediately preceding the recent window, adjacent, not overlapping and not gapped, so the comparison is "how has this week performed relative to the established recent baseline," not confounded by an arbitrary gap between the two periods.
The test, formally. Let precent and pprior be the drop-off rates (fraction of step-X users who did NOT reach step Y) in each window, with xrecent, xprior the step-X user counts in each window. The null hypothesis is that the true drop-off rate is the same in both windows:
H0:precent=ppriorPooled proportion and pooled standard error, used for the hypothesis test itself:
p^pool=xrecent+xpriorfailrecent+failprior,SEpool=p^pool(1−p^pool)(xrecent1+xprior1) z=SEpoolprecent−ppriorThe confidence interval for the DIFFERENCE uses the unpooled standard error instead (standard practice, since a confidence interval should not assume the null is true the way the hypothesis test's pooled SE does):
SEunpooled=xrecentprecent(1−precent)+xpriorpprior(1−pprior),CI95%=(precent−pprior)±1.96⋅SEunpooledWorked example
Synthetic 8 weeks (56 days) of daily step-X and step-Y counts, engineered with a stable ~40% baseline drop-off rate for the first 49 days and a genuine, injected regression to ~48% drop-off for the final 7 days (simulating, for example, a checkout-page bug shipped a week ago).
SQL aggregation (executed against SQLite as a stand-in for the target warehouse engine):
CREATE TABLE daily_funnel_counts (day TEXT, step_x_users INTEGER, step_y_users INTEGER);
INSERT INTO daily_funnel_counts VALUES
('2026-01-01',4879,2879),
('2026-01-02',4872,2832),
('2026-01-03',5276,3144),
('2026-01-04',4760,2794),
('2026-01-05',5037,3036),
('2026-01-06',5212,3121),
('2026-01-07',5064,2952),
('2026-01-08',5230,3085),
('2026-01-09',5002,3091),
('2026-01-10',4901,2887),
('2026-01-11',4986,2941),
('2026-01-12',4766,2855),
('2026-01-13',5102,3006),
('2026-01-14',5104,3098),
('2026-01-15',5197,3126),
('2026-01-16',5155,2999),
('2026-01-17',5055,2952),
('2026-01-18',4826,2981),
('2026-01-19',4976,2935),
('2026-01-20',5061,3054),
('2026-01-21',4825,2834),
('2026-01-22',4702,2794),
('2026-01-23',4773,2861),
('2026-01-24',5143,3000),
('2026-01-25',5021,3058),
('2026-01-26',5095,3124),
('2026-01-27',5041,2969),
('2026-01-28',5292,3201),
('2026-01-29',5000,2991),
('2026-01-30',5000,2991),
('2026-01-31',5000,2991),
('2026-02-01',5000,2991),
('2026-02-02',5000,2991),
('2026-02-03',5000,2991),
('2026-02-04',5000,2991),
('2026-02-05',5000,2991),
('2026-02-06',5000,2991),
('2026-02-07',5000,2991),
('2026-02-08',5000,2991),
('2026-02-09',5000,2991),
('2026-02-10',5000,2991),
('2026-02-11',5000,2991),
('2026-02-12',5000,2991),
('2026-02-13',5000,2991),
('2026-02-14',5000,2991),
('2026-02-15',5000,2991),
('2026-02-16',5000,2991),
('2026-02-17',5000,2991),
('2026-02-18',5020,3011),
('2026-02-19',4986,2601),
('2026-02-20',4986,2601),
('2026-02-21',4986,2601),
('2026-02-22',4986,2601),
('2026-02-23',4986,2601),
('2026-02-24',4986,2601),
('2026-02-25',4992,2607);
WITH bounds AS (
SELECT MAX(day) AS max_day FROM daily_funnel_counts
),
recent AS (
SELECT SUM(step_x_users) AS x_total, SUM(step_y_users) AS y_total, COUNT(*) AS n_days
FROM daily_funnel_counts, bounds
WHERE day > date(bounds.max_day, '-7 days')
),
prior AS (
SELECT SUM(step_x_users) AS x_total, SUM(step_y_users) AS y_total, COUNT(*) AS n_days
FROM daily_funnel_counts, bounds
WHERE day <= date(bounds.max_day, '-7 days')
AND day > date(bounds.max_day, '-28 days')
)
SELECT 'recent_7d' AS window, x_total, y_total, n_days,
ROUND(1.0 - 1.0 * y_total / x_total, 4) AS dropoff_rate
FROM recent
UNION ALL
SELECT 'prior_21d' AS window, x_total, y_total, n_days,
ROUND(1.0 - 1.0 * y_total / x_total, 4) AS dropoff_rate
FROM prior;
Output (actually executed):
window x_total y_total n_days dropoff
recent_7d 34908 18213 7 0.4783
prior_21d 105020 62831 21 0.4017
Significance test, computed in Python from the aggregated counts above (actually executed):
import math
x_recent, y_recent, n_recent = 34908, 18213, 7
x_prior, y_prior, n_prior = 105020, 62831, 21
fail_recent = x_recent - y_recent
fail_prior = x_prior - y_prior
p_recent = fail_recent / x_recent
p_prior = fail_prior / x_prior
diff = p_recent - p_prior
p_pool = (fail_recent + fail_prior) / (x_recent + x_prior)
se_pool = math.sqrt(p_pool * (1 - p_pool) * (1 / x_recent + 1 / x_prior))
z = diff / se_pool
p_value = math.erfc(abs(z) / math.sqrt(2))
se_unpooled = math.sqrt(p_recent * (1 - p_recent) / x_recent + p_prior * (1 - p_prior) / x_prior)
ci_lo = diff - 1.96 * se_unpooled
ci_hi = diff + 1.96 * se_unpooled
print(f"Drop-off rate, recent 7 days: {p_recent:.4f} ({fail_recent:,}/{x_recent:,})")
print(f"Drop-off rate, prior 21 days: {p_prior:.4f} ({fail_prior:,}/{x_prior:,})")
print(f"Observed difference (recent - prior): {diff:.4f}")
print(f"Pooled proportion: {p_pool:.4f}")
print(f"Pooled SE: {se_pool:.6f}")
print(f"z statistic: {z:.3f}")
print(f"two-tailed p-value: {p_value:.6f}")
print(f"95% CI for the difference (unpooled SE): [{ci_lo:.4f}, {ci_hi:.4f}]")
print(f"CI excludes 0: {ci_lo > 0 or ci_hi < 0}")
alpha = 0.05
print(f"At alpha={alpha}: {'REJECT H0 (drop-off increase is statistically significant)' if p_value < alpha else 'FAIL TO REJECT H0'}")
Output (actually executed):
Drop-off rate, recent 7 days: 0.4783 (16,695/34,908)
Drop-off rate, prior 21 days: 0.4017 (42,189/105,020)
Observed difference (recent - prior): 0.0765
Pooled proportion: 0.4208
Pooled SE: 0.003050
z statistic: 25.093
two-tailed p-value: 0.000000
95% CI for the difference (unpooled SE): [0.0705, 0.0826]
CI excludes 0: True
At alpha=0.05: REJECT H0 (drop-off increase is statistically significant)
The 7.65-percentage-point increase (40.2% to 47.8%) is overwhelmingly significant here (z well above the roughly 1.96 threshold for α=0.05, p-value effectively zero, confidence interval [7.05, 8.26] percentage points, comfortably excluding zero), consistent with the injected regression being large relative to this funnel's daily traffic volume.
Confidence-interval extension. The 95% confidence interval above, [0.0705, 0.0826], is the direct answer to "how much did drop-off actually increase, with uncertainty," a more complete and more decision-useful statement than the p-value alone: a p-value only says whether the increase is distinguishable from zero, while the confidence interval says how big it plausibly is, which is what determines whether the underlying cause is worth an urgent fix versus a lower-priority investigation.
Complexity
The SQL aggregation is two O(d) scans over d days of pre-aggregated daily counts (56 rows here), trivial at this grain regardless of how many raw events fed into those daily counts upstream; the actual cost lives in whatever job produced the daily rollup, not in this query. The z-test and confidence-interval computation are O(1) arithmetic once the two window totals are in hand.
Edge cases
- A step-X count of zero in either window makes the drop-off rate undefined (division by zero); guard for this explicitly (skip or flag the window) rather than letting the query silently return NULL or error deep in a dashboard pipeline.
- Very small counts in either window (a low-traffic step, or a short window) push the normal approximation the z-test relies on toward invalidity; a common rule of thumb is requiring at least 5 to 10 expected successes and failures in each group, worth checking before trusting the p-value at low volume.
- A window boundary that splits a single day (a partial day of data at the report's exact cutoff) can bias the comparison if included inconsistently; anchoring cleanly on whole calendar days, as the worked example does, avoids this.
Trade-offs and pitfalls
- Common mistake: comparing raw drop-off COUNTS between the two windows instead of RATES. Because the windows have different total traffic (34,908 users in 7 days versus 105,020 in 21 days), a naive count comparison is meaningless without normalizing by the number of users who reached step X in each window; the rate, not the count, is the quantity the hypothesis is actually about.
- Traffic-mix confounds. If the recent 7 days happens to include a different marketing-channel mix, device mix, or day-of-week composition than the prior 21 days (a holiday, a new ad campaign launch), the significant difference detected here could reflect a MIX shift rather than a genuine step-level regression; segmenting the same test by channel or device before concluding "the step itself broke" is a reasonable next check.
- A statistically significant result at this scale does not by itself prove urgency. With tens of thousands of users per window, even a modest, business-marginal shift can reach significance; pair the p-value and confidence interval with the ABSOLUTE revenue or user impact of the shift before treating it as a fire drill.
- This test is intentionally narrow, not a substitute for general monitoring. It answers "is THIS specific, already-suspected step-pair's recent change real," on demand, for one comparison. It is not a replacement for continuous anomaly-detection infrastructure that watches every step-pair automatically and flags whichever one moves: that is a general-purpose monitoring system, built once with control charts or change-point models and run continuously across every metric, not the single, already-scoped hypothesis test this question asks for.
As head of BI, propose a 3-month roadmap to improve funnel measurement. Include instrumentation priorities, experiment platform integration, dashboards for key stakeholders, data quality metrics, and success KPIs. Describe how you'd secure cross-functional buy-in and track progress.
Sample Answer
Direct answer
Sequence the three months so each builds on a floor the last one poured: month one fixes instrumentation and locks in data-quality guardrails, because nothing built afterward is trustworthy standing on broken tracking; month two wires the experiment platform into that now-clean data and ships stakeholder-specific dashboards; month three operationalizes the whole thing with named KPIs, a standing review cadence, and buy-in earned by a visible, dated fix rather than asked for on faith. Progress is tracked against the same guardrail metrics the pipeline itself is judged on, so the roadmap's own status is never just a subjective read.
Structured elaboration
Month 1: instrumentation priorities and data-quality metrics (the foundation everything else depends on).
Audit current event coverage against the funnel's ordered steps and prioritize gaps by three criteria: which steps show the highest measured or suspected drop-off, which steps block downstream attribution or experiment work entirely, and which steps have tracking known to be broken from support tickets or team anecdote before this audit even started. Ship a versioned event schema for the top three to five gap steps behind a shared client library, not a scattershot fix across the whole funnel. In parallel, stand up the data-quality metrics that guard everything built in months two and three: event volume against an expected baseline (with an anomaly alert), schema-validation failure rate, duplicate-event rate, and end-to-end latency from client fire to warehouse-queryable. These four become the guardrail dashboard referenced again in month three.
Month 2: experiment-platform integration and dashboards for key stakeholders.
Wire the now-clean funnel events into the organization's experimentation tool (or stand up assignment logging plus a stats library if none exists yet), so a test's variant assignment and a user's funnel-step events join cleanly on a shared user or session key. This is the highest-leverage integration in the whole roadmap, because every funnel change proposed after this point needs to be measurable as an experiment rather than argued from opinion. Build three separate dashboards, not one dashboard trying to serve three audiences: an executive view (three to five top KPIs, weekly trend, no drill-down clutter), a PM and growth-team view (step-by-step funnel with segment cuts by channel, device, and cohort, plus experiment overlays), and an engineering and data-quality view built directly from month one's guardrail metrics, alerting-oriented rather than exploratory.
Month 3: success KPIs, cross-functional buy-in, and progress tracking.
Define success at two levels. Process KPIs, which are available almost immediately: the guardrail metrics staying in a healthy range, the share of funnel steps with validated instrumentation, and experiment velocity (tests shipped per month). Outcome KPIs, which lag behind: step-conversion movement attributable to shipped experiments, and time-to-decision on a running test. Tie the roadmap's own early success to the process KPIs, since outcome KPIs need real experiments to have run their course first, and only shift the headline metric to outcomes once that has happened. Earn cross-functional buy-in rather than requesting it up front: ship the month-one data-quality fix as a visible, dated before-and-after (concretely, if the audit turns up a duplicate-event bug that was undercounting one channel's attributed conversions, that specific, dated correction becomes the pitch for why other teams should build on this pipeline), then pair it with a standing biweekly review where the dashboards themselves, not a slide deck, are the artifact under discussion, and let each function nominate its own top data need for the backlog instead of BI deciding unilaterally. Track progress on a visible roadmap board, not a private planning doc, with each workstream above as a line item carrying a red/amber/green status; the guardrail dashboard doubles as an independent scoreboard for whether the roadmap is actually working, since data quality trending the right way is evidence on its own, separate from anyone's subjective sense of progress.
Resource-constrained version: what to cut first with a fraction of this team or budget. Keep month one's instrumentation and data-quality work fully intact regardless of team size; it is the one piece every later cut still depends on, and cutting it removes the floor from under whatever gets built afterward. Cut breadth, not the floor: drop the third, engineering-facing dashboard first, folding its alerts into a single paging or chat channel instead of a maintained dashboard; collapse months two and three into one and ship the executive dashboard plus one experiment integration end-to-end for the single highest-drop-off step, deferring the multi-segment PM dashboard and the rest of the funnel until that first slice proves the pipeline works; keep the biweekly stakeholder review even at minimum scope, since it is what earns the next round of investment, not a nice-to-have that gets cut alongside the dashboards.
Governance, a distinct organizational concern from the roadmap's project list. A working pipeline decays back into the mess it replaced within a quarter or two once a second team starts adding events of its own, unless a governance process exists alongside it. Four elements: an event registry, a single, discoverable source of truth listing every tracked event, its schema, its owner, and its purpose, so anyone proposing a new event can first check whether something close already exists; explicit event ownership, every event assigned to a named team responsible for its continued correctness rather than left an orphaned artifact; a lightweight approval workflow for new or changed events, a review against the registry for duplication and against the schema-validation rules, not a bureaucratic gate that teams learn to route around; and contract stability for the event schema itself, versioned schemas, a stated deprecation policy for old shapes, and a compatibility check in continuous integration (CI) so a client-side change cannot silently break a downstream dashboard or an experiment's analysis. Introduce this by making the registry genuinely useful to search first, before adding any approval friction, so adoption is earned rather than mandated.
Worked example
A condensed view of the sequencing described above:
| Month | Primary deliverable | Depends on |
|---|---|---|
| 1 | Instrumentation for top 3-5 gap steps; guardrail metrics (volume, validation-failure rate, duplicate rate, latency) live | Prior audit of coverage vs. known drop-off |
| 2 | Experiment-platform join on shared user/session key; three audience-specific dashboards | Month 1's guardrails staying green |
| 3 | Process and outcome KPIs defined; biweekly stakeholder review live; roadmap board tracking RAG status | Month 2's dashboards existing to review against |
Concretely, imagine the month-one audit turns up that a mobile-web add-to-cart event was firing twice on slow network retries, silently inflating cart-to-purchase drop-off for that segment. Fixing the duplicate-event bug and republishing the corrected step-conversion number, with the date and the size of the correction attached, is the month-three buy-in pitch: it is a concrete, falsifiable reason for the growth team to trust the pipeline enough to route their next experiment's read through it, rather than a promise that the roadmap will eventually be worth trusting.
Trade-offs and pitfalls
- One dashboard trying to serve all three audiences is a common failure mode. An executive who wants three numbers and a trend line gets buried in the same segment-cut detail a PM needs, and neither ends up looking at it regularly; splitting by audience costs more up-front build time but is what actually gets used.
- Common mistake: integrating the experiment platform before data quality is fixed. Running tests on top of noisy or duplicated instrumentation produces results nobody trusts once someone finds the underlying bug, which damages buy-in far more than a slower rollout would have.
- Common mistake: defining success as dashboards shipped rather than decisions changed. A roadmap can hit every delivery date and still fail if nobody's actual funnel decisions are informed by the new dashboards; the biweekly review exists specifically to catch this by keeping the dashboards in front of the people making those calls.
- Common mistake: launching the governance approval workflow as a heavy gate from day one. Teams route around friction they did not ask for; earning adoption through the registry's usefulness first, then tightening the approval step once people are already searching it, gets more real compliance than mandating it upfront.
- Sequencing risk if month one slips. Every later workstream depends on it, so keep a hard, deliberately small fallback scope for month one (the top three highest-value events, not the full gap list) so a partial month one still unblocks month two on schedule rather than dragging the whole roadmap late.
Unlock Full Question Bank
Get access to all 27 Conversion Funnel Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.