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-ofjoins 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
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 at00: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 oft(if the platform bills monthly rather than weekly, either restrict to accounts whose renewal date falls in[t, t + 7 days)or includedays_until_renewalas a primary feature). Exclude subscribers who already switched auto-renew off beforet— they are "pending cancellation," so predicting them is trivial and artificially inflates model metrics. - Target label (
y):1if the subscriber does not complete renewal for the[t, t + 7 days)window, and0if 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 millionactive subscribers, a2.5%weekly churn rate (200,000churners per week), and150engineered features per subscriber.
- Snapshot time
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 Mondayt. Three engineering guardrails enforce this:- Dual timestamp cutoffs (
event_time < tANDingested_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 whereevent_time < tbutingested_at > tgives the historical model visibility that live Monday scoring never has. - 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)usingvalid_from <= t AND t < valid_to, never joining historical snapshots against today's current-state user table. - 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 usingingested_at <= tand verify exact parity with the stored partition, and (3) compare Week-1 live scoring distributions against backtest folds before launching retention campaigns.- Dual timestamp cutoffs (
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. - At150float32features (4 byteseach), uncompressed feature storage is416M * 150 * 4 bytes = 249.6 GB/year(roughly70–90 GBcompressed in columnar Parquet). - The bottleneck is not storing416Msnapshot 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):
- Raw event landing (daily partitions): Append playback streams, browse clicks, app opens, and billing events partitioned by
event_date, preservingingested_at. - 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). - 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 ratiowatch_mins_7d / (watch_mins_28d / 4 + 1)(capturing sudden viewing drop-offs),days_since_last_session,tenure_days, andfailed_payments_90d— joined as-oftto plan/pricing history. Additive sums (watch_minutes,sessions) can update incrementally (+ newest 7 days - oldest 7 days) instead of rereading 90 partitions. - Delayed label materialization at
t + 10 days: Compute finalized0/1renewal outcomes for snapshottand co-partition bothfeatures(t)andlabels(t)byhash(user_id)so distributed joins run locally without network shuffles.
- Raw event landing (daily partitions): Append playback streams, browse clicks, app opens, and billing events partitioned by
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.
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_kto scores_k, snapshots_(k-1)'s renewal window just ended at00:00 UTCand still needs 3 grace days (t_k + 3d) for payment retries to finish. Sos_(k-2)is the newest fully labeled week available in production! - Run this exact split across
12consecutive evaluation weeksk = 1..12, always evaluatings_kat its true, untouched2.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.
- When the live model runs on Monday
Handle <5% class imbalance without distorting probabilities
At
2.5%weekly churn across26weeks of8Msubscribers (208Mrows), 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 the5.2Mchurners and randomly sampler = 10%of the202.8Mnon-churners (20.28M), shrinking the training matrix~8.2xto25.48Mrows (20.41%positive) while retaining nearly identical ranking accuracy. Alternatively, train withscale_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
rof negatives multiplies the ratio of positives to negatives (the odds,q / (1 - q)) by1 / r. To map a downsampled model's raw probabilityqback to true population churn riskp, multiply the odds back byr(p / (1 - p) = r * q / (1 - q)) and solve forp:
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- Negative downsampling (or class weights) on training folds only: Keep
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 at2.5%churn: anFPRof10%looks low on an ROC plot, yet10%of7.8Mnon-churners floods780,000happy 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 scores0.025, not0.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
betatimes higher than precision) ignores true dollar economics. Suppose on1,000,000subscribers (25,000churners,975,000stayers), a retention offer costs$3per targeted user, saves20%of targeted churners, and each saved subscriber is worth$75($15expected 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,500Targeting 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)^2between predicted risk and0/1outcomes).- 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 (
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.10stable,0.10–0.25moderate shift,> 0.25alert 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 sizeD(e.g.,D > 0.10), never on the KS p-value — with1,000,000users, the5%critical value1.36 * sqrt(2 / 1,000,000)is0.0019, so harmless weekly wiggles triggerp < 0.05every single week!
- PSI (Population Stability Index): Splits a feature into training-decile bins and computes
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 the20.0%cutoff) immediately attas an early signal, then evaluate rolling PR-AUC, precision@K, and calibration ratio (mean_predicted_risk / observed_churn_rate) att + 10 daysonce 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.
- Feature drift (covariate shift — inputs
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 att, wait a retry grace period (t + 10 days) before finalizing0/1renewal labels, and separate voluntary churn (explicit cancel) from involuntary churn (card failure). - Enforce point-in-time feature parity: Filter logs by both
event_time < tandingested_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 weekly7d / 28d / 90dwindows never rescan billions of raw events (416Msubscriber-weeks/year is ~250 GBrawfloat32, or ~80 GBin Parquet). - Mimic live label lag with rolling-origin backtesting: Train on
s_(k-27)..s_(k-2), leaves_(k-1)as an embargo gap while its payment retries settle, and evaluate ons_kat its natural2.5%churn rate across 12 rolling folds. - Downsample negatives for compute, then recalibrate: With
5.2Mpositives across 26 weeks, keeping10%of negatives cuts compute~8.2xwithout hurting tree splits; recover true probabilities viap = 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.025random 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
Drather than p-values, track concept drift (shiftingP(Y | X)) via 10-day-lagged PR-AUC and calibration, and protect future training labels from retention offers with a5%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'sstatus = '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 / prevalencelift alongside it), and atn = 1,000,000users a tiny0.002KS gap yieldsp < 0.05every week. - Retraining blindly on subscribers who received retention discounts: Saved churners flip from
y = 1toy = 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 / 28dwatch windows and distinct attrition drivers (trial-to-paid drop-off or early onboarding friction), so measure their performance in a dedicated< 7 daytenure 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 explicittenure_daysand 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 / 90dfeatures into an in-memory or low-latency key-value store (such as Redis or DynamoDB) indexed byuser_id, where reading 150 precomputed floats takes2–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 msper subscriber), set a hard50 mslookup 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)(whereris the majority keep fraction, mappingq = 0.50atr = 0.10to0.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 natural2.5%churn rate, checking reliability plots, Brier score (mean squared probability error), and predicted-to-observed ratios across risk deciles.
Follow-up questions
- How should the system score newly registered subscribers who have fewer than seven days of behavioral logs?
- Suppose real-time scoring must finish within a 200 ms per-subscriber latency budget—how would you architect feature lookup?
- How do you restore well-calibrated churn probabilities after subsampling the majority non-churn class during training?
Similar questions
- Experiment Design for Low-Rate Subscription Cancellations
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling