Design a Scalable Video Recommendation Architecture and Logging Engine
Machine LearningModel answerLast updated
Architect a low-latency video feed and next-up system with focus on feature pipelines, stream joins, impression logging, and multi-objective ranking.
Design an end-to-end Machine Learning system for a personalized video streaming service that supports both a continuous Home Feed and a contextual Next Video (Autoplay) feature.
System Requirements & Constraints
- Latency Budget: Provide personalized recommendations within a tight server-side deadline ($p99 \le 200\text{ ms}$).
- Throughput & Scale: Support tens of thousands of requests per second across hundreds of millions of daily active users and a catalog of over 100 million videos.
- Dual Surface Support:
- Home Feed: Long-term preferences, user history, and dynamic interest tracking.
- Next Video: Immediate session context, short-term user transition history, and co-viewing affinities.
- Observability & Logging Infrastructure:
- Define exact payload schema and impression-tracking architecture.
- Join outcome events (clicks, watch time, reactions) to serving features reliably without data leakage or bias.
- Pipeline Architecture: Design both streaming and batch feature generation strategies with online-offline consistency.
- Modeling & Optimization: Outline candidate generation, multi-task ranking objectives, and offline/online evaluation techniques.
Hints
Hint 1
Distinguish clearly between a server-side impression and a client-side viewed impression. Training on items never seen by the user introduces significant noise.
Hint 2
Log features directly at inference time rather than recomputing them asynchronously from feature stores later to prevent point-in-time snapshot leaks.
Hint 3
Address position bias during model training using shallow position towers or explicitly logged position features, then set the position parameter to zero (or top slot) at inference.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Scale Estimation
Traffic & Data Scale
- Active Users: $50\text{M}$ DAU performing an average of $20$ feed/next-up queries daily $\implies 1\text{B}$ requests/day ($\sim 11.5\text{k}$ average QPS, peak $\approx 35\text{k}$ QPS).
- Payload Volume: $20$ candidate items returned per request $\implies 20\text{B}$ served impressions/day.
- Storage Footprint: At $\sim 500\text{ bytes}$ per raw impression event, raw server logging reaches $\approx 10\text{ TB/day}$ prior to downstream feature joins.
- Catalog Scale: $100\text{M}$ active catalog items, with $1\text{M}$ newly ingested items daily (requiring robust cold-start mechanisms).
- Latency Budget: Server-side response time budget is $p99 \le 200\text{ ms}$.
2. API Contract
GET /api/v1/recommendations?surface=home|up_next&user_id=U123&session_id=S456&context_video_id=V789&limit=20
Response Payload:
{
"request_id": "req-98765-abc",
"items": [
{
"video_id": "vid-1111",
"impression_id": "imp-aaaa-1111",
"position": 0,
"source_type": "two_tower_ann"
}
],
"next_cursor": "eyJvZmZzZXQiOjIwfQ=="
}
POST /api/v1/events
Batched Client Event Payload:
{
"events": [
{
"event_id": "evt-001",
"request_id": "req-98765-abc",
"impression_id": "imp-aaaa-1111",
"event_type": "watch_heartbeat",
"client_timestamp_ms": 1710000005000,
"payload": { "watch_time_sec": 10.0, "visible_percentage": 100 }
}
]
}
3. High-Level System Architecture
+-----------------------+
| Client Device |
+-----------+-----------+
|
HTTP Request | Client Events (batched)
(Home / Next) v
|
+-------------------------------------------+-----------------------------------------------+
| ONLINE SERVING LAYER | |
| v |
| +--------------------+ +--------------------+ |
| | API Gateway / Auth | | Ingestion Gateway | |
| +---------+----------+ +---------+----------+ |
| | | |
| v v |
| +--------------------+ +--------------------+ |
| | Retrieval / ANN | | Kafka Event Stream | |
| | (100M -> 1k) | +---------+----------+ |
| +---------+----------+ | |
| | | |
| v v |
| +--------------------+ +--------------------+ +---------------------------+ |
| | Filtering & Light | | Apache Flink | ---> | Feature Store (Online KV) | |
| | Ranker (1k -> 200)| | (Stream Joiner) | +---------------------------+ |
| +---------+----------+ +---------+----------+ ^ |
| | | | |
| v v | |
| +--------------------+ +--------------------+ | |
| | Multi-Task Heavy | | Serving Logger / | | |
| | Ranker (200 -> 20) | | Point-in-time Log | | |
| +---------+----------+ +---------+----------+ | |
| | | | |
+------------|-----------------------------|----------------------------|-----------------+
v v |
+-----------------------------------------------------------------------|-----------------+
| OFFLINE / DATA LAKE STORAGE | |
| | |
| +-----------------------------------+ | |
| | Iceberg / Delta Lake (Data Lake) | | |
| +-----------------+-----------------+ | |
| | | |
| v | |
| +-----------------------------------+ | |
| | Spark Batch Jobs | ---------------------+ |
| +-----------------+-----------------+ |
| | |
| v |
| +-----------------------------------+ |
| | GPU Model Training & Registry | |
| +-----------------------------------+ |
+-----------------------------------------------------------------------------------------+
Retrieval & Ranking Stages
- Candidate Retrieval (100M $\rightarrow$ 1,000): Multi-armed parallel generators:
- Two-Tower Embedding ANN: Approximate Nearest Neighbor search over HNSW indices built using user/session embeddings and item embeddings.
- Session Co-Watch Graph: Real-time key-value lookup of items frequently played immediately following
context_video_id(vital for "Up Next"). - Social / Subscriptions: Fresh uploads from subscribed creators.
- Cold-Start / Exploration: High-velocity new content (<24h old) filtered by category match.
- Hard Filtering: Remove already-watched videos (using a Bloom filter), blocked creators, geo-restricted items, and policy/NSFW flags.
- Light Ranker (1,000 $\rightarrow$ 200): Linear model or small GBDT using basic cross-features to shrink candidate volume prior to neural scoring.
- Heavy Ranker (200 $\rightarrow$ 20): Multi-Task Deep Neural Network scoring multiple objectives simultaneously.
- Re-ranking & Slate Optimization: Applies diversity rules (e.g., max 2 videos per creator), fresh content boosting, and business logic.
4. Observability, Logging, and Data Pipelines
Impression Identity & Stream Joining
Server Impression Event
│
▼
┌───────────────────┐
│ Kafka Event Bus │
└─────────┬─────────┘
│
┌─────────────────────┴─────────────────────┐
│ │
▼ ▼
┌───────────────────┐ ┌───────────────────┐
│ Client Outcome │ │ Serving Log │
│ Events │ │ Features │
│ (Clicks, Watches) │ │ (Snapshot) │
└─────────┬─────────┘ └─────────┬─────────┘
│ │
└─────────────────────┬─────────────────────┘
│
▼
┌────────────────────┐
│ Apache Flink │
│ (Stateful Join) │
└─────────┬──────────┘
│
┌────────────────────┴────────────────────┐
│ 30-Min Early Join Window │ 24-Hour Late Window
▼ ▼
┌────────────────────┐ ┌────────────────────┐
│ Fast Training Data │ │ Final Reconciled │
│ (Near-Real-Time) │ │ Labels (Data Lake) │
└────────────────────┘ └────────────────────┘
- ID Generation: Server generates a deterministic or unique
impression_id = UUIDv4()(orhash(request_id, video_id, position)) on response construction. - Log At Serving Time: To eliminate point-in-time data leakage and feature store retrieval skews, log all calculated feature vectors directly at inference to the data pipeline alongside the
impression_id. Do not recompute features retroactively during training set creation. - Viewed vs. Served:
- Served Impression: The API outputted the item.
- Viewed Impression: Client confirmed the video entered the viewport (e.g., $\ge 50%$ visible for $\ge 1\text{ second}$).
- Rule: Only train ranking models on viewed impressions. Using unviewed served items as implicit negatives distorts loss distributions.
Event Stream Joining (Flink)
- Use Apache Flink to execute a key-by
impression_idstream join between serving feature logs and incoming client outcomes. - Attribution Windows:
- Fast Path (30 minutes): Emit early labels for click-through rate (CTR) and short watch-time events for quick online model updates.
- Reconciliation Path (24 hours): Retain state in RocksDB state backend for up to 24 hours to capture late shares, playlist saves, and complete watch durations. Update data lake records asynchronously.
Addressing Logging Pitfalls
- Position Bias:
- Problem: Top-ranked items receive significantly higher engagement purely due to slot layout.
- Solution: Train models with
positionas a distinct feature column (or pass it through a shallow position network module). During inference, set the position feature to a constant standard baseline (position = 0).
- Missing-Not-At-Random (MNAR):
- Problem: Feedback loops limit logs strictly to items historical systems prioritized.
- Solution: Allocate $1\text{–}2%$ of production traffic to exploratory policy routing (e.g., epsilon-greedy sampling over top candidates). Record item selection probabilities ($\pi(k)$) and apply Inverse Propensity Weighting (IPW) during off-policy model evaluation: $$\text{Loss}{\text{unbiased}} = \sum{i} \frac{y_i \cdot \mathcal{L}(f(x_i), y_i)}{\pi(x_i)}$$
- Idempotency & Retries:
- Clients send an explicit
event_idper batch request. Flink applies a deduplication transformer using a short sliding time window ($5\text{ minutes}$) to discard duplicate retries caused by poor network connectivity.
- Clients send an explicit
5. Feature Engineering Infrastructure
| Pipeline Layer | Engine | Update Latency | Storage Target | Features Extracted |
|---|---|---|---|---|
| Batch | Apache Spark | Daily / Hourly | Iceberg / Offline Feature Store | Long-term user interest vectors, 30-day creator retention profiles, global video quality scores. |
| Streaming | Apache Flink | Real-time ($\approx \text{seconds}$) | Redis / Online Key-Value | Last $N$ watched videos in session, 1-hour item velocity/CTR, instantaneous skip counter. |
| On-Demand | Model Gateway | In-flight ($\le 2\text{ ms}$) | Ephemeral Context Memory | Current time of day, client device, network speed, active session route (Home vs Up Next). |
Feature Store Consistency & Guardrails
- Dual Materialization: Feature definitions written via declarative schemas (e.g., Feast/Tecton) write synchronously to Redis (Online, low latency $p99 < 5\text{ ms}$) and Parquet/Iceberg (Offline, point-in-time joins).
- Schema Versioning: Attach a unique schema version hash to feature payloads. Reject requests in the model server if feature version alignment fails runtime checks.
6. Modeling, Training & Multi-Task Ranking
Candidate Generation (Two-Tower Network)
- User Tower: Deep neural network mapping user demographic data, session history, and short-term clicks to vector $u \in \mathbb{R}^d$.
- Item Tower: Deep network mapping video tags, audio/visual embeddings, and creator metadata to vector $v \in \mathbb{R}^d$.
- Objective: Maximize dot product inner product $u^T v$ via Softmax Loss over sample-softmax negatives, corrected for item popularity bias: $$P(v_i | u) = \frac{\exp(u^T v_i - \log \pi_i)}{\sum_j \exp(u^T v_j - \log \pi_j)}$$
Heavy Ranker (Multi-Gate Mixture-of-Experts Architecture)
Instead of predicting raw CTR alone, employ an MMoE framework to model multi-objective outcomes:
Multi-Objective Predictions
┌───────────────┬───────────────┬───────────────┬───────────────┐
│ p(Click) │ E[WatchTime] │ p(Complete) │ p(Negative) │
└───────▲───────┴───────▲───────┴───────▲───────┴───────▲───────┘
│ │ │ │
┌───────┴───────┬───────┴───────┬───────┴───────┬───────┴───────┐
│ Task Head 1 │ Task Head 2 │ Task Head 3 │ Task Head 4 │
└───────▲───────┴───────▲───────┴───────▲───────┴───────▲───────┘
│ │ │ │
└───────────────┼───────────────┴───────────────┘
│ Gating Networks
▼
┌─────────────────────────┐
│ Multi-Gate Experts │
│ (MMoE Shared Backbone) │
└────────────▲────────────┘
│
Combined Feature Vector
-
Task Heads:
- $\hat{y}_{\text{click}}$: Binary Classification (BCE Loss)
- $\hat{y}_{\text{watch}}$: Regression of log-transformed watch time $\log(1 + \text{duration_sec})$ (MSE Loss)
- $\hat{y}_{\text{finish}}$: Binary Completion Rate $\ge 90%$ (BCE Loss)
- $\hat{y}_{\text{neg}}$: Binary Skip / Hide / Dislike (BCE Loss)
-
Final Score Formulation: $$\text{Score} = w_1 \cdot \hat{y}{\text{click}} + w_2 \cdot f(\hat{y}{\text{watch}}) + w_3 \cdot \hat{y}{\text{finish}} - w_4 \cdot \hat{y}{\text{neg}}$$ Weights ($w_1 \dots w_4$) are dynamically tuned via grid search and online A/B optimization to optimize long-term retention rather than naive clickbait.
7. Serving Infrastructure & Fault Tolerance
Incoming Client Request
│
▼
┌─────────────────────┐
│ Dynamic Budgeter │ (Budget: 200ms)
└──────────┬──────────┘
│
┌────────────┴────────────┐
│ │
[ <160ms ] [ >160ms ] (Deadline Exceeded)
│ │
▼ ▼
┌───────────────┐ ┌─────────────────┐
│ Full MMoE │ │ Fallback Mode │
│ Scoring Route │ │ Light Ranker / │
└───────────────┘ │ Cached Recs │
└─────────────────┘
- Strict Latency Budget Allocations:
- API Routing & Context Retrieval: $15\text{ ms}$
- Candidate Generation (ANN Parallel Query): $35\text{ ms}$
- Feature Store Multi-Get: $25\text{ ms}$
- Light Ranking & Filtering: $25\text{ ms}$
- Heavy Ranker Neural Inference: $70\text{ ms}$
- Re-ranking & Business Rules: $15\text{ ms}$
- Buffer / Network Overhead: $15\text{ ms}$
- Fallback Mechanisms:
- Soft Timeout ($160\text{ ms}$): If the Heavy Ranker times out, bypass neural inference and return candidates ordered directly by the Light Ranker scores.
- Hard Timeout / Infrastructure Failure: Fallback to a pre-cached local Redis list of globally trending and category-popular videos.
- Model Drift & Monitoring:
- Compute Population Stability Index (PSI) hourly across feature inputs.
- Monitor prediction calibration ratio: $\text{Calibration} = \frac{\text{Mean Predicted Probability}}{\text{Observed Empirical Rate}}$. Trigger alerts if calibration drifts by $> 5%$.
8. Privacy & Data Compliance
- Data Minimization & Expiry: Purge fine-grained raw client impression telemetry after 30 days. Maintain anonymized aggregate counts for training features beyond 30 days.
- Right to be Forgotten (GDPR): When a user deletes their profile, purge their identity records from the offline feature store and issue deletion markers to event streams. Replace explicit user identifiers in historical training logs with randomized hash keys.
- Differential Privacy: Inject calibrated Laplacian noise into real-time aggregate video watch counts prior to feature store writes to eliminate side-channel user tracking.