ML Infrastructure for Real-Time Engagement Prediction
Machine LearningModel answerLast updated
Build an end-to-end platform for predicting user engagement likelihood, covering feature pipelines, online/offline stores, training workflows, and high-throughput inference.
Problem
You're designing infrastructure for a machine learning system that predicts whether a user will engage with content (such as leaving a comment on a social media post). Your interviewer clarifies that you should treat the predictive model itself as given—your focus is on the platform and infrastructure that surrounds it.
Scope
Design a production system that handles:
- Offline components: generating training datasets, orchestrating model training, versioning artifacts
- Online components: serving predictions in real-time at scale, fetching features with low latency
- Feature infrastructure: managing features across batch and streaming pipelines, maintaining consistency between training and serving
- Operational concerns: monitoring model and data health, handling failures gracefully, supporting experimentation
Context and Constraints
Make reasonable assumptions, but state them explicitly. Consider:
- Scale: The system serves predictions for a high-traffic consumer application (tens of thousands of requests per second at peak)
- Latency: End-to-end prediction latency must stay within 50–150 ms at p95
- Feature freshness: Some signals need near-real-time updates (within seconds or minutes)
- Consistency: Training data must reflect what the model actually sees during inference
- Cold start: The system must handle new users and new content gracefully
- Iteration: Support safe model rollout, A/B testing, and rapid experimentation
What to Cover
Explain your approach to:
- Event collection and labeling: What data gets logged, how labels are defined and joined
- Feature management: Batch vs. streaming features, online/offline stores, preventing training-serving skew
- Training workflows: Dataset construction, versioning, evaluation, promotion criteria
- Serving architecture: Real-time vs. batch inference, caching strategies, fallback mechanisms
- Production operations: Monitoring (data quality, model performance), retraining triggers, reliability patterns
Be concrete about trade-offs and failure modes. The interviewer may drill into any component.
Hints
Hint 1
Think about how to ensure features computed offline for training exactly match those fetched online during inference
Hint 2
Consider which features can be precomputed vs. must be computed per-request, and how caching reduces load
Hint 3
Plan for what happens when feature lookups time out or models fail—graceful degradation matters at scale
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: ML Infrastructure for Real-Time Engagement Prediction
1. Clarifying Scope and Scale
Prediction objective. We're estimating P(user engages | user, content, context) where "engagement" means an action (e.g., commenting) within a defined window after exposure. Key decisions:
- Label window: 24 hours is common—captures most organic engagement while keeping labels reasonably fresh
- Negative definition: A negative is "content shown and viewed for ≥1 second, no engagement." Content never rendered shouldn't count (introduces noise)
- Use cases: Feed ranking needs real-time scoring; notification targeting can use batch scoring
Scale assumptions (state these explicitly):
- 50M daily active users
- 15k queries per second at peak (feed requests)
- ~250 content items scored per request → ~3.75M item-level predictions/sec
- Latency budget: p95 ≤ 100ms total, with ~30ms for feature fetch, ~50ms for model inference, ~20ms overhead
- Event volume: ~8B impressions/day, ~2TB/day compressed logs
- Base engagement rate: ~1–3% of impressions
The millions-per-second inference requirement drives architectural choices around batching, caching, and precomputation.
2. Event Collection and Label Generation
Event streams. Clients and backend services emit structured events to Kafka:
impression(request_id, user_id, content_id, position, surface, dwell_time_ms)engagement(user_id, content_id, action_type, timestamp)content_published,user_action,moderation_event
Every event includes request_id and model_version to enable precise label attribution and debugging.
Logging served features (critical for consistency). The inference service asynchronously writes the exact feature vector used for each prediction to Kafka, keyed by (request_id, content_id). This becomes the ground truth for training data—we join logged features with labels rather than reconstructing features later, which eliminates a major source of training-serving skew.
Label pipeline. A stream processor (Flink or Spark Structured Streaming) joins impression events with engagement events on (user_id, content_id) within the time window. Labels are emitted only after the window closes to avoid partial data. Deduplication by event_id handles retries.
3. Feature Store Architecture
Features fall into tiers based on freshness and computation cost:
| Tier | Examples | Computation | Update Frequency |
|---|---|---|---|
| Batch | User 30-day engagement rate, content historical performance, user-content affinity embeddings | Spark jobs on warehouse | Hourly or daily |
| Streaming | Content engagement in last 5min/1hr, engagement velocity, user recent session activity | Flink windowed aggregations | Seconds to minutes |
| Request-time | Position in feed, time-of-day, time-since-publish, embedding similarity scores | Computed in inference service | Per-request |
| Content-time | Text embeddings, image features, safety scores | Async inference on content creation | Near-instant (seconds) |
Online store. A distributed key-value system (Redis cluster or Cassandra) stores materialized features:
user:{id}→ feature vector (protobuf or flatbuffer)content:{id}→ feature vectoruser_content:{uid}:{cid}→ pairwise features (if needed)
Use compact serialization and versioned schemas. Content features are heavily reused across users, making them ideal for aggressive caching.
Offline store. Timestamped feature tables in a data warehouse (Delta/Iceberg) enable point-in-time-correct joins for training data, capturing what features looked like historically. Streaming features are also written here with event timestamps.
Preventing skew:
- Single codebase for batch and streaming feature transforms
- Training data uses logged features as the default source
- Daily validation job recomputes a sample of logged features from offline store and alerts on divergence (>1% mismatch rate)
4. Training Pipeline
Dataset construction:
- Join logged features with labels over a rolling window (e.g., last 30 days)
- Downsample negatives (keep ~10% given low base rate) and record sampling weight for calibration
- Generate train/validation/test splits with temporal holdout (never leak future into past)
Versioning. Every dataset gets an ID encoding:
- Date range
- Feature schema versions
- Label definition (window, negative criteria)
- Sampling parameters
- Code commit hash
Datasets and models are stored immutably with full lineage—any model can be reproduced from its dataset ID.
Training orchestration (Airflow/Kubeflow):
- Daily full retraining or warm-start from previous checkpoint
- Optional incremental updates every few hours for time-sensitive features
- Workflow: build dataset → train → offline evaluation → conditional promotion
Offline evaluation gates (all on fixed holdout set):
- Logloss and AUC
- Calibration: mean predicted / mean observed ≈ 1.0 (critical for downstream use)
- Slice metrics: performance on new users, new content, different content types, geos
- No slice can regress beyond a threshold (e.g., >2% relative logloss increase)
A model is promoted to candidate status only if it beats the current production model on all gates.
5. Online Inference Architecture
Client → Feed Service → Inference Service (autoscaled, stateless)
├─ Feature Fetcher
│ ├─ User lookup (1 call)
│ └─ Batched content lookups (1 multi-get for 250 items)
│ └─ In-process LRU cache for content features (TTL: 60s)
├─ Request-time feature compute
├─ Model Server (TensorFlow Serving / Triton, dynamic batching)
└─ Async logger → Kafka (features + scores)
Batching strategies:
- Feed ranking: real-time inference required, but content features cached aggressively (popular content hit rate >80%)
- Notifications: batch-scored periodically (every 15–30 min), top-K per user written to queue
- Embeddings: precomputed in batch, online service just does dot products
Caching:
- Content features cached in-process (popular content dominates traffic)
- User features fetched once per request
- Optionally cache final scores for (user, content) pairs with short TTL for pagination/re-ranking
Graceful degradation:
- Per-feature timeouts (15ms). On timeout, use defaults learned during training plus a "missing" indicator feature
- Model server timeout → fall back to lightweight baseline (logistic regression on core features)
- Full failure → heuristic scoring (content popularity × recency)
- All fallbacks logged with
fallback_levelfor monitoring
6. Monitoring and Operations
Data monitoring:
- Feature distributions: alert on drift beyond p99 thresholds (e.g., mean shifts >3σ)
- Null rates, staleness (comparing event timestamps with wall clock)
- Label distribution shifts (sudden changes in engagement rate)
Model monitoring:
- Online calibration: track predicted vs. observed in 1-hour buckets
- Slice-level metrics: engagement rate by content type, user segment, time-of-day
- Latency: p50/p95/p99 for feature fetch, inference, end-to-end
- Fallback rate: percentage of requests using degraded modes
Retraining triggers:
- Scheduled: daily or every few hours
- Triggered: when performance degrades beyond threshold or data drift detected
- Manual: for major feature changes or architecture updates
A/B testing:
- Shadow mode: new model scores logged alongside production, no traffic impact
- Small-scale A/B (1–5% traffic) with online metrics (engagement rate, user satisfaction)
- Gradual rollout with automated rollback on metric regression
Reliability patterns:
- Multi-region deployment with failover
- Circuit breakers on downstream dependencies (feature store, model server)
- Request hedging for p99 latency (send duplicate request after p95 timeout)
- Load shedding during overload (drop low-priority requests, return cached scores)
Common Pitfalls
- Feature skew: Recomputing features at training time instead of using logged values
- Label leakage: Using features that contain future information at training time
- Cold start ignored: No fallback for users/content without features
- Single point of failure: Model server or feature store down → entire system fails
- Calibration neglected: Downstream systems depend on well-calibrated probabilities
- No versioning: Can't reproduce old models or debug production issues
Summary
A production ML platform for real-time engagement prediction requires careful orchestration of data pipelines, feature stores, training workflows, and serving infrastructure. The key insight is that logging features at serving time is the most reliable way to prevent training-serving skew. Combine this with layered caching, graceful degradation, and comprehensive monitoring to build a system that is both performant and reliable at scale.