Production Weekly Churn Pipeline Without Leakage

Hard · Machine Learning · Data Scientist · Online Assessment

Prompt

A consumer video-streaming service with millions of active subscribers wants an automated ML system that scores every subscriber's likelihood of failing to renew over the coming seven-day cycle. Available raw sources include app session telemetry, title playback events, and billing transaction records, and fewer than 5% of active subscribers fail to renew in a typical week.

Architect a production-grade training, validation, and batch-scoring workflow that prevents future information from contaminating historical features, handles severe class skew without biasing evaluation, mirrors weekly live operations during offline backtesting, and tracks both input distribution shifts and relationship shifts after launch.

Scope & Expectations

  • System architecture & scalable snapshot engineering: Sketch an end-to-end text diagram from raw logs to scored outputs, and explain how to materialize point-in-time weekly feature tables across millions of accounts without rescanning raw event histories from scratch.
  • Leakage prevention & rolling validation: Enforce strict event-time and arrival-time boundaries (as-of joins and delayed billing-retry label windows), and design a forward-chaining weekly backtest that matches live label availability.
  • Imbalance strategy, metric selection, & live monitoring: Contrast ROC-AUC, Precision-Recall AUC, and cost-sensitive F-scores or expected campaign utility under < 5% prevalence, manage majority-class downsampling and probability calibration, and specify statistical checks for input drift, concept drift, and retention-campaign feedback loops.

