Design a Weekly User Activity Forecasting System
Machine LearningModel answerLast updated
Build an ML platform to forecast which users will remain active next week, supporting both batch predictions for millions of users and low-latency individual queries.
Problem
You need to architect a machine learning platform that forecasts whether individual users will engage with a streaming service during the following seven days. This forecast powers retention marketing initiatives.
What the System Must Do
- Compute weekly activity forecasts for the entire active user population
- Expose an endpoint allowing internal teams to retrieve individual user forecasts with minimal delay
- Handle predictions for recently registered users who lack historical patterns
Scale and Performance Targets
- User base: 500+ million monthly active accounts
- Batch processing: Complete predictions for all users weekly
- Real-time queries: Respond within 100 milliseconds at the 99th percentile
- Event-driven updates: Re-score users when significant profile changes occur
Your Design Should Address
- Data infrastructure: How you'll process behavioral telemetry streams and organize features for training and inference
- Modeling approach: Algorithm selection, temporal pattern handling, and label definition strategy
- Inference architecture: How batch scoring differs from online serving, and the trade-offs involved
- Operational resilience: Detecting distribution shift, handling degraded states, and maintaining system health
Available Resources
- Distributed computation framework (assume Spark-equivalent capabilities)
- Low-latency key-value storage (assume Cassandra/DynamoDB-class datastore)
- User interaction data arrives continuously but exhibits sparsity and high cardinality
Hints
Hint 1
Think about the feature freshness requirements: which features need real-time updates versus daily batch computation?
Hint 2
Consider the difference between scoring all users weekly versus scoring one user on-demand—what can you precompute?
Hint 3
New users present a different prediction problem than established users; should you use the same model for both?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Weekly User Activity Forecasting System
1. Problem Framing and Requirements Analysis
Prediction objective: Estimate the probability a user will have at least one interaction during the seven days following time T, given all information available up to T.
Scale considerations:
- With 500M monthly users and roughly 250M daily actives generating ~50 events each, expect approximately 12 billion events daily (140K/sec average, 500K/sec peak)
- Feature storage: Assuming 200 numeric features plus a 64-dimensional embedding vector (~1KB per user), the online feature store requires roughly 500GB-1TB
- Batch inference: Scoring 500M users with a gradient boosted model at 50K predictions/sec per core means 500 cores complete the job in about 20 minutes; feature assembly typically dominates over model execution
Clarifying questions to ask:
- Will scores drive binary decisions (contact/don't contact) or ranking for budget allocation? This determines whether probability calibration matters
- Does "active" encompass all content types (music, podcasts, offline playback)?
- What's the acceptable staleness for batch scores before a re-score is required?
2. Data Pipeline and Feature Engineering
Event ingestion architecture:
Stream user interaction events (plays, skips, searches, session boundaries) to a distributed log (Kafka), partitioned by user identifier. This log feeds two parallel consumers:
-
Real-time aggregation engine (Flink or Spark Streaming): Maintains short-window statistics like streams in the past hour/day, recent skip rate, current session duration, and recency metrics. Writes continuously to the online feature store.
-
Raw event archival: Dumps to a data lake in columnar format (Parquet), partitioned by date for efficient historical analysis.
Batch feature computation (daily Spark jobs):
Generate longer-horizon aggregates across 7/28/90-day windows:
- Activity patterns: engaged days, total listening hours, session frequency
- Trend indicators: week-over-week changes, 7-day vs 28-day average comparisons
- Content diversity: unique artists, genre distribution entropy
- Behavior modes: playlist versus search-driven consumption ratios
- Account characteristics: subscription level, payment status, account age, registered device count
Handling high-cardinality features:
Rather than encoding millions of artists or tracks directly, compress listening preferences into:
- A pretrained user embedding (borrowed from the recommendation system or derived via matrix factorization)
- Bucketed genre histograms using feature hashing
- Aggregated artist/track popularity percentiles
Point-in-time correctness:
This is critical to prevent training/serving skew. For each training example at snapshot date T:
- Compute features strictly from data before T
- Store features as dated snapshots
(user_id, date, features)in the offline warehouse - Maintain a shared feature definition registry that both offline (training) and online (serving) pipelines consume
- This ensures identical feature computation logic across training and inference
3. Model Design
Label construction:
For a snapshot at time T, label = 1 if the user has ≥1 stream during [T, T+7 days). Labels only become available after the week elapses, so training data lags by at least seven days.
Generate multiple training snapshots per user (e.g., weekly over six months) to:
- Increase training volume
- Capture seasonal and day-of-week patterns
- Allow the model to learn from users at different lifecycle stages
Apply sample weighting: downsample highly active users (who are ~95% likely to return) and reweight to maintain calibrated probabilities.
Model architecture choice:
Use a gradient boosted decision tree (LightGBM or XGBoost) as the primary model:
- Handles mixed feature types, missing values, and non-linear interactions naturally
- Fast inference (sub-millisecond for ~200 features)
- Produces feature importances for interpretability
- Scales well to hundreds of millions of training examples
Include segment indicators (market, subscription tier, tenure bucket, device type) as features rather than building separate models. With 500M users, the global model has sufficient data to learn segment-specific patterns through interactions.
Handling temporal dynamics:
Capture time dependencies primarily through engineered features:
- Rolling window statistics (1-day, 7-day, 28-day)
- Trend features (slopes, accelerations)
- Recency metrics (days since last activity)
For version 2, consider a sequence model (GRU/Transformer) over daily activity vectors from the past 90 days that produces a "trajectory embedding." Compute this in batch and feed as additional features to the GBDT. This captures sequential patterns without adding deep learning latency to the serving path.
Cold-start strategy for new users:
Build a separate lightweight model for users with tenure < 14 days, using:
- Registration context (geography, acquisition channel, device type, plan type)
- Onboarding signals (genre selections, initial follows)
- First-session engagement depth (streams, saves, minutes within first 24 hours)
Below this threshold, fall back to base rates stratified by acquisition channel and market. Transition to the primary model once sufficient behavioral history accumulates.
Model evaluation:
- Use temporal validation (train on weeks ≤ W, validate on W+2) to respect the time-series nature; never use random splits
- Primary metrics:
- Precision-Recall AUC focusing on the inactive class
- Log loss and expected calibration error
- Recall at top-K% thresholds (where K aligns with campaign budgets)
- Slice metrics by market, subscription tier, and tenure cohort to detect segment-specific issues
- Apply post-training calibration (isotonic regression or Platt scaling) on a held-out recent week
4. Serving Architecture
Batch scoring path:
- Weekly Spark job loads features from the offline store and scores all 500M users
- Writes results
(user_id, probability, model_version, scored_timestamp)to the online score table (DynamoDB/Cassandra) - Also publishes to the data warehouse for audience segmentation and campaign tools
Event-driven re-scoring:
For high-signal profile changes (payment failure, plan upgrade/downgrade, new device registration, onboarding completion):
- Emit event to a scoring queue (Kafka)
- Scoring service fetches user's batch features + latest streaming features
- Runs model inference in-process (GBDT inference takes <1ms)
- Updates the score table with fresh prediction
Query API:
GET /api/v1/activity-forecast/{user_id}
Response: {
user_id,
activity_probability: 0.63,
model_version: "v2.4",
scored_at: "2024-03-15T08:00:00Z",
score_source: "batch" | "realtime" | "fallback",
confidence_indicators: {...}
}
The API performs a single key-value lookup from the precomputed score table—no model execution on the request path. This easily meets the 100ms p99 latency target (typical response in 5-10ms).
Architecture trade-off: Precomputed scores introduce some staleness (up to seven days for batch-only users) but provide robustness and cost-efficiency. Event-triggered re-scoring captures important moments (payment issues, engagement spikes) without continuously scoring all users.
5. Operational Resilience
Data quality monitoring:
- Track feature null rates, schema compliance, and freshness (streaming lag, batch job completion times)
- Implement threshold checks: block score publication if mean prediction shifts beyond expected bounds or if a feature shows anomalous distribution
Distribution drift detection:
- Compute Population Stability Index (PSI) or KL divergence for each feature and for the score distribution, sliced by major segments
- Since ground truth labels arrive seven days delayed, compute realized AUC and calibration metrics weekly
- Alert when metrics degrade beyond thresholds or when prediction distributions shift significantly
Graceful degradation:
When the scoring service fails or features are unavailable, implement a fallback chain:
- Return the most recent score if less than 14 days old
- Otherwise return a segment-specific baseline (average for user's market + tier + tenure bucket)
- Mark degraded scores with
score_source: "fallback"so downstream systems can decide whether to use them
Model rollout process:
- Shadow-score with the new model alongside production
- Compare offline distributions and metric differences
- Canary deploy to a single small market
- Monitor for metric degradation or unexpected behavior before full rollout
Feedback loop considerations:
Once marketing campaigns target low-probability users, the observed outcomes reflect both organic behavior and intervention effects. This creates:
- Selection bias in future training data (low-scorers become more active due to campaigns)
- Potential feedback loops where the model's predictions influence what it learns
Mitigate by:
- Including holdout control groups that don't receive interventions, providing unbiased labels
- Logging campaign exposure as a feature for future model versions
- Periodically retraining on pre-intervention cohorts to recalibrate base rates
6. Common Pitfalls
- Training/serving skew: Using different feature computation logic for training versus production is the most common failure mode. A shared feature registry is essential.
- Ignoring temporal structure: Random train/test splits leak future information and produce overly optimistic metrics that don't reflect real deployment performance.
- Over-engineering for rare cases: Building separate models for dozens of small segments creates operational complexity. Start with a single global model that includes segment features.
- Neglecting calibration: If scores drive budget allocation decisions, poorly calibrated probabilities lead to over- or under-spending. Always validate calibration on held-out data.
- Insufficient cold-start handling: New users represent a significant fraction of the population but require different features and modeling approaches than established users.