Build an End-to-End User Purchase Prediction System
Machine LearningModel answerLast updated
Design a complete ML pipeline to predict which users will buy after receiving a promotional message, handling causality, cold starts, and production deployment.
You're building a machine learning system for a two-sided marketplace that wants to send targeted promotional notifications. The business rule is simple: each day, score all active users and send promotions to the top 20% most likely to convert.
Your task is to design the complete modeling pipeline, covering:
Label Construction & Data Leakage
Define how you'll label training examples to predict "will this user purchase in the next 7 days if we message them today?" Many users have already received messages historically—how do you avoid contaminating your labels with post-treatment signals? Should you train on everyone who was messaged, or apply additional filters? How do you handle users who receive multiple promotions?
Feature Engineering
Propose concrete features that capture user behavior, preferences, and context. Explain how you'll enforce temporal consistency (no information from the future) and prevent training-serving skew when the model runs daily in production.
Handling Imbalance & Ensuring Calibration
Purchase rates are low (around 3%). Choose appropriate techniques for class imbalance and explain how you'll calibrate probabilities. Why does calibration matter here? Describe your monitoring and recalibration strategy.
Offline Validation Strategy
Design your evaluation approach: which metrics matter, how to construct train/test splits for time-series data, and what slice-level analyses you'll perform to catch issues before production.
Estimating Incremental Impact
The real business value isn't just "probability of purchase" but "incremental purchases caused by the message." Using only historical observational data (no past A/B tests), how would you estimate whether your targeting policy actually drives incremental revenue versus just messaging people who would have bought anyway?
Production Rollout & Monitoring
Describe your online testing plan: what holdout strategy, what metrics to monitor, how to detect and respond to distribution shift, and when to retrain.
Cold Start Problem
How will you score brand-new users on their first day, and how will you iteratively improve as more data arrives?
Assume 50M daily active users, targeting the top 10M, with a baseline conversion rate around 3% over 7 days.
Hints
Hint 1
Think about the difference between correlation and causation—ranking users who are likely to buy is not the same as ranking users who buy *because* of the message.
Hint 2
For temporal data, your train/test split must respect time. Random shuffling will leak future information into your training set.
Hint 3
Calibration matters when downstream decisions use expected values (e.g., expected revenue × probability - cost), not just relative ranking.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution Framework
Clarifying the Core Tension
Before diving into implementation, recognize a critical distinction: the prompt asks for "propensity to purchase if sent a promo," which is P(purchase | treatment, features). However, business value comes from incremental purchases—the difference between purchase probability with and without the message. A model that simply ranks on P(purchase | treatment) will favor "sure things" who would buy regardless. The complete solution requires both a treated-response model and a control-response model, with selection based on estimated uplift.
1. Label Definition & Leakage Prevention
Training Examples:
Each row represents a user on a specific date (the decision point). Features capture only information available before that date; the label indicates whether a purchase occurred in the following 7 days.
Avoiding Post-Treatment Bias:
Use intent-to-treat labeling: treatment means a notification was sent, regardless of whether it was delivered, opened, or clicked. Opens and clicks happen after treatment and are correlated with purchase—conditioning on them introduces severe leakage. This approach also matches the actual decision lever (whether to send).
Multiple Exposures:
- Include prior notification counts (last 7/30 days) as features—they're pre-treatment for today's decision
- Don't truncate labels at the next send; this artificially inflates negatives for frequently-messaged users
- Sample at most one decision point per user per week to reduce correlation
Negative Examples:
- Require complete 7-day observation windows; exclude the most recent 7 days (right-censored)
- Keep churned users as true negatives
- Exclude users who were ineligible: opted-out, banned, or with purchases already in-flight
2. Feature Engineering
Behavioral Signals:
- Recency: days since last visit, search, cart addition, purchase
- Frequency: event counts across 1/7/30/90-day windows
- Trends: ratios between windows (e.g., 7-day activity / 30-day activity)
Product Affinity:
- Category distribution (share of views by category)
- Catalog diversity (entropy across categories)
- Availability status of previously viewed items
Economic Indicators:
- Historical discount usage rate
- Median price point relative to category averages
- Cart abandonment patterns
- Wishlist items currently on promotion
Contextual Features:
- User tenure bucket, country, device type
- Recent messaging fatigue (sends and opens in past week)
- Notification channel preferences
Temporal Consistency:
- Implement point-in-time joins in a feature store, keyed by (user, decision_date)
- Version all slowly-changing dimensions (loyalty tier, preferences)
- Never aggregate over windows that include the label period [t, t+7]
- Use identical code paths for training and serving
Preventing Training-Serving Skew:
- Log actual feature vectors at inference time
- Retrain periodically using logged features (once labels mature)
- Monitor population stability index (PSI) per feature between training and production distributions
3. Class Imbalance & Calibration
Model Choice:
Gradient boosted trees (LightGBM, XGBoost) with binary log-loss. For revenue prediction, use Tweedie loss or a two-stage approach (classification then regression).
Imbalance Techniques:
- Scale positive class weight by the imbalance ratio
- If downsampling negatives by factor r, correct probabilities: p_corrected = p_model / (p_model + (1 - p_model)/r)
- Regularization: L2 penalties, minimum samples per leaf, feature subsampling, early stopping
Calibration:
Apply isotonic regression or Platt scaling on a held-out recent week (separate from training). This is essential because downstream decisions involve expected revenue calculations (probability × revenue - cost), not just ranking.
Ongoing Monitoring:
- Track predicted vs. observed conversion by score decile (with 7-day lag)
- Calculate expected calibration error (ECE) daily
- Refit calibrator weekly; retrain full model when ECE or slice-level base rates drift >15%
4. Offline Evaluation
Metrics:
- Ranking quality: Precision-Recall AUC, plus precision/recall at the actual decision threshold (top 20%)
- Probability quality: log-loss, ECE, reliability diagrams
- Uplift curves when randomized data is available
Time-Based Splits:
- Train on weeks 1 through N
- Insert a 7-day gap (equal to label horizon) to prevent leakage
- Validate on week N+2
- Roll forward through multiple periods, including seasonality changes
Never use random user-level splits—this leaks future behavior through users appearing in both sets.
Slice Analysis:
- Segment by country, tenure (0-7d, 8-30d, 1-6mo, 6mo+), platform
- Check calibration, PR-AUC, and messaging volume share per slice
- Flag slices that lose or gain disproportionate share under new model
5. Causal Uplift Estimation (Observational Data)
The Challenge:
Historical data reflects a biased policy (possibly rule-based). We need to estimate incremental revenue from the new top-20% policy versus no messaging.
Propensity Score Estimation:
- If historical policy was logged with probabilities, use them directly
- Otherwise, fit e(X) = P(treatment | X) using features from the legacy rule
- Use cross-fitting to prevent overfitting
Doubly Robust Estimation: Fit separate outcome models μ₁(X) and μ₀(X) for treated and control. Estimate policy value:
V̂(policy) = mean[μ_policy(X)(X) + I{T=policy(X)} · (Y - μ_T(X)) / e_policy(X)]
This remains consistent if either the outcome or propensity model is correct.
Bias Reduction:
- Overlap diagnostics: Plot propensity distributions for treated/control, especially in top 20%. Trim scores outside [0.05, 0.95]
- Balance checks: Verify standardized mean differences <0.1 after weighting
- Stabilized weights: Use weights capped at 99th percentile to reduce variance
- Sensitivity analysis: Report estimates across multiple trimming thresholds
6. Production Rollout & Monitoring
Launch Strategy:
- Deploy with 90/10 holdout (10% random holdout gets no targeting)
- Monitor for 2-3 label horizons (14-21 days) before expanding
- Primary metric: incremental conversion rate (treatment vs. holdout)
- Guardrail metrics: opt-out rate, app uninstalls, overall engagement
Distribution Shift Detection:
- Track feature distributions daily (PSI, KL divergence)
- Monitor base conversion rate by cohort
- Alert when score distribution shifts significantly
- Implement automated fallback to previous model version
Feedback Loop Prevention:
- Users receiving more messages may show increased future scores (fatigue or habituation)
- Include messaging history as features to internalize this
- Periodically refresh holdout groups to get unbiased conversion estimates
Retraining Cadence:
- Full retrain: weekly or when drift exceeds threshold
- Calibration update: every 2-3 days as new labels arrive
7. Cold Start Strategy
New Users (Day 0):
- Use a simpler model with only available features: signup source, device, country, referral status
- Apply population-level priors from similar cohorts
- Default to median score initially (50th percentile treatment)
Rapid Learning:
- Collect initial behavioral signals (first session activity)
- Update feature vector after each interaction
- Rescore 2-3 times during first week as more data arrives
New Items:
- Use content-based features (category, price band, brand)
- Leverage embeddings from similar items with interaction history
- Implement collaborative filtering for items with minimal data
Backfill Strategy:
- As cold-start users generate 7-day outcomes, add them to training data
- Weight recent cold-start examples higher during retraining
- Monitor performance specifically on recent-signup cohorts
Common Pitfalls
- Training on opens/clicks: Conditions on post-treatment outcomes, severely inflates performance
- Random train/test splits: Leaks future into training; always split by time
- Ignoring calibration: Breaks downstream expected-value decisions
- Missing overlap: Estimating uplift where one group has no historical data
- Static models: Conversion rates drift with seasons, inventory, competition—retrain regularly
This framework provides production-grade propensity modeling that's causally sound, operationally robust, and continuously improving.