Step-by-step walkthrough

  1. Lock down the prediction contract: cohort, snapshot time, and label

    Almost every data leakage bug (accidentally feeding a training model future clues that will not exist at prediction time) starts with a fuzzy problem definition. Pin down the exact unit of prediction first:

    • Snapshot time t: Every Monday at 00:00 UTC. Each training or scoring row represents one (user_id, t) pair.
    • Eligible population at t: Subscribers holding an active plan with auto-renew enabled as of t (if the platform bills monthly rather than weekly, either restrict to accounts whose renewal date falls in [t, t + 7 days) or include days_until_renewal as a primary feature). Exclude subscribers who already switched auto-renew off before t — they are "pending cancellation," so predicting them is trivial and artificially inflates model metrics.
    • Target label (y): 1 if the subscriber does not complete renewal for the [t, t + 7 days) window, and 0 if renewal succeeds. Because declined credit cards go through automatic payment retries for several days, wait a 3-day grace period (t + 10 days) before locking the final label. Track voluntary churn (subscriber actively cancels) separately from involuntary churn (payment card fails), since content recommendations cannot fix an expired credit card.
    • Illustrative scale: Assume 8 million active subscribers, a 2.5% weekly churn rate (200,000 churners per week), and 150 engineered features per subscriber.
  2. Enforce temporal integrity and eliminate data leakage

    The golden rule of temporal integrity is simple: the feature vector computed for (user_id, t) during historical training must match bit-for-bit what the live production job would have computed on Monday t. Three engineering guardrails enforce this:

    1. Dual timestamp cutoffs (event_time < t AND ingested_at <= t): Event time is when a viewer pressed play on a smart TV or mobile offline download; ingestion (arrival) time is when that log actually landed in the data warehouse. Offline devices often sync logs 12–48 hours late. Training on events where event_time < t but ingested_at > t gives the historical model visibility that live Monday scoring never has.
    2. Point-in-time (as-of) joins: Mutable account attributes (plan tier, monthly price, payment card status, country) must live in history tables with [valid_from, valid_to) intervals. An as-of join matches (user_id, t) using valid_from <= t AND t < valid_to, never joining historical snapshots against today's current-state user table.
    3. Immutable weekly partitions and shared feature code: Write each Monday's snapshot once to an append-only partition snapshot_date = t, using the exact same feature transformation code for offline training and live scoring to prevent training-serving skew (mismatches between how training and production compute a feature).

    Run every new feature through a leakage audit before adding it to training:

    Leakage trap                      Concrete example                               Exact fix
    --------------------------------  ---------------------------------------------  ----------------------------------------
    Unbounded rolling window          "Watch minutes last 7d" run without upper cap  Anchor window strictly to [t - 7d, t)
    Current-state dimension join      Joining today's subscription_status = 'cancel' As-of join on history valid_from <= t
    Target proxy ("label in disguise") Refund issued or dunning retry count in wk t  Drop post-t billing/cancellation signals
    Global target encoding            Country churn rate averaged across full year   Compute target stats strictly prior to t
    Random row train/val split        Training on Week 30, validating on Week 20     Split strictly forward in time (see below)
    

    Three practical smoke tests catch subtle leaks early: (1) flag any single feature whose standalone ROC-AUC (ranking score from 0.5 to 1.0) exceeds 0.90, (2) recompute a past week's snapshot from raw logs using ingested_at <= t and verify exact parity with the stored partition, and (3) compare Week-1 live scoring distributions against backtest folds before launching retention campaigns.

  3. Scale weekly feature snapshots for millions of subscribers

    Size the data volume first so the batch design matches reality: - 8,000,000 subscribers * 52 weeks = 416,000,000 rows/year. - At 150 float32 features (4 bytes each), uncompressed feature storage is 416M * 150 * 4 bytes = 249.6 GB/year (roughly 70–90 GB compressed in columnar Parquet). - The bottleneck is not storing 416M snapshot rows — it is scanning tens of billions of raw playback heartbeats over 90-day lookback windows if computed naively every Monday.

    Avoid rescanning raw event logs with a two-tier batch rollup (for example in Apache Spark on object storage):

    1. Raw event landing (daily partitions): Append playback streams, browse clicks, app opens, and billing events partitioned by event_date, preserving ingested_at.
    2. Daily per-user summary table (1 row per active subscriber per day): Aggregate billions of raw events once per day into (user_id, date, watch_minutes, sessions, distinct_titles, completion_rate, search_count, payment_failures). Inactive subscribers require no daily row (treated as zero).
    3. Weekly snapshot builder at t: Read daily summaries to build multi-horizon engagement levels and trends — e.g., watch_mins_7d, watch_mins_28d, velocity ratio watch_mins_7d / (watch_mins_28d / 4 + 1) (capturing sudden viewing drop-offs), days_since_last_session, tenure_days, and failed_payments_90d — joined as-of t to plan/pricing history. Additive sums (watch_minutes, sessions) can update incrementally (+ newest 7 days - oldest 7 days) instead of rereading 90 partitions.
    4. Delayed label materialization at t + 10 days: Compute finalized 0/1 renewal outcomes for snapshot t and co-partition both features(t) and labels(t) by hash(user_id) so distributed joins run locally without network shuffles.
  4. End-to-end pipeline architecture

     Session Logs ---+
     Playback Events +--> Data Lake (partitioned by event_date, keeping ingested_at)
     Billing Records +                      |
                                            v
                              Daily Per-User Rollup Job
                            (1 compact row / active user / day)
                                            |
                                            v
                         Weekly Snapshot Builder (as of Monday t) -----> Online Key-Value Store
                                            |                            (optional <200ms lookup)
                                            v
                         Offline Feature Store (partition: snapshot=t)
                                            |
                  Delayed Label Job --------+  (runs at t + 7d window + 3d retry grace)
                  (writes labels(t))        |
                                            v
                    Point-in-Time Training Join + Negative Downsampling
                                            |
                                            v
                    Rolling-Origin Backtest & Training --> Model Registry
                                            |
                                            v
                    Weekly Batch Scoring at t --> Probability Calibration --> Retention CRM
                                            |                                      |
                                            v                                      v
                    Monitoring: PSI / KS Feature Drift,             5% Untreated Random Holdout
                    Score Shift, Delayed PR-AUC & Calibration       (clean labels + uplift read)
    

    Data flows strictly left to right (and top to bottom): raw events condense into daily user summaries, materialize into immutable Monday feature snapshots, pair with 10-day-lagged labels for leak-free training, and feed weekly calibrated risk scores into both retention campaigns and an untouched 5% holdout group.

  5. Validate like production: rolling-origin backtesting with a label-lag gap

    Random k-fold cross-validation across (user_id, week) rows leaks platform-wide events — if a major hit series ends or subscription prices rise in Week 24, training on Week 25 tells the model what happened in Week 24! Instead, use rolling-origin backtesting (also called forward-chaining weekly validation), where we repeatedly train on past weeks and evaluate on a future week, advancing one week per fold.

    Crucially, copy production's label-finalization lag by inserting a 1-week purge/embargo gap between training and evaluation:

    Monday timeline:    ...   t_(k-3)    t_(k-2)    t_(k-1)      t_k (live scoring moment)
    Snapshot ID:               s_(k-3)    s_(k-2)    s_(k-1)      s_k
    Label settled by t_k?       YES        YES        NO! (needs [t_(k-1), t_k) + 3d retry grace)
    
    Fold k split:       [---- Train: s_(k-27) .. s_(k-2) (26 wks) ----] | GAP: s_(k-1) | Eval: s_k
    
    • When the live model runs on Monday t_k to score s_k, snapshot s_(k-1)'s renewal window just ended at 00:00 UTC and still needs 3 grace days (t_k + 3d) for payment retries to finish. So s_(k-2) is the newest fully labeled week available in production!
    • Run this exact split across 12 consecutive evaluation weeks k = 1..12, always evaluating s_k at its true, untouched 2.5% churn prevalence.
    • Tune hyperparameters on the earlier 8 folds, hold the newest 4 weeks untouched for final sign-off, and plot weekly metric trends (a steady downward slope reveals seasonal sensitivity before launch). Compare a rolling 26-week window (adapts faster to behavior shifts) against an expanding window on those folds.
  6. Handle <5% class imbalance without distorting probabilities

    At 2.5% weekly churn across 26 weeks of 8M subscribers (208M rows), we already have 5.2 million positive churners — gradient-boosted trees have abundant positive signal! Imbalance here is primarily a compute efficiency and thresholding problem, not a lack-of-positives problem:

    • Negative downsampling (or class weights) on training folds only: Keep 100% of the 5.2M churners and randomly sample r = 10% of the 202.8M non-churners (20.28M), shrinking the training matrix ~8.2x to 25.48M rows (20.41% positive) while retaining nearly identical ranking accuracy. Alternatively, train with scale_pos_weight / class-weighted log loss.
    • What never to do: Never apply SMOTE (Synthetic Minority Over-sampling Technique, which fabricates synthetic points between minority rows), and never downsample or rebalance validation/test snapshots — evaluation must reflect real 2.5% traffic.
    • Exact probability recalibration after downsampling: Keeping only fraction r of negatives multiplies the ratio of positives to negatives (the odds, q / (1 - q)) by 1 / r. To map a downsampled model's raw probability q back to true population churn risk p, multiply the odds back by r (p / (1 - p) = r * q / (1 - q)) and solve for p:
    def correct_for_negative_sampling(sampled_prob, keep_rate):
        """Map probability q from a model trained with negative keep_rate r back to true base rate."""
        scaled_pos = keep_rate * sampled_prob
        return scaled_pos / (scaled_pos + (1.0 - sampled_prob))
    
    
    # Example: keep_rate = 0.10 (kept all positives and 10% of negatives)
    # Sampled base rate 20.41% maps cleanly back to the true 2.50% weekly churn rate:
    print(round(correct_for_negative_sampling(0.2041, 0.10), 4))  # 0.025
    print(round(correct_for_negative_sampling(0.5000, 0.10), 4))  # 0.0909
    
  7. Choose evaluation metrics: ROC-AUC vs. PR-AUC vs. expected profit

    Compare the three candidate metrics carefully (including one widespread interview misconception):

    • ROC-AUC (Area Under the Receiver Operating Characteristic Curve — the probability that a random churner receives a higher score than a random non-churner): Because true positive rate (TP / P) and false positive rate (FP / N) are computed separately inside each class, ROC-AUC is invariant to class prevalence. That makes it dangerously flattering at 2.5% churn: an FPR of 10% looks low on an ROC plot, yet 10% of 7.8M non-churners floods 780,000 happy subscribers with unnecessary discounts!
    • PR-AUC (Area Under the Precision-Recall Curve, or Average Precision — average precision across all recall levels): Because precision (TP / (TP + FP)) pits caught churners directly against false alarms, PR-AUC depends on class prevalence (a random guesser scores 0.025, not 0.50). Despite often being misquoted as "prevalence-invariant," its sensitivity to the rare positive class is the exact reason PR-AUC measures real operational difficulty! Compare PR-AUC across weeks alongside PR lift (PR-AUC / weekly_churn_rate).
    • Expected business profit (versus cost-weighted F-beta): F-beta (a weighted harmonic mean of precision and recall that weights recall beta times higher than precision) ignores true dollar economics. Suppose on 1,000,000 subscribers (25,000 churners, 975,000 stayers), a retention offer costs $3 per targeted user, saves 20% of targeted churners, and each saved subscriber is worth $75 ($15 expected value per targeted true churner):
    Threshold operating point     TP       FP      Precision   F1     Net profit = TP*0.20*$75 - (TP+FP)*$3
    ---------------------------  ------   ------   ---------  -----   --------------------------------------
    Aggressive (TPR 80%,FPR 10%) 20,000   97,500     17.0%    0.281   $300,000 - $352,500 = -$52,500
    Selective  (TPR 48%,FPR  2%) 12,000   19,500     38.1%    0.425   $180,000 -  $94,500 = +$85,500
    

    Targeting a subscriber only pays off when their calibrated churn probability exceeds $3 / (0.20 * $75) = 20.0%. Therefore: rank candidate models by rolling PR-AUC, pick the campaign cutoff using expected profit (or precision@K for fixed outreach budgets), and verify probability calibration via Brier score (mean squared error (p_i - y_i)^2 between predicted risk and 0/1 outcomes).

  8. Operationalize monitoring: feature drift, concept drift, and feedback loops

    Once live, separate monitoring into zero-lag input checks, delayed-label accuracy checks, and intervention isolation:

    • Feature drift (covariate shift — inputs P(X) change): Every Monday before scoring, verify null rates, row counts, and feature distributions against the training baseline on top-importance features using two effect-size metrics:
      • PSI (Population Stability Index): Splits a feature into training-decile bins and computes sum((actual_share - expected_share) * ln(actual_share / expected_share)). Rules of thumb: < 0.10 stable, 0.10–0.25 moderate shift, > 0.25 alert and investigate.
      • Kolmogorov-Smirnov (KS) statistic: D = max |F_train(x) - F_live(x)|, the largest gap between training and live cumulative distributions. Alert on the effect size D (e.g., D > 0.10), never on the KS p-value — with 1,000,000 users, the 5% critical value 1.36 * sqrt(2 / 1,000,000) is 0.0019, so harmless weekly wiggles trigger p < 0.05 every single week!
    import math
    
    
    def compute_psi(expected_shares, actual_shares, eps=1e-6):
        """Population Stability Index across matching histogram bins (clipped by eps for safety)."""
        psi_total = 0.0
        for expected, actual in zip(expected_shares, actual_shares):
            e = max(expected, eps)
            a = max(actual, eps)
            psi_total += (a - e) * math.log(a / e)
        return psi_total
    
    
    print(round(compute_psi([0.25, 0.25, 0.25, 0.25], [0.34, 0.26, 0.22, 0.18]), 3))  # 0.055 (stable)
    print(round(compute_psi([0.25, 0.25, 0.25, 0.25], [0.46, 0.24, 0.18, 0.12]), 3))  # 0.247 (review)
    
    • Concept drift (relationship P(Y | X) changes): Price hikes, seasonal sports endings, or rival launches shift churn rates even when input features look steady. Monitor predicted score drift (share of subscribers above the 20.0% cutoff) immediately at t as an early signal, then evaluate rolling PR-AUC, precision@K, and calibration ratio (mean_predicted_risk / observed_churn_rate) at t + 10 days once labels settle.
    • Defending against the retention feedback loop: When the CRM team sends a discount to high-risk subscribers and saves 20% of them, their observed label turns into 0 ("renewed")! Retraining naively on treated rows teaches the next model that high-risk users stay on their own. Hold out a 5% random untreated control group every week (never targeted by retention offers) to measure true campaign uplift (incremental churn saved) and preserve uncontaminated labels for calibration and retraining. Retrain monthly (shadow-testing challenger vs. champion for one week) with automatic fallback to last week's scores if upstream data checks fail.

