Predicting 90-Day Customer Churn

Medium · Machine Learning · Data Scientist · Onsite

Prompt

You are a Data Scientist at a B2B SaaS platform that manages payroll and employee benefits for small and medium-sized businesses. Product and Customer Success leadership want an early-warning model that flags business accounts likely to terminate their subscription within the upcoming 90 days, enabling account managers to run prioritized retention outreach before an account leaves.

Four relational datasets are available in the warehouse:

  1. subscriptions: account_id, start_date, end_date, plan_type
  2. activity_logs: account_id, timestamp, event_type (for example: login, payroll_run, tax_filing)
  3. support_tickets: account_id, timestamp, sentiment_score
  4. billing: account_id, amount_due, payment_status

Walk through your end-to-end modeling and deployment design across five areas:

  1. Target Definition: How do you construct a 90-day churn label when account exits can be either customer-initiated or billing-driven, and when certain employers operate on seasonal payroll schedules?
  2. Point-in-Time Feature Engineering: How do you assemble historical training rows from activity_logs, support_tickets, subscriptions, and billing while guaranteeing zero temporal look-ahead leakage?
  3. Imbalanced Learning & Model Choice: Most businesses remain subscribed in any 90-day window. Which model family, training objective, and class-imbalance strategy would you choose, and why?
  4. Offline Evaluation & Stakeholder Reporting: Why is raw classification accuracy misleading on this task? Which ranking and calibration metrics would you optimize, and how would you translate model performance for Customer Success leadership?
  5. Operational Cadence & Explainability: To intervene before accounts leave, how often should predictions refresh, and what form of per-account explanation should surface inside the support team's workflow?

Scope & Expectations

  • Domain-grounded labeling and temporal rigor: Distinguish genuine retention targets from payment-failure closures and seasonal pauses, and specify strict snapshot cutoffs (including schema-level leakage hazards and train/validation purge gaps).
  • Calibrated modeling and capacity-aware metrics: Justify your model family and loss function under heavy class skew, optimize metrics tied to finite outreach bandwidth, and present gains in business-friendly terms.
  • Actionable deployment loop: Connect batch/event scoring schedules, human-readable risk drivers for account managers, and holdout measurement into a closed operational system.

