view source

Cohort, Retention, Churn and Funnel Analysis

skill

Analyze cohort retention, churn and funnels with correct denominators: day-N retention, survival curves, conversion windows. Use for product analytics.

Apache-2.0 SQL examples use SQLite date functions; adapt them for other engines. Python with pandas; the survival curve needs lifelines, or uv to fetch it.

agents that use this skill

instructions

Overview

Retention, churn and funnel numbers go wrong in the denominator far more often than in the arithmetic. This skill covers the period grain, which users count as eligible, which retention variant answers the question, how to treat periods that are not finished, how to define churn, and how to count funnel steps. The deliverable is a cohort table or a curve whose every cell has a stated denominator, produced by a query that was run and checked against a hand count on one cohort.

Mental model

  • A cohort is a group of users who share a starting event in the same period (signup week, first purchase month). Retention asks what share of that group did a return event later.
  • A user is eligible for a retention cell only when the whole period of that cell has been observed. A user who signed up yesterday cannot have been retained at day 30; they are not a failure, they are not yet observed.
  • The last loaded day is usually partial: treat it as unobserved.
  • Right-censoring means the end of the data cut the observation short: the user has not churned yet, and the time to churn is longer than what was seen. Dropping censored users, or counting them as churned, both bias the answer.
  • A funnel is a sequence of events per user inside a time limit. A raw event count is not a funnel.

Rules

Define the cohort and the grain first

  • Write down the starting event, the return event, the cohort period (day, week, month) and the time zone, before any query. Make the starting event a first-time event, one row per user.
  • Pick the grain by how often a healthy user acts: daily grain for a daily product, weekly for a weekly one. A weekly cohort with a monthly return event produces a table of noise.
  • Report cohort size next to every row. A cohort of 20 users moves 5 points per user.

Pick the retention variant

VariantA user counts whenFits
On day Nthey returned on exactly day NHabit products with a fixed cadence; checking whether day 1 return follows onboarding
On or after day Nthey returned on day N or any later dayProducts with irregular use; the share still alive. Never rises with N for a fixed set of users
Within a bracketthey returned anywhere in a range such as days 8 to 14Weekly or monthly products; smooths day-level noise

Mixpanel's default counting method is on or after, and Amplitude offers both, as Return On and Return On or After. Amplitude measures custom brackets independently, so a later bracket can show a higher percentage than an earlier one; that is not an error. State the variant in the chart title. Never compare an on-day figure with an on-or-after figure.

Handle incomplete periods

  • A cell is filled only when every user in its cohort has had the full period to return. Mask the rest as blank or mark it provisional; never plot it as a drop.
  • Mixpanel marks buckets still in progress with an asterisk and averages only over completed buckets. Do the same: the average row is weighted by cohort size and uses completed cells only.

Churn definitions

BusinessChurn eventWatch
SubscriptionCancellation or non-renewal dateVoluntary and involuntary (failed payment) are separate causes
Usage-based, no contractNo activity for a gap GG comes from the data: read the distribution of gaps between visits, pick a gap within which most returning users come back, and show the answer at two values of G

With an inactivity gap, a user is churned only when last activity plus G is on or before the last complete day. Otherwise the user is censored at the last complete day. Churn rate for a period is churned users divided by users at risk at the period start, not by all users ever seen.

Survival curves

When some users are still active, use the Kaplan-Meier estimate. At each event time it multiplies the running probability by one minus deaths over the number still at risk; a censored user stays in the at-risk count until the censoring time and never counts as a death. In lifelines the fit call takes durations and an event indicator that is 1 for churned and 0 for censored. Report the median survival time only if the curve crosses 0.5; otherwise it is undefined (lifelines returns inf). Compare segments with a log-rank test, and show the number at risk under the curve.

Funnels

  • Order: say whether steps must happen in sequence with other events allowed between them (the usual default), in any order, or in exact consecutive order. Amplitude names these this order, any order and exact order.
  • Conversion window: the time a user has from the first step to finish. Mixpanel defaults to 7 days and Amplitude to 1 day, so state the window when comparing tools. The window starts at the first step-one event and later step-one events do not restart it. Pick the window from the product's buying cycle, and report the same window for every segment compared.
  • Users or events: count each user once at the first step-one event in the range (uniques), or let them re-enter after finishing or timing out (totals). Percentages on different counting methods do not compare.
  • Step conversion is step n over step n-1. Overall conversion is the last step over step one. Show both.
  • Time to convert: report the median and a high percentile of the gap between steps, not the mean. Users still inside the window who have not converted are not slow converters; they are censored.
  • A user who entered less than one window before the last loaded day has not had the full window: exclude or mark them.

Compare segments without Simpson's paradox

A blended rate is a mix of segment rates weighted by segment size. If the segment mix differs between the groups compared, the blended comparison can reverse the within-segment comparison. Always compute the rate within each segment (platform, plan, channel, country) beside the blended one, and the share of users in each segment for both groups. When they disagree, report the within-segment result and the mix difference. A cell with only a handful of users is shown as a count, not a percentage.