Intuition & how it works

Think of weekly subscription churn prediction like issuing a Monday-morning 7-day storm forecast using only satellite readings that have already arrived at the weather station before midnight Sunday. Every design decision in the pipeline protects that strict time boundary: snapshots freeze exactly what the system knew at Monday 00:00 UTC, validation advances week by week with a 1-week buffer for delayed payment-retry outcomes, and outreach thresholds balance the cost of sending a coupon against the expected value of saving a subscriber.

A naive setup — joining historical user activity to today's user-profile table, running random 5-fold cross-validation, optimizing ROC-AUC (probability a churner ranks above a stayer), and classifying at 0.5 — fails completely in production. Joining today's profile leaks future cancellations into past training rows, random splits let the model train on Week 30 to "predict" Week 20's seasonal slump, and at 2.5% churn an ROC false-positive rate of 10% looks harmless on paper while wasting coupons on 780,000 happy subscribers out of 8 million.

Walk through a concrete single-week trace to see how the pieces fit together: 1. Point-in-time snapshot (Monday t_k): Subscriber Maya is active with auto-renew on. We aggregate daily rollup tables using only events with event_time < t_k and ingested_at <= t_k (say watch_mins_7d = 15, down from 160 weekly average) plus an as-of join (valid_from <= t_k < valid_to) for her plan price at t_k. 2. Validation gap: Because week k - 1's failed cards still have 3 days of payment retries left on Monday t_k, our model trains on snapshots s_(k-27) through s_(k-2), skips s_(k-1), and scores s_k. 3. Downsampling + odds correction: Training keeps 100% of churners and r = 10% of stayers for speed. If the sampled model outputs q = 0.50 for Maya, Bayes odds scaling maps her score to true risk p = (0.10 * 0.50) / (0.10 * 0.50 + 0.50) = 9.1%. 4. Profit-driven action: If a $3 offer saves 20% of $75-value churners, break-even risk is $3 / (0.20 * $75) = 20.0%, so Maya (9.1%) is not targeted while subscribers above 20.0% enter the campaign (excluding a 5% untreated holdout kept for clean monitoring labels).