Step-by-step walkthrough

  1. Define a 90-day churn label that respects billing failures and seasonality

    For a small-business payroll and benefits platform, waiting until an owner formally submits a cancellation form misses the real moment they left: once a company moves payroll to another provider, the account is already lost even if end_date sits blank for two more months. Separate four distinct exit paths up front:

    1. Voluntary cancellation: The customer actively ends their subscription (end_date populated at customer request) — our primary target for Customer Success outreach.
    2. Silent (usage) churn: The subscription remains open, but payroll_run activity stops completely outside any normal seasonal break.
    3. Involuntary churn (payment failure): Unpaid invoices (payment_status = failed) close the account after automated retry/dunning emails. Model or route this separately: an expired credit card needs an automated billing-update prompt, not a 30-minute relationship call from an account manager.
    4. Business closure: If exit surveys indicate the company went out of business, track it separately so reps are not judged on unsaveable closures.

    Accounting for seasonal small businesses: Landscapers, summer camps, ski shops, and tax-prep offices legitimately pause payroll for 4–8 months every year. A naive rule like "no payroll_run for 45 days = churn" falsely flags every seasonal business every off-season! Instead, adapt the silent-churn threshold to each account's own payroll cadence and prior-year calendar:

    • Compute the account's median days between consecutive payroll_run events (using the median so one prior off-season gap does not skew the typical rhythm), and set its inactivity cutoff to max(45 days, 2 * typical_gap_days):
      • Biweekly payer (14-day typical gap): max(45, 28) = 45 days.
      • Monthly payer (30-day typical gap): max(45, 60) = 60 days.
    • Label rule at snapshot date T: For an account active (and not already silently churned) at T, set churn_90d = 1 if within [T, T + 90 days) the account either (a) voluntarily cancels, or (b) crosses its inactivity cutoff during calendar weeks when it actively ran payroll last year (or if < 1 year old and not flagged seasonal at signup). Note that snapshot T's label only matures once logs reach T + 90 days!
    import math
    from statistics import median
    
    
    def account_inactivity_threshold(payroll_dates, floor_days=45, cadence_multiplier=2):
        """Return silent-churn cutoff in days: max(floor_days, cadence_multiplier * median_gap)."""
        ordered_dates = sorted(payroll_dates)
        if len(ordered_dates) < 2:
            return floor_days
    
        gaps = []
        for prev_date, next_date in zip(ordered_dates, ordered_dates[1:]):
            gaps.append((next_date - prev_date).days)
    
        # Use the true median gap so one seasonal pause cannot inflate the account's normal cadence
        typical_gap = median(gaps)
        return max(floor_days, math.ceil(cadence_multiplier * typical_gap))
    
  2. Build leak-free point-in-time features across all four tables

    Construct a longitudinal snapshot dataset with one row per (account_id, snapshot_date T) (for example, every Monday for active accounts). Picture standing at 00:00 on date T — every feature must aggregate strictly over timestamp < T, while the label looks strictly forward over [T, T + 90 days):

    2025-03-03 ........................ 2025-06-01 (Snapshot T) ................. 2025-08-30 (T + 90d)
    |<--- Feature window (< T) -------->|                                         |
      activity_logs, support_tickets     |<--- Forward label window [T, T+90d) -->|
                                                                                  ^-- Row usable for training
                                                                                      only after 2025-08-30!
    

    High-signal point-in-time features by table: - activity_logs: days_since_last_payroll_run divided by the account's typical_gap (so 1.8x means nearly a missed cycle whether weekly or monthly), payroll_runs_last_30d / payroll_runs_prev_60d trend, login frequency drop, missed tax_filing milestones, and payroll_runs_same_quarter_last_year (explicit seasonality context). - support_tickets: Ticket volume in the last 30 and 90 days, minimum sentiment_score in the last 90 days (one angry -0.9 broken-payroll ticket predicts churn far better than five neutral +0.1 questions), and sentiment velocity (mean_30d - mean_prev_60d). - subscriptions & billing: Account tenure T - start_date, initial plan_type, recent plan downgrades, shrinking amount_due (a proxy for laid-off employees), and past payment hiccups.

    Critical leakage traps hidden in this exact schema: 1. billing (account_id, amount_due, payment_status) and subscriptions.plan_type lack timestamps! Querying a live mutable table joins today's post-cancellation state (amount_due = $0, payment_status = failed, or a final downgraded plan) onto a 2024 training snapshot! Require immutable timestamped invoice/plan-change logs, or snapshot those tables daily going forward and exclude un-versioned columns until historical snapshots exist. 2. Filter by ingestion/availability time (< T) and exclude pending cancellations: Ensure late-arriving logs or rescored sentiment_score models match what live serving sees at T, and remove accounts that already submitted a cancellation notice before T awaiting their billing-period end_date (route those straight to an immediate save desk). 3. Chronological split with a 90-day purge gap: Ensure the final training snapshot T_train sits at least 90 days before T_val so training label windows [T_train, T_train + 90d) never overlap validation snapshots, and keep all snapshots of an account_id grouped when tuning.

    from datetime import timedelta
    
    
    def count_window_events(event_timestamps, snapshot_time, lookback_days):
        """Count events in [snapshot_time - lookback_days, snapshot_time); hides >= snapshot_time."""
        window_start = snapshot_time - timedelta(days=lookback_days)
        total = 0
        for ts in event_timestamps:
            # Strict '< snapshot_time' guarantees zero look-ahead leakage from snapshot day onward
            if window_start <= ts < snapshot_time:
                total += 1
        return total
    
  3. Model severe class imbalance without ruining probability calibration

    Suppose 6% of active SMB accounts churn in any 90-day window (94% stay). Class imbalance rarely breaks modern learners directly — what breaks pipelines is distorting probability calibration or optimizing the wrong metric.

    • Model choice: Start with L2-regularized Logistic Regression as a fast, auditable baseline, then transition to Gradient-Boosted Decision Trees (LightGBM or XGBoost). Boosted trees excel here because churn triggers are sharply nonlinear and interactive (missing one payroll cycle plus a -0.8 support ticket spikes risk 6x) and trees handle NaN lookback ratios on newer businesses natively.
    • Loss function — unweighted Binary Cross-Entropy (Log Loss): Log loss is a proper scoring rule, meaning its mathematical optimum outputs true calibrated probabilities P(churn_90d | x). Keep the training loss unweighted by revenue: if you multiply Customer Success rankings by account_revenue downstream, weighting the loss by revenue and multiplying by revenue counts size twice and wrecks probability calibration.
    • Handling imbalance cleanly (in order of preference):
      1. No resampling first: Standard boosted trees with log loss handle a 6% positive rate cleanly when evaluated with PR-AUC rather than a naive 0.50 cutoff.
      2. Negative downsampling + exact Bayes odds correction (if snapshot volume is huge): If you keep 100% of churners and randomly keep fraction b = 0.10 of non-churners to speed up training, raw model scores p_s will be artificially inflated because 90% of stayers were hidden. Recover the exact true probability p via Bayes' rule on odds (true_odds = b * sampled_odds):
    Sampled score p_s = 0.40  ->  sampled_odds = 0.40 / 0.60 = 2 / 3
    Kept b = 0.10 of stayers  ->  true_odds    = 0.10 * (2 / 3) = 1 / 15
    True churn probability p  = (1/15) / (1 + 1/15) = 1 / 16 = 0.0625 (6.25%)
    
    Closed-form formula:  p = (b * p_s) / (b * p_s + 1 - p_s)
    
    3. **Skip SMOTE (synthetic oversampling):** Interpolating between two distinct small businesses fabricates impossible payroll histories and rarely improves boosted trees on tabular event logs (if ever tested, run strictly inside training folds).
    
  4. Optimize capacity-aligned metrics and present a clear gains table

    Why accuracy fails: At a 6% churn rate, a dummy model predicting "zero accounts will churn" scores 94.0% accuracy while saving $0! Even ROC-AUC can look deceptively high (> 0.85) because the 94% flood of true negatives keeps the false-positive rate tiny even when half of the top call list are false alarms.

    Metrics to optimize and report: - Model selection: PR-AUC (Average Precision), whose random baseline equals the 0.06 churn rate. - Operational sizing: Precision@K, Recall@K, Lift@K (Precision@K / base_rate), and Revenue-Weighted Recall@K (share of total churned MRR captured) where K equals the Customer Success team's quarterly outreach capacity.

    Walk through a 20,000-account portfolio (6% churn = 1,200 churners) where reps can proactively work K = 1,000 accounts and catch 300 true churners: - Precision@1000 = 300 / 1,000 = 30.0% (3 in 10 calls reach a genuine churner, vs. 6 in 100 at random). - Recall@1000 = 300 / 1,200 = 25.0% (25% of all churners reached by contacting just 5% of customers!). - Lift@1000 = 30.0% / 6.0% = 5.0x.

    import numpy as np
    
    
    def precision_recall_lift_at_k(labels, scores, k):
        """Compute (precision@k, recall@k, lift@k) for binary 0/1 labels and risk scores."""
        y_true = np.asarray(labels, dtype=float)
        y_score = np.asarray(scores, dtype=float)
        if k <= 0 or y_true.sum() == 0:
            return 0.0, 0.0, 0.0
    
        # Indices of the top-k highest predicted risk scores
        top_k_idx = np.argsort(-y_score)[:k]
        true_positives = float(y_true[top_k_idx].sum())
    
        precision_k = true_positives / k
        recall_k = true_positives / float(y_true.sum())
        base_rate = float(y_true.mean())
        lift_k = precision_k / base_rate
        return precision_k, recall_k, lift_k
    

    Presenting results to Customer Success stakeholders: Skip abstract curves and present a decile gains table in business terms:

    Risk Decile     Accounts   Actual 90d Churners   Churn Rate   Lift    Cumulative Churners Caught
    1 (Top 10%)      2,000       500                 25.0%        4.2x    41.7%  (500 / 1,200)
    2 (10% - 20%)    2,000       250                 12.5%        2.1x    62.5%  (750 / 1,200)
    3 (20% - 30%)    2,000       150                  7.5%        1.25x   75.0%  (900 / 1,200)
    4 - 10 (Rest)   14,000       300                  2.1%        0.36x  100.0% (1,200 / 1,200)
    

    Translate directly into staffing value: "Calling the top 1,000 accounts puts reps in front of 300 businesses on track to leave — 5x more effective than unguided check-ins — and accounts scored at 30% truly cancel ~30% of the time without intervention."

  5. Set a hybrid scoring cadence and deliver actionable explainability

    Scoring frequency — Weekly batch + Daily event triggers: Because the target horizon is 90 days and small businesses run payroll weekly, biweekly, or monthly, weekly batch scoring (every Monday morning, ranked by P(churn_90d) * account_MRR with a 30-day contact cooldown) hits the operational sweet spot: monthly batching is too slow when a frustrated owner starts shopping competitors mid-month, while pure daily re-ranking whipsaws rep queues before calls are finished. Layer daily real-time trigger alerts on top of the weekly list for acute emergencies: - A scheduled payroll_run missed past typical_gap + 3 days, - A support ticket arriving with severe negative sentiment (sentiment_score < -0.7), or - A visit to the subscription-cancellation flow.

    Retrain the model monthly or quarterly as matured 90-day labels close, monitoring feature drift and holdout precision weekly in between.

    Explainability tailored to account managers: Account managers do not want raw tree splits or log-odds — they need plain-English reason codes paired with a concrete conversation playbook right inside their CRM:

    Account #4812  |  90-Day Churn Risk: 34% (Top 4%)  |  MRR: $310/mo ($105 expected MRR at risk)
    Top Risk Drivers:
      1. Payroll overdue: 38 days since last payroll_run (account's usual cadence is every 14 days)
      2. Support friction: 2 tickets in last 30 days (lowest sentiment_score = -0.78 on tax filing)
      3. Shrinking usage: Employees paid per run dropped from 18 to 11 over the last quarter
    Recommended Playbook: Escalate open tax-filing ticket first, then schedule an AM check-in call.
    

    Compute per-account SHAP values, group correlated features (e.g., merging days_since_last_payroll_run and payroll_runs_30d into one "Payroll Activity" theme), translate the top 2–3 positive contributors into templated sentences, and train reps to treat drivers as diagnostic clues to verify on the call rather than guaranteed root causes. Finally, log every outreach disposition alongside a randomized no-outreach holdout so future iterations can evolve into uplift modeling (ranking accounts by incremental probability of being saved).

Intuition & how it works

Think of predicting 90-day churn for a small-business payroll platform like being a neighborhood utility company watching water meters: long before a restaurant formally mails in a disconnect notice, their kitchen water flow suddenly stops — unless, of course, they are a summer beach stand that closes every October and reopens every May! Building a useful churn system means teaching the model to spot abnormal silence relative to each business's own rhythm, freezing a strict historical "time machine" date so future events never leak backward, and handing account managers not just a panic score, but why the alarm rang and which accounts carry the most revenue at risk.

Naive churn pipelines fail at every stage of that chain. Defining churn solely by formal end_date cancellations misses silent churn (businesses that already moved payroll to a competitor while forgetting to cancel) yet mixes in involuntary churn (expired credit cards that need automated billing retries rather than a phone call), while a rigid "45 days without payroll" rule falsely cries wolf on every seasonal summer camp or tax office. Worse, joining untimestamped tables like billing (payment_status) onto historical snapshots leaks post-cancellation failures into past training rows, and optimizing accuracy on a 6% churn base rate rewards a useless model that predicts "nobody ever cancels" with 94% accuracy!

Walk through one concrete business (Account #4812, a biweekly café paying $310/mo) on snapshot date June 1: 1. Adaptive label & leak-free snapshot: Because the café normally runs payroll every 14 days year-round, its silent-churn cutoff is max(45, 2 * 14) = 45 days. Standing strictly at June 1, our pipeline counts only activity_logs and support_tickets with timestamp < June 1: 38 days since last payroll run plus a -0.78 sentiment tax ticket in May. 2. Calibrated risk & CRM action card: Our boosted tree model outputs a calibrated 34% 90-day churn probability ($310 * 34% = $105.40/mo at risk), placing the café in the Customer Success team's top K = 1,000 weekly outreach queue (5.0x lift over random calling) with clear SHAP (additive feature-contribution) reason codes telling the rep to resolve the tax ticket before calling.

Key points

  • Separate voluntary, silent, and involuntary churn, and adapt to seasonal rhythms. Combine voluntary cancellations in [T, T + 90d) with silent payroll churn crossing max(45 days, 2 * median_payroll_gap) during calendar months the business operated last year, while routing involuntary payment_status = failed churn to automated card-updater workflows instead of Customer Success reps.
  • Guard strictly against snapshot data leakage — especially untimestamped state tables. Filter activity_logs and support_tickets strictly to timestamp < T (by arrival time), drop pending pre-T cancellations, separate train and validation snapshots by a 90-day purge gap so forward label windows never overlap, and never join current-state columns (billing.payment_status, billing.amount_due, mutable plan_type) onto historical rows without point-in-time invoice/plan history.
  • Train Gradient-Boosted Trees with unweighted Log Loss to preserve calibrated probabilities. Binary cross-entropy (log loss) is a proper scoring rule (a loss function minimized only when predicted scores match true probabilities), letting downstream queues rank cleanly by P(churn_90d) * monthly_revenue; if negative downsampling (keeping fraction b of non-churners) is used, restore true probabilities analytically via p = (b * p_s) / (b * p_s + 1 - p_s) or Platt / isotonic calibration.
  • Optimize PR-AUC and Precision/Lift@K, and translate into a decile gains table. Replace misleading accuracy (94% when flagging nobody) with PR-AUC (Precision-Recall Area Under the Curve) for model selection and Precision@K, Recall@K, Lift@K, and Revenue Recall@K sized to rep capacity K, presented via an intuitive risk-decile table.
  • Pair weekly batch queues with daily acute alerts and plain-English playbooks. Score the full base weekly (matching biweekly/monthly payroll cadences without daily queue thrash), trigger instant daily alerts on missed payroll dates or -0.7 sentiment tickets, attach human-readable SHAP reason codes, and maintain a randomized no-outreach holdout.

Common mistakes

  • Applying a flat 45-day payroll inactivity label across all SMBs, mislabeling seasonal landscapers, summer camps, and tax preparers as churned every off-season.
  • Joining un-timestamped billing or subscriptions.plan_type rows onto historical snapshots, leaking post-cancellation $0 balances, failed payments, or final downgrades into training features.
  • Randomly splitting (account_id, snapshot_date) rows or skipping the 90-day train/validation gap, allowing overlapping 90-day outcome windows and duplicate customer histories to inflate offline metrics.
  • Weighting training log loss by account revenue and also ranking by score * revenue, double-counting size and breaking probability calibration, or applying SMOTE (synthetic feature interpolation) before splitting folds.
  • Evaluating models after launch by checking whether contacted accounts stayed, without a randomized holdout group to separate outreach saves from accounts that would have stayed anyway.

Follow-up questions

  • When an account receives an elevated risk score, how would you translate local feature attributions (such as SHAP or LIME) into guidance that an account manager trusts and acts on? For a gradient-boosted tree classifier, TreeSHAP decomposes an individual account's prediction in log-odds (ln(p / (1 - p))) into the portfolio's baseline log-odds plus exact additive contributions from each feature: for instance, starting from a 6.0% base rate (log-odds = -2.75), +1.20 from 38 days without payroll, +0.80 from shrinking headcount, +0.50 from negative ticket sentiment (-0.78), and -0.40 from 4 years of tenure sum to -0.65, which converts via 1 / (1 + exp(0.65)) to 34.3% churn risk. Never show raw log-odds or variable names to reps — group correlated features together, render the top 2–3 positive contributors as plain-English facts ("38 days since last payroll vs. usual 14-day cycle"), and map each theme to a recommended playbook. Prefer TreeSHAP over LIME (which fits a noisy local linear approximation on randomly perturbed points around the customer and can flip top reasons across runs), and remind reps that SHAP explains why the model flagged the account, not a proven causal root cause.
  • Once account managers start intervening on top-scored customers, how do you evaluate both ongoing model accuracy and the net retention impact of the outreach program? Embed a randomized holdout experiment directly inside the weekly high-risk queue: for example, out of the top 1,000 flagged accounts, randomly assign 800 to Customer Success outreach and hold back 200 with business-as-usual support. If 90-day churn finishes at 22.0% in the outreach arm versus 30.0% in the holdout arm, the causal churn reduction is 8.0 percentage points (SE = sqrt(0.22 * 0.78 / 800 + 0.30 * 0.70 / 200) = 3.56 points, 95% CI [+1.0, +15.0] points), translating to 0.08 * 800 = 64 saved businesses and measurable retained ARR minus rep time cost. Track two separate scorecards from those two groups: model health (Precision@K and calibration measured strictly on the untouched 200-account holdout, since outreach changes outcomes in the 800 arm!) and program ROI (incremental retained ARR between treatment and holdout), then use those randomized outcomes to train an uplift model targeting persuadable accounts.
  • How should your pipeline score newly onboarded businesses that have fewer than 30 days of activity history? Customers in their first 30 days haven't completed 60- or 90-day payroll lookbacks yet, and their churn stems from stalled onboarding (failing to link a bank account, import employee W-4s, or complete their very first payroll run) rather than declining habitual usage. Build a dedicated onboarding risk model (or explicit < 30-day tenure interaction features) powered by setup-funnel milestones (days_since_signup_without_first_payroll, bank/tax-ID verification status, employee roster count imported, onboarding support ticket count/sentiment, and firmographic signup traits like company size and industry), supplemented initially by crisp operational rules such as "no first payroll run by day 21 -> trigger onboarding specialist call." Evaluate < 30-day accounts on their own separate PR-AUC and calibration slice, and graduate accounts into the main behavioral churn model once they pass 60 days of history.

Follow-up questions

Similar questions

More Gusto interview questions

All 15 Gusto questions →