Build and verify

  1. Run the retention query below on a small sample and recompute one cohort by hand.
  2. Check that cohort sizes sum to the number of users with the starting event.
  3. For one fixed set of users, check that on-or-after never rises as N grows and that on-day is never above on-or-after.
  4. Confirm the eligible count per cell equals users whose period is fully observed.

The SQL below is SQLite dialect. Retention on day N and on or after day N, with eligibility. Count users with COUNT(DISTINCT user_id): the join to activity repeats user rows.

text
WITH first AS (SELECT user_id, MIN(date(ts)) AS d0 FROM events WHERE event='signup' GROUP BY user_id),
act AS (SELECT DISTINCT user_id, date(ts) AS d FROM events WHERE event='active'),
last AS (SELECT MAX(date(ts)) AS last_day FROM events),
n(n) AS (VALUES (1),(7),(14),(30))
SELECT n.n,
  COUNT(DISTINCT f.user_id) AS eligible,
  COUNT(DISTINCT CASE WHEN a.d = date(f.d0,'+'||n.n||' day') THEN f.user_id END) AS on_day,
  COUNT(DISTINCT CASE WHEN a.d >= date(f.d0,'+'||n.n||' day') THEN f.user_id END) AS on_or_after
FROM first f CROSS JOIN n CROSS JOIN last
LEFT JOIN act a ON a.user_id = f.user_id
WHERE date(f.d0,'+'||n.n||' day') < last.last_day
GROUP BY n.n

Funnel with ordered steps and a 7-day window from the first view (view, then cart, then buy). Users whose first view is less than one window before the last loaded event are left out:

text
WITH last AS (SELECT MAX(ts) AS last_ts FROM events),
s1 AS (SELECT user_id, MIN(ts) AS t1 FROM events WHERE event='view' GROUP BY user_id
       HAVING MIN(ts) <= datetime((SELECT last_ts FROM last),'-7 day')),
s2 AS (SELECT s1.user_id, MIN(s1.t1) AS t1, MIN(e.ts) AS t2 FROM s1 JOIN events e ON e.user_id=s1.user_id
       AND e.event='cart' AND e.ts>=s1.t1 AND e.ts<=datetime(s1.t1,'+7 day') GROUP BY s1.user_id),
s3 AS (SELECT s2.user_id FROM s2 JOIN events e ON e.user_id=s2.user_id
       AND e.event='buy' AND e.ts>=s2.t2 AND e.ts<=datetime(s2.t1,'+7 day') GROUP BY s2.user_id)
SELECT (SELECT COUNT(*) FROM s1) AS step1, (SELECT COUNT(*) FROM s2) AS step2, (SELECT COUNT(*) FROM s3) AS step3

Pandas weekly cohort table with incomplete cells masked, and the survival fit. Here a holds distinct user-days of activity with the cohort week start in cohort and the signup date in d0, size is users per cohort, observed_until is the first day not fully loaded, and durations are in days. A cell is complete when the last possible signup of its cohort has had the full week:

text
a['week'] = (a.ts - a.d0).dt.days // 7
tab = a.groupby(['cohort', 'week']).user_id.nunique().unstack(fill_value=0).div(size, axis=0)
ends = tab.index.values[:, None] + pd.to_timedelta(7 * (tab.columns.values + 2) - 1, unit='D').values[None, :]
tab = tab.where(ends <= observed_until.to_datetime64())
kmf = KaplanMeierFitter().fit(df.days, event_observed=df.churned)
kmf.median_survival_time_

Run with uv run --with pandas --with lifelines python analysis.py.

Examples

Wrong denominator. Bad: "Day 30 retention is 18%", computed over every signup including those from the last 20 days. Good: "Day 30 retention is 23% (228 of 978 users whose day 30 is fully observed), on or after variant."

Funnel on events. Bad: 5,000 cart events over 4,000 view events, "125% conversion". Good: unique users, 711 viewed, 241 added to cart within 7 days (34% step conversion), 25 bought (10% of carted, 3.5% overall).

Blended comparison. Bad: "Version A converts 28% and B 17%, so revert B." Good: B converts better in both segments (mobile 15% against 10%, desktop 40% against 30%); A looks better only because 91% of its users are on desktop against 9% for B.

Checklist

  • Starting event, return event, grain and time zone are written down.
  • The retention variant is named in the title.
  • Every cell has a stated denominator, and incomplete cells are masked.
  • Churn has a definition, and censored users are not counted as churned.
  • Funnel order, window and counting method are stated and equal across segments.
  • Step and overall conversion are both shown; time to convert uses median and percentile.
  • Segment rates and segment mix sit beside every blended comparison.
  • The query was run and one cohort was recomputed by hand.

When the user cannot be asked, state the retention variant and the churn gap you assumed.

Composition / References

Scope limits: predicting who will churn, chart styling, significance tests of an experiment and warehouse pipeline design are separate jobs.