Key points

  • Frame rows strictly as (user_id, snapshot Monday t): Include only active, auto-renewing subscribers at t, wait a retry grace period (t + 10 days) before finalizing 0/1 renewal labels, and separate voluntary churn (explicit cancel) from involuntary churn (card failure).
  • Enforce point-in-time feature parity: Filter logs by both event_time < t and ingested_at <= t, join mutable user dimensions via as-of joins (valid_from <= t < valid_to), materialize immutable weekly partitions, and share transformation code across training and serving to eliminate training-serving skew (offline/online feature calculation mismatches).
  • Scale via two-tier daily rollups: Condense raw playback heartbeats once daily into 1 row per (user_id, date) so weekly 7d / 28d / 90d windows never rescan billions of raw events (416M subscriber-weeks/year is ~250 GB raw float32, or ~80 GB in Parquet).
  • Mimic live label lag with rolling-origin backtesting: Train on s_(k-27)..s_(k-2), leave s_(k-1) as an embargo gap while its payment retries settle, and evaluate on s_k at its natural 2.5% churn rate across 12 rolling folds.
  • Downsample negatives for compute, then recalibrate: With 5.2M positives across 26 weeks, keeping 10% of negatives cuts compute ~8.2x without hurting tree splits; recover true probabilities via p = r * q / (r * q + 1 - q) and never alter validation class balance.
  • Rank by PR-AUC, threshold by expected profit: Unlike ROC-AUC (which ignores class prevalence), PR-AUC (average precision across recall levels) reflects rare-event false-alarm pressure (0.025 random baseline), while expected campaign profit sets the exact probability cutoff.
  • Monitor inputs, delayed accuracy, and campaign feedback: Track feature drift (shifting input distributions) with PSI (Population Stability Index) and KS (Kolmogorov-Smirnov) distance D rather than p-values, track concept drift (shifting P(Y | X)) via 10-day-lagged PR-AUC and calibration, and protect future training labels from retention offers with a 5% random untreated holdout.

