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.
Compute required sample size for an A/B test where baseline conversion is 10% and you want to detect a 10% relative lift (i.e., increase to 11% absolute), with 80% power and a 5% two-sided significance level. Show the formula, calculation steps, and final sample size per variant. Explain approximations and caveats.
Sample Answer
Direct answer
For a baseline conversion rate of 10% and a target 10% relative lift (an absolute increase to 11%), at 80% power and a 5% two-sided significance level, the required sample size is 14,751 users per variant (29,502 total), computed with the standard two-proportion z-test sample-size formula and verified in code rather than looked up. The two biggest caveats to state alongside that number: the formula assumes a fixed sample size decided in advance and analyzed once (not repeatedly peeked at), and it assumes exactly one comparison, running the same kind of test many times across funnel steps and segments requires correcting the significance threshold, which materially increases the required sample size.
Structured elaboration
The formula. For detecting a difference between baseline conversion rate p1 and target rate p2, with two-sided significance level α and power 1−β, the required sample size per variant is
n=(p2−p1)2(zα/22pˉ(1−pˉ)+zβp1(1−p1)+p2(1−p2))2where pˉ=(p1+p2)/2 is the pooled average rate used for the critical-value term, zα/2 is the standard normal critical value for the chosen two-sided significance level, and zβ is the standard normal value corresponding to the chosen power.
Every calculation step, for p1=0.10, p2=0.11, α=0.05, power =0.80:
- zα/2=z0.025=1.9600 (the value beyond which 2.5% of the standard normal distribution lies on each tail, for a 5% two-sided test)
- zβ=z0.20=0.8416 (the value corresponding to 80% power)
- pˉ=(0.10+0.11)/2=0.105
- Critical-value term: zα/22pˉ(1−pˉ)=1.9600×2×0.105×0.895=1.9600×0.1880=1.9600×0.4335=0.8497
- Power term: zβp1(1−p1)+p2(1−p2)=0.8416×0.10×0.90+0.11×0.89=0.8416×0.09+0.0979=0.8416×0.1879=0.8416×0.4335=0.3648
- Sum, squared, over (p2−p1)2=0.012=0.0001: n=(0.8497+0.3648)2/0.0001=1.21452/0.0001=1.4751/0.0001=14,751 (rounding the intermediate sum up slightly at each displayed step; the exact, unrounded computation below gives 14,750.79, rounded up to 14,751)
Final answer: n = 14,751 per variant, 29,502 total across both variants.
Approximations and caveats in the formula itself. This is the normal (Wald-style) approximation to the binomial, accurate for the sample sizes this kind of calculation typically produces, but technically an approximation, not an exact result; some practitioners add a small continuity correction for extra conservatism, which this answer omits since the effect is negligible at n in the thousands. The formula also assumes a FIXED sample size decided before the test starts and analyzed exactly once at the end; a test monitored continuously and stopped as soon as significance is first observed (without a formal sequential-testing correction) will falsely "succeed" far more often than the stated 5% significance level implies, because repeated looks each carry their own chance of a false positive.
Worked example
All arithmetic verified in Python (statistics.NormalDist, no external library required), not by hand or by eyeballing z-scores:
import math
from statistics import NormalDist
nd = NormalDist()
def sample_size_two_proportion(p1, p2, alpha=0.05, power=0.8):
z_alpha = nd.inv_cdf(1 - alpha / 2)
z_beta = nd.inv_cdf(power)
p_bar = (p1 + p2) / 2
term1 = z_alpha * math.sqrt(2 * p_bar * (1 - p_bar))
term2 = z_beta * math.sqrt(p1 * (1 - p1) + p2 * (1 - p2))
n = ((term1 + term2) ** 2) / ((p2 - p1) ** 2)
return n, math.ceil(n)
print("Primary (10% -> 11%):", sample_size_two_proportion(0.10, 0.11))
print("Companion (5% -> 6%):", sample_size_two_proportion(0.05, 0.06))
m = 10
print(f"Bonferroni-corrected, m={m} concurrent tests:",
sample_size_two_proportion(0.10, 0.11, alpha=0.05 / m))
Output (actually executed):
Primary (10% -> 11%): (14750.79046904495, 14751)
Companion (5% -> 6%): (8157.731447849276, 8158)
Bonferroni-corrected, m=10 concurrent tests: (25019.652834268625, 25020)
Companion instance, at different baseline and lift numbers. For a baseline of 5% detecting a 20% relative lift (to 6% absolute), holding power and significance fixed at the same 80% and 5% two-sided, the required sample size is 8,158 per variant, noticeably smaller than the primary case despite testing a comparable relative lift, because the absolute gap between the two rates (1 percentage point in both cases) sits on a smaller baseline variance term at 5% than at 10%.
Multiplicity: what changes when many tests run concurrently
Running this same kind of sample-size-and-significance calculation independently across many funnel steps and many segments (checking, say, 10 different step-by-segment slices in the same rollout) inflates the true chance of at least one false positive far above the nominal 5% significance level per test; with 10 independent tests each run at 5%, the chance of at least one false "significant" result by pure chance is 1−(1−0.05)10≈40%, not 5%. Two standard corrections address this, with different trade-offs:
- Bonferroni correction. Divide the target significance level by the number of comparisons, αcorrected=α/m, and use THAT corrected alpha in the sample-size formula's zα/2 term. This is simple and conservative (it controls the probability of ANY false positive across all m tests, the family-wise error rate), but it is a strict, often overly cautious correction, and it directly and substantially inflates the required sample size, computed above: for m=10, αcorrected=0.005, giving zα/2=2.8070 instead of 1.9600, and the required sample size rises to 25,020 per variant, a 1.696x inflation over the uncorrected 14,751.
- Benjamini-Hochberg procedure. Instead of fixing a single stricter alpha for every test in advance, this method controls the false discovery rate (FDR, the expected proportion of "significant" results that are actually false positives, rather than the probability of any false positive at all) by ranking all m tests' p-values after the data is collected and comparing each rank's p-value to a rank-dependent threshold. It is meaningfully more powerful than Bonferroni for the same nominal error-control target, since it does not treat every test as if it needed the full worst-case correction, but its correction is inherently a function of the actual observed p-values, not a single fixed number known before the study runs, so it is typically applied at the ANALYSIS stage after data collection rather than used directly, in closed form, to size the study in advance the way Bonferroni's fixed corrected alpha can be.
Trade-offs and pitfalls
- The Bonferroni-inflated sample size (25,020 per variant for 10 concurrent tests) is a real operational cost, not just an abstract statistical nicety; a team that runs many simultaneous funnel-step experiments without planning for this will either under-power every individual test or need to accept a much longer data-collection window, and this trade-off should be surfaced to stakeholders before the rollout, not discovered afterward when none of the ten tests reach significance.
- A common mistake is applying a multiplicity correction to the significance threshold used for ANALYSIS while never adjusting the sample-size calculation that determined how long the test would run, which produces an experiment that was never actually powered to detect the effect at the stricter, corrected threshold it will be judged against.
- Continuously monitoring a running test and stopping the moment it crosses significance, without a sequential-testing correction, invalidates the 5% significance-level guarantee this calculation is built on; if early stopping is operationally necessary, use a sequential testing method (such as a group-sequential design with pre-specified alpha spending) rather than an ad hoc "check daily, stop when significant" practice layered on top of a fixed-sample-size calculation.
- The formula's power term uses p1 and p2's own individual variances (the more standard, slightly more accurate approach), while the critical-value term uses the pooled pˉ; a simplified version some calculators use applies pˉ to BOTH terms, which is a reasonable approximation when p1 and p2 are close together (verified directly: this simplification gives 14,752 for the primary case here, versus 14,751 with the more precise unpooled power term, a 0.01% difference) but diverges more as the two rates get further apart, so know which version a given calculator or teammate is using before comparing numbers.
Design strategies to detect and deduplicate duplicate events in an event stream. Describe both prevention (client/server-side idempotency) and post-ingest deduplication (SQL/ETL) approaches, and discuss trade-offs when using event_id, fingerprinting, or time-window based deduplication.
Sample Answer
Direct answer
Deduplication needs two layers, not one: prevention, so as few duplicates as possible are created in the first place (idempotency keys enforced on both the client and the server), and post-ingest cleanup in SQL or an extract-transform-load (ETL) job, because some duplicates will slip through prevention no matter how carefully it is built (retries during a network partition, at-least-once delivery from a message queue, multi-region replication). For the post-ingest layer, the actual matching technique, exact event_id, a fingerprint hash of key fields, or a time-window heuristic, is chosen based on what identifying information the event actually carries, trading exactness for coverage as you move from event_id toward time-window.
Structured elaboration
Prevention, client-side. Generate a unique event identifier (a UUID is standard) at the moment the event is created on the device, not at send time, and attach it to the event payload. Buffer the event locally (a queue or outbox) before transmission, so a retry caused by a timeout or app restart resends the exact same event_id rather than minting a new one for what is logically the same user action. This is the single highest-leverage prevention step, because it fixes duplication at its most common source: client-side retry logic.
Prevention, server-side. The ingestion endpoint enforces idempotency using that event_id: before accepting a write, check a fast key-value store (commonly Redis or an equivalent low-latency cache) keyed by event_id with a time-to-live (TTL) set to cover the expected retry window (for example, a few minutes). If the key already exists, return a success response without reprocessing rather than writing a second row; this makes the write operation idempotent from the client's point of view, retrying is always safe.
Post-ingest deduplication (SQL/ETL). Even with both prevention layers in place, duplicates still reach storage: legacy or third-party sources without a reliable event_id (webhooks, older client versions), at-least-once delivery semantics from the underlying event bus (Kafka, Kinesis, and similar systems guarantee delivery, not exactly-once arrival, unless the consumer adds its own dedup layer), or a bug in the idempotency-key generation itself. The standard SQL pattern is a windowed dedup: ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY ingestion_time ASC), keeping only rn = 1, run either as a scheduled batch job or as an upsert (MERGE/INSERT ... ON CONFLICT) directly against the target table keyed by event_id. In a streaming pipeline, the equivalent is a stateful deduplication operator (for example Flink's or Kafka Streams' state store) holding a bounded lookback window of recently seen ids, since holding every id ever seen in memory forever is not viable at scale.
Trade-offs among the three matching techniques.
| Technique | What it needs | Strength | Weakness |
|---|---|---|---|
| event_id-based | A reliable, consistently generated identifier on every event | Exact match, cheap index lookup, no false positives if ids are correct | Fails silently if id generation is buggy: two different logical events sharing an id (under-counts), or the same event minted with two different ids (over-counts) |
| Fingerprinting-based | A hash of a chosen, fixed set of stable fields (user_id, event_name, and other consistent attributes, often bucketed into a coarse time window) | Works when no reliable event_id exists (legacy sources, third-party webhooks) | False positives if the chosen fields under-distinguish two genuinely different events; false negatives if a field that should be excluded from the hash (like a millisecond timestamp) is accidentally included, which prevents true duplicates from matching |
| Time-window-based | Only a timestamp and enough shared context (same user, same event name) | Last resort when no id or fingerprint field reliably distinguishes events; catches double-click and rapid-retry cases | Highest false-positive risk: a user can legitimately repeat the same action quickly (two genuine add-to-cart clicks seconds apart), so the window must be tuned empirically and validated, not guessed |
How you validate this works. A dedup design is only as good as its test plan, and that plan has three layers. Unit tests on the dedup logic in isolation: feed the ROW_NUMBER SQL (or the equivalent stream-processor state logic) a fixed set of rows with known duplicates by event_id and by fingerprint, and assert the exact surviving row count and row identities, not just "count went down"; include a negative test where two genuinely distinct events happen to share a fingerprint's non-hashed fields but occur in different time buckets, and must both survive. Integration tests exercising the full client-to-server path: simulate a client network timeout that triggers a retry, and assert the server receives two requests carrying the same event_id but persists exactly one row, proving the idempotency-key enforcement (not just the offline SQL job) actually works end to end. Production validation via client-server reconciliation: compare a client-side "events sent" counter (or local outbox queue depth) against the server's ingested-and-deduplicated row count for the same time window and user population, run continuously rather than as a one-time check. A persistent gap is diagnostic: server counts running higher than client counts signals under-deduplication (a broken or missing event_id); server counts running lower signals either over-aggressive dedup (false-positive fingerprint collisions) or true event loss upstream of ingestion.
Worked example
Six raw event rows land in the table:
| row | event_id | user | event | ingestion_time |
|---|---|---|---|---|
| 1 | evt-abc-123 | 1 | add_to_cart | 10:00:00.000 |
| 2 | evt-abc-123 | 1 | add_to_cart | 10:00:00.900 (client retry, same id) |
| 3 | NULL | 2 | purchase | 11:00:00.000 |
| 4 | NULL | 2 | purchase | 11:00:00.050 (duplicate delivery, no id) |
| 5 | evt-def-456 | 3 | add_to_cart | 12:00:00.000 |
| 6 | evt-ghi-789 | 3 | add_to_cart | 12:00:00.400 (genuine second click, distinct id) |
Running the exact-event_id ROW_NUMBER dedup (SQLite, actually executed):
CREATE TABLE raw_events (row_id INTEGER, event_id TEXT, user_id INTEGER, event_name TEXT, ingestion_time TEXT);
INSERT INTO raw_events VALUES
(1,'evt-abc-123',1,'add_to_cart','2024-04-01 10:00:00.000'),
(2,'evt-abc-123',1,'add_to_cart','2024-04-01 10:00:00.900'),
(3,NULL,2,'purchase','2024-04-01 11:00:00.000'),
(4,NULL,2,'purchase','2024-04-01 11:00:00.050'),
(5,'evt-def-456',3,'add_to_cart','2024-04-01 12:00:00.000'),
(6,'evt-ghi-789',3,'add_to_cart','2024-04-01 12:00:00.400');
WITH ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY ingestion_time ASC) AS rn
FROM raw_events
WHERE event_id IS NOT NULL
)
SELECT row_id, event_id, user_id, event_name, ingestion_time FROM ranked WHERE rn = 1 ORDER BY row_id;
row_id | event_id | user_id | event_name | ingestion_time
1 | evt-abc-123 | 1 | add_to_cart | 2024-04-01 10:00:00.000
5 | evt-def-456 | 3 | add_to_cart | 2024-04-01 12:00:00.000
6 | evt-ghi-789 | 3 | add_to_cart | 2024-04-01 12:00:00.400
Row 2 (the retried duplicate) is correctly dropped, and rows 5 and 6 both survive, because they carry distinct event_ids even though they are close in time, exactly the case a naive time-window rule would have wrongly collapsed. For the two rows with no event_id, a fingerprint of user_id | event_name | 1-second time bucket is used instead:
SELECT row_id, user_id, event_name, ingestion_time,
user_id || '|' || event_name || '|' || CAST(strftime('%s', ingestion_time) AS INTEGER) AS fp
FROM raw_events WHERE event_id IS NULL;
row_id | user_id | event_name | ingestion_time | fp
3 | 2 | purchase | 2024-04-01 11:00:00.000 | 2|purchase|1711969200
4 | 2 | purchase | 2024-04-01 11:00:00.050 | 2|purchase|1711969200
Row 4, the 50-millisecond-later duplicate delivery of the same logical purchase, shares row 3's fingerprint bucket exactly, so it correctly collapses into row 3.
Trade-offs and pitfalls
- Deduplicating too aggressively is a real failure mode, not just under-deduplicating: an overly coarse time window or an under-specified fingerprint will silently merge two real user actions into one, which quietly deflates true funnel volume in a way that is much harder to notice than a duplicate-inflation bug, because the numbers just look "clean."
- Decide and document a tie-break rule for which row survives when duplicates are detected (first-seen by ingestion_time is standard, since it best represents when the user actually acted), because downstream joins that assume a unique event_id per logical event will behave inconsistently if the choice is arbitrary or changes between runs.
- A stream-processor's deduplication state store has a bounded lookback window by necessity; a duplicate arriving after that window has aged out of state will not be caught by streaming dedup and must rely on the batch/ETL pass as a backstop, so treat the two as complementary layers, not either/or.
- Prevention (idempotency keys) reduces the RATE of duplicates but does not eliminate the need for post-ingest dedup, since third-party and legacy sources will never carry a reliable id; a design that only implements one layer is incomplete regardless of which layer is chosen.
You have a simple 3-step funnel with monthly unique user counts: Step A (landing page) = 100,000, Step B (signup) = 8,000, Step C (paid conversion) = 1,200. Calculate: overall conversion rate A→C, step-to-step conversion rates A→B and B→C, and percentage drop-off at each step. Show formulas and final numbers.
Sample Answer
Direct answer
With Step A (landing) = 100,000, Step B (signup) = 8,000, and Step C (paid) = 1,200: overall conversion A to C is 1.2%, step A to B is 8%, step B to C is 15%, drop-off at A to B is 92%, and drop-off at B to C is 85%. The A to B step is the priority: it has both the lower conversion rate and, by a wide margin, the larger absolute number of users lost.
Structured elaboration
Formulas. For any two steps, conversion rate is users at the later step divided by users at the earlier step, and drop-off is one minus that rate (equivalently, users lost divided by users at the earlier step):
conversion rate=users at earlier stepusers at later step,drop-off=1−conversion rateOverall conversion across a multi-step funnel is either computed directly (final step users divided by first step users) or as the product of the individual step rates, and both must agree:
overall=AC=(AB)(BC)Applying the formulas:
- Overall A to C: 1,200/100,000=1.2%
- Step A to B: 8,000/100,000=8%
- Step B to C: 1,200/8,000=15%
- Drop-off A to B: 1−8%=92%, meaning 92,000 of the 100,000 landing-page visitors never signed up.
- Drop-off B to C: 1−15%=85%, meaning 6,800 of the 8,000 signups never paid.
- Check: 0.08×0.15=0.012=1.2%, matching the direct overall calculation.
Which step to prioritize. Two lenses matter and they can disagree, so check both: the RELATIVE rate (which step converts a smaller share of the people who reach it) and the ABSOLUTE volume lost (which step, in raw user count, is bleeding the most people, since a small percentage improvement on a huge base can outweigh a large percentage improvement on a small base). Here they agree: A to B converts at only 8% (versus B to C's 15%), and A to B also loses 92,000 users in absolute terms versus B to C's 6,800, roughly 13.5 times more. Both signals point the same direction, so A to B (landing to signup) is the clear priority. When the two lenses disagree, in general prioritize by the absolute number of users recoverable at a plausible improvement size, since that is what actually shows up in the paid-conversion count at the bottom of the funnel, not the percentage alone.
Worked example
Uplift-projection variant: what if a step's conversion rate improved? Take a separate, illustrative scenario built on the same funnel shape and the same 100,000-visitor base: suppose the A to B step conversion rate improved from a baseline of 20% to 30% (an illustrative before/after pair, distinct from this funnel's actual 8% observed rate, used here to demonstrate how an improvement propagates downstream). Holding the actual B to C rate fixed at 15%:
- Before: 100,000×20%=20,000 reach step B; downstream paid conversions: 20,000×15%=3,000.
- After: 100,000×30%=30,000 reach step B; downstream paid conversions: 30,000×15%=4,500.
- Incremental paid conversions: 4,500−3,000=1,500, a 50% relative increase in paid conversions from a 10-percentage-point improvement at the first step.
This illustrates the general propagation rule: an improvement at an EARLY step multiplies through every downstream rate, so the revenue impact of fixing the A to B step is proportionally larger than the same percentage-point improvement made at B to C, purely because more of the funnel's total user base passes through the earlier step.
A near-identical restatement worth naming, not reworking. A version of this question that swaps the funnel to a Discover, Activate, Retain framing with the same "which step would you prioritize" ask, or one that relabels the raw counts as page views instead of landing-page visits, is testing the exact same skill: compute each rate, compute drop-off, compare relative and absolute loss, and justify a prioritization call. Nothing in the underlying reasoning changes when only the stage labels or the cover story changes.
Trade-offs and pitfalls
- Percentage points versus relative percentage. Saying a rate "improved by 10%" is ambiguous: going from 20% to 30% is a 10-PERCENTAGE-POINT increase but a 50% RELATIVE increase. Always state which one you mean; conflating the two is a common way to overstate or understate an improvement's real size.
- A single point-in-time snapshot hides trend. These three numbers are a snapshot; without knowing whether 8% at A to B is stable, improving, or degrading over time, prioritizing purely off one month's numbers risks reacting to noise rather than a real pattern.
- Absolute volume can mislead when a step's population is not truly comparable. If Step A includes a large amount of bot or low-intent traffic that Step B naturally filters out, the 8% rate may partly reflect traffic quality rather than a fixable UX problem; a prioritization decision made purely on the arithmetic above should be sanity-checked against what is actually driving the low rate before committing resourcing to "fix" it.
- Common mistake: treating drop-off percentages as if they were independent of each other, and assuming fixing the worse-percentage step alone doubles overall conversion. Because overall conversion is the PRODUCT of step rates, an improvement at one step still gets multiplied by the (unchanged) rate of every other step, so the overall lift is smaller than the step-level percentage-point gain might suggest, exactly as the uplift-projection example above shows (a 10-point step improvement yielded a 50% relative lift in paid conversions, not a 10-point lift in the overall rate).
SQL challenge (hard): Given events: first_touch(user_id, first_touch_at TIMESTAMP) and conversions(user_id, conversion_at TIMESTAMP), write an efficient SQL (assume BigQuery or Postgres with analytic functions) to compute median time-to-conversion (in hours) for each monthly acquisition cohort. Explain performance considerations for large datasets.
Sample Answer
Direct answer
Join every user's first touch to their (possibly absent) conversion, bucket by the calendar month of first touch, and compute the median of the conversion-time gap in hours using a native percentile function (MEDIAN or PERCENTILE_CONT(0.5), both available in BigQuery and Postgres-family engines including DuckDB); the part most answers get wrong is censoring, users with a first touch but no matching conversion must be excluded from the median computation (their time-to-conversion is undefined, not infinite or zero) while still being counted in the cohort's size and reported conversion rate, so the median is never silently computed over a biased, converters-only view without saying so.
Structured elaboration
Cohort definition. date_trunc('month', first_touch_at) groups users by the calendar month their first touch occurred, giving a fixed cohort assignment per user, independent of whether or when they ever convert.
Computing the gap. For users who do have a conversion row, the gap in hours is EXTRACT(EPOCH FROM (conversion_at - first_touch_at)) / 3600.0; EPOCH here means the timestamp difference expressed in seconds, the standard way to get a precise sub-day duration out of a timestamp subtraction across both BigQuery and Postgres-family engines.
Censoring, handled explicitly, not implicitly. A LEFT JOIN from first_touch to conversions is the correct join direction, since every first-touch user belongs in the cohort regardless of outcome; for a user with no matching conversion row, the gap expression naturally evaluates to NULL. Both MEDIAN() and COUNT(column) (as opposed to COUNT(*)) ignore NULL values by standard SQL aggregate semantics, so the median is automatically computed only over users who actually converted, which is correct, PROVIDED the query also reports the cohort's total size and conversion rate alongside the median so nobody downstream mistakes "median time-to-conversion among converters" for "median time-to-conversion for the whole cohort," two different and easily conflated claims. This is the single most important design decision in this query: silently dropping non-converters from the join entirely (an INNER JOIN instead of LEFT JOIN) would compute the same median number but hide the fact that a meaningful share of the cohort never converted at all.
Performance considerations for large datasets. MEDIAN and PERCENTILE_CONT are fundamentally different from SUM or COUNT: computing an exact percentile requires the engine to see every value in sorted order within its group, an O(nlogn) operation per group, rather than a single streaming pass. At real event-stream scale (many millions of users per cohort), this becomes a real cost, and the standard production mitigations are: use an approximate percentile function where the engine offers one (APPROX_QUANTILE in several warehouse engines, backed by a mergeable sketch such as a t-digest or similar structure), which trades a small, bounded amount of accuracy for a computation that is close to linear and far more memory-efficient at scale; materialize and incrementally maintain a small per-user (user_id, cohort_month, hours_to_convert) table from the raw event streams, rather than recomputing the full join and extraction against raw first-touch and conversion events on every query; and ensure the underlying tables are partitioned or clustered by the cohort date so a query scoped to a specific month's cohort does not need to scan unrelated months' data at all. Whether exact or approximate percentiles are used should be a stated, deliberate choice tied to how the number will be used (an executive trend line can typically tolerate an approximate percentile; a number feeding a financial or compliance report usually cannot), not a default picked without considering the trade-off.
Worked example
Schema: first_touch(user_id, first_touch_at TIMESTAMP), conversions(user_id, conversion_at TIMESTAMP). Run in DuckDB (chosen specifically because it has native MEDIAN/PERCENTILE_CONT, unlike SQLite):
WITH joined AS (
SELECT
f.user_id,
date_trunc('month', f.first_touch_at) AS cohort_month,
CASE
WHEN c.conversion_at IS NOT NULL
THEN EXTRACT(EPOCH FROM (c.conversion_at - f.first_touch_at)) / 3600.0
END AS hours_to_convert
FROM first_touch f
LEFT JOIN conversions c ON c.user_id = f.user_id
)
SELECT
cohort_month,
COUNT(*) AS cohort_size,
COUNT(hours_to_convert) AS converted_count,
ROUND(COUNT(hours_to_convert) * 100.0 / COUNT(*), 1) AS conversion_rate_pct,
ROUND(MEDIAN(hours_to_convert), 2) AS median_hours_to_convert
FROM joined
GROUP BY cohort_month
ORDER BY cohort_month;
Pinned data: 10 users, 5 per monthly cohort (January and February), each cohort containing 4 converters at varied hours-to-convert values and 1 user with no conversion row at all (users 5 and 10, the censored cases).
CREATE TABLE first_touch (user_id INTEGER, first_touch_at TIMESTAMP);
CREATE TABLE conversions (user_id INTEGER, conversion_at TIMESTAMP);
INSERT INTO first_touch VALUES
(1,'2024-01-01 00:00:00'),(2,'2024-01-01 00:00:00'),(3,'2024-01-01 00:00:00'),
(4,'2024-01-01 00:00:00'),(5,'2024-01-01 00:00:00'),
(6,'2024-02-01 00:00:00'),(7,'2024-02-01 00:00:00'),(8,'2024-02-01 00:00:00'),
(9,'2024-02-01 00:00:00'),(10,'2024-02-01 00:00:00');
INSERT INTO conversions VALUES
(1,'2024-01-01 06:00:00'), -- 6h
(2,'2024-01-02 00:00:00'), -- 24h
(3,'2024-01-02 00:00:00'), -- 24h
(4,'2024-01-11 00:00:00'), -- 240h
-- user 5: no conversion row at all (censored)
(6,'2024-02-01 12:00:00'), -- 12h
(7,'2024-02-02 00:00:00'), -- 24h
(8,'2024-02-01 12:00:00'), -- 12h
(9,'2024-02-02 00:00:00'); -- 24h
-- user 10: no conversion row at all (censored)
Output (actually executed, DuckDB):
cohort_month | cohort_size | converted_count | conversion_rate_pct | median_hours_to_convert
2024-01-01 00:00:00 | 5 | 4 | 80.0 | 24.0
2024-02-01 00:00:00 | 5 | 4 | 80.0 | 18.0
The January cohort's four converted users took 6, 24, 24, and 240 hours; sorted, the middle two values (24 and 24) average to a median of exactly 24.0, matching the printed result. The February cohort's converters took 12, 24, 12, and 24 hours; sorted [12, 12, 24, 24], the middle two average to 18.0, also matching. Both cohorts report cohort_size = 5 and conversion_rate_pct = 80.0, confirming the censored user in each cohort was correctly counted toward cohort size and conversion rate while correctly excluded from the median calculation itself; separately querying MEDIAN(hours_to_convert) and PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY hours_to_convert) side by side on the same data confirmed both functions agree exactly and both ignore the NULL (censored) rows.
Complexity
The join itself is O(F+C) where F and C are the sizes of the first_touch and conversions tables, assuming an index or clustering on user_id for both. The per-cohort median requires sorting each cohort's converted-user gaps, O(mlogm) per cohort where m is that cohort's converter count, an unavoidable cost for an exact percentile unless an approximate, sketch-based function is substituted as discussed above.
Edge cases
- Censored (never-converted) users, the case this whole design is built around: handled by the
LEFT JOINplusNULL-producingCASEexpression, verified explicitly in the worked example (users 5 and 10 counted incohort_sizebut excluded frommedian_hours_to_convert, withconversion_rate_pctmaking the exclusion visible rather than silent). - A negative or implausibly small gap (a
conversion_atearlier than its ownfirst_touch_at, a real data-quality possibility from clock skew or a backfilled event with the wrong timestamp): worth an explicit guard (WHERE c.conversion_at IS NULL OR c.conversion_at >= f.first_touch_at) so a data error does not silently corrupt the median with a nonsensical negative value. - A cohort with zero converters at all:
COUNT(hours_to_convert)correctly returns 0 andMEDIAN(hours_to_convert)correctly returnsNULLrather than erroring, which should be handled explicitly in any downstream reporting layer (distinguishing "no data yet" from "0 hours") rather than defaulting to a misleading zero.
A related but distinct variant: per-step, not end-to-end, timing
The same median/percentile machinery extends directly to a genuinely different, harder question worth naming explicitly: rather than one end-to-end gap from first touch to conversion, compute the average (or median) time BETWEEN each pair of consecutive funnel steps for users who have a full, multi-step event sequence. Two considerations specific to this variant that do not arise in the single-gap version above: outlier handling, a per-step gap has a much longer realistic tail than an end-to-end conversion gap (a user can sit on one step for weeks before returning), so a mean-based aggregate is far more outlier-sensitive here than a median is, and even the median benefits from an explicit cap or exclusion rule (winsorizing gaps beyond a chosen percentile, or excluding sessions inactive beyond a defined engagement window, stated explicitly as a modeling choice, not silently baked into the query); and midnight/day-boundary handling, computing step-to-step elapsed time must use the full timestamp difference (as this answer does throughout), never a DATE()-truncated day-difference, since two timestamps 90 minutes apart that happen to straddle local midnight would show a spurious "1 day" gap under naive date-truncated arithmetic despite the real elapsed time being under two hours; storing and computing entirely in UTC (or at minimum a single, consistently applied timezone) avoids a second, related failure mode where users in different timezones get inconsistently bucketed "same day" or "next day" for what is actually the same elapsed duration.
Trade-offs and pitfalls
MEDIAN/PERCENTILE_CONTsupport and exact syntax vary meaningfully by engine (this answer's SQL runs as shown on DuckDB and Postgres-family engines; BigQuery usesAPPROX_QUANTILEby default and requiresPERCENTILE_CONTinside anOVERwindow clause rather than as a plain aggregate, and SQLite has neither natively), so "assume BigQuery or Postgres with analytic functions," as the question specifies, is doing real work; verify the target engine's exact percentile syntax rather than assuming a single form is universal.- The single biggest correctness risk in this whole query shape is an accidental
INNER JOIN(or an equivalentWHERE conversion_at IS NOT NULLfilter applied too early) silently converting a censored population into a converters-only one; the median number produced would look completely plausible while quietly answering a different, easily-conflated question. - Choosing exact versus approximate percentiles is a real, statable trade-off, not a default; report which was used alongside the number, since a stakeholder comparing this month's median against last month's needs to know both were computed the same way.
- A common mistake specific to the per-step variant is reusing this query's exact aggregation logic unchanged and only swapping the column names, without separately addressing outlier and timezone handling, both of which matter far more for step-to-step gaps than for the single end-to-end gap this base query computes.
Describe the difference between funnel analysis (conversion flow) and retention/cohort analysis. For which business questions is each method more appropriate? Give an example question best answered by cohort analysis and one best answered by funnel analysis.
Sample Answer
Direct answer
Funnel analysis measures a user's FIRST, bounded pass through an ordered sequence of steps toward ONE terminal conversion or activation event, asking "of everyone who started, what share made it all the way through, and where did the rest fall out." Retention and cohort analysis measures what happens AFTER that event, RECURRING behavior over time, asking "of everyone who converted, how many are still coming back in week 2, week 4, month 3." The two are not interchangeable: a funnel question has a natural endpoint (conversion), a retention question does not (it is inherently about a repeated, ongoing relationship with the product).
Structured elaboration
What distinguishes them is not the word "cohort." Both fields use cohorts (a group of users who share a defining event or time window) and both can appear in a table with dates down one side and a metric across the top, which is why the two get confused. The real discriminator is what is being MEASURED, not the presence of a cohort: a funnel/conversion-flow analysis measures progress through a fixed, ordered SEQUENCE of steps toward a single terminal event; a retention/cohort analysis measures RECURRENCE, whether a user comes back and engages again, repeatedly, with no single terminal event to reach. "Cohort LTV (lifetime value) within a bounded conversion window" (does an onboarding change increase deal size AT the moment of conversion) is funnel-side; "cohort retention curve" (what fraction of a signup cohort is still active in week N, for many values of N) is retention-side, even though both use the word "cohort" and both can be visualized as a matrix.
When each is the right tool.
- Funnel analysis answers questions like: "Where in the checkout flow are we losing the most users?", "What is our signup-to-paid conversion rate this month?", "Did removing a field from the signup form improve completion?" Each of these has a clear start (entering the flow) and a clear end (the terminal conversion event), and the analysis is about the PATH between them.
- Retention/cohort analysis answers questions like: "Do users who signed up in January still use the product in April?", "Is our week-4 retention rate improving release over release?", "Which acquisition channel brings in users who stick around longest?" Each of these has no single terminal event; the question is inherently about a REPEATED relationship over an open-ended time horizon.
Why the distinction matters practically, not just semantically. A team that treats a retention problem as a funnel problem will try to "fix a drop-off step" for something that is actually about ongoing engagement decay, weeks or months after the original conversion, where there is no single broken step to find, the fix is more likely to be a product-engagement or lifecycle-messaging change than a flow-friction fix. Conversely, a team that treats a funnel problem as a retention problem risks measuring the wrong horizon (looking at whether users are active a month after SIGNUP instead of asking whether they got through onboarding to activation in the first place), missing that most of the loss actually happened in the first hour, not in ongoing usage.
Worked example
One example question best answered by funnel analysis: "Our checkout completion rate dropped from 12% to 9% last week; which step is responsible?" This is answered by building a stage-by-stage conversion table (cart to shipping-info to payment-info to order-confirmed) for last week versus the prior baseline and finding which step's conversion rate moved. The analysis has a clear start (entering checkout) and a clear end (order confirmed), and the question is entirely about the PATH between them; retention data (whether these same users come back next month) is irrelevant to answering it.
One example question best answered by cohort/retention analysis: "Users who signed up through our new referral program, are they sticking around as well as users from paid search?" This is answered by building a retention curve for each acquisition-channel cohort (percentage of each cohort still active at week 1, week 4, week 12) and comparing the curves. There is no single terminal event here; the question is explicitly about ongoing, repeated engagement over an open time horizon, and a funnel table (which stops at the first conversion) cannot answer it at all, since the entire question is about what happens for months AFTER that first conversion.
Trade-offs and pitfalls
- Common mistake: using the word "cohort" as a proxy for "this is a retention question." A cohort LTV analysis scoped narrowly to value realized AT the conversion event itself (did an onboarding redesign increase average deal size for the cohort that experienced it) is still fundamentally a funnel-side question, the intervention under test is a funnel change, and LTV here is the outcome metric for that specific conversion, not a standalone multi-period retention study.
- The boundary gets genuinely blurry around activation. Whether a user reaching "activation" counts as the funnel's terminal event or the start of a retention question depends on what is actually being measured: if the analysis asks "did this onboarding change get more users to activation," that is funnel-side (activation is the terminal event under test); if it asks "do users who activated early retain better at day 90 than users who activated late," that is retention-side (the analysis is now about recurrence AFTER activation, using activation timing only as a segmenting variable). The same event, activation, sits on either side of the boundary depending on what question is actually being asked about it.
- Combining both analyses is often the right move, not a sign one of them is wrong. A mature analytics practice runs funnel analysis to optimize the path TO conversion and retention analysis to understand what happens AFTER, and treats them as complementary views of the same user lifecycle rather than competing frameworks; a genuinely complete picture of a product's health needs both, not a choice between them.
- A retention curve built on too small or too recent a cohort produces a misleadingly optimistic tail. Users who signed up 3 days ago cannot yet demonstrate 30-day retention; mixing immature and mature cohorts in the same retention comparison (without accounting for how much time each cohort has actually had to churn) is a version of the same right-censoring problem that shows up in funnel time-to-conversion analysis, just on the retention side of the boundary.
Unlock Full Question Bank
Get access to all 47 Conversion Funnel Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.