Common mistakes

  • Using random k-fold splits on (user, week) panels: Letting Week 30 train a model evaluated on Week 20 leaks seasonal spikes, content finales, and price changes backward in time.
  • Training on s_(k-1) before payment retries finish: Counting subscribers still inside their 3-day billing-retry grace window as "renewed" corrupts the freshest week of labels, or assumes labels that production cannot actually see yet.
  • Joining current-state account tables or ignoring ingested_at: Joining today's status = 'cancelled' column leaks the answer directly, and ignoring late-arriving smart-TV logs gives training data that Monday's live job lacks.
  • Including already-cancelled ("pending churn") subscribers in the cohort: Scoring accounts that already switched off auto-renew makes PR-AUC look impressive while giving marketing zero actionable lead time.
  • Applying SMOTE or rebalancing validation sets: Synthesizing fake rows before time-splitting or evaluating on a 50/50 balanced test set hides real-world false-positive costs completely.
  • Calling PR-AUC "prevalence-invariant" or alerting on KS p-values: PR-AUC shifts whenever base churn shifts (so track PR-AUC / prevalence lift alongside it), and at n = 1,000,000 users a tiny 0.002 KS gap yields p < 0.05 every week.
  • Retraining blindly on subscribers who received retention discounts: Saved churners flip from y = 1 to y = 0, poisoning the next retrain unless an untreated holdout (or explicit treatment modeling) is maintained.

Follow-up questions

  • How should the system score newly registered subscribers who have fewer than seven days of behavioral logs? New subscribers have incomplete 7d / 28d watch windows and distinct attrition drivers (trial-to-paid drop-off or early onboarding friction), so measure their performance in a dedicated < 7 day tenure slice rather than letting mature cohorts mask errors. Either train a specialized early-life model built on registration signals (acquisition channel, promotional offer, plan tier, device platform, billing instrument) plus first-24-hour engagement (minutes streamed, titles sampled, profiles created), or pass explicit tenure_days and window-completeness indicators into gradient-boosted trees so tree splits naturally isolate brand-new accounts.
  • Suppose real-time scoring must finish within a 200 ms per-subscriber latency budget—how would you architect feature lookup? Keep heavy window aggregations off the live request path by pre-loading weekly 7d / 28d / 90d features into an in-memory or low-latency key-value store (such as Redis or DynamoDB) indexed by user_id, where reading 150 precomputed floats takes 2–5 ms. Merge lightweight streaming counters (such as sessions or billing declines over the past 24 hours) updated via an event processor (such as Kafka + Flink) into the same record, run compact CPU tree inference (< 2 ms per subscriber), set a hard 50 ms lookup timeout that falls back to the latest Monday batch score, and generate batch and streaming features from shared definitions to avoid skew.
  • How do you restore well-calibrated churn probabilities after subsampling the majority non-churn class during training? Use a two-stage calibration flow: first apply the closed-form Bayes odds adjustment p = r * q / (r * q + 1 - q) (where r is the majority keep fraction, mapping q = 0.50 at r = 0.10 to 0.091), which immediately corrects the base-rate shift. Next, fit a monotonic post-processing curve — Platt scaling (a 2-parameter logistic fit on log-odds, reliable on smaller positive counts) or isotonic regression (a non-parametric monotone step fit suited to tens of thousands of validation positives) — on an untouched validation week at its natural 2.5% churn rate, checking reliability plots, Brier score (mean squared probability error), and predicted-to-observed ratios across risk deciles.

Follow-up questions

Similar questions

More HBO interview questions

All 2 HBO questions →