Build a Recommendation Engine for Content Discovery
Machine LearningModel answerLast updated
Design an ML system that delivers personalized content feeds combining user interests with global trends while maintaining low latency and diversity.
Problem
You're building a content recommendation engine that surfaces interesting articles, questions, and topics to users when they open your application. The system needs to balance what each individual user cares about with what's currently popular or newsworthy across the platform.
Your feed must feel fresh and responsive—new trending content should appear quickly, and recommendations should adapt as users interact with the system. At the same time, you want to avoid creating echo chambers where users only see variations of what they've seen before.
What You Need to Design
Core functionality:
- Generate a ranked list of recommended content items for each user session
- Blend personal preferences (derived from past behavior) with platform-wide signals like trending topics
- Deliver results fast enough that users don't perceive any wait
System properties:
- Support a large user base with millions of daily sessions
- Incorporate new content and trending signals within a few minutes of emergence
- Maintain variety in recommendations to expose users to different topics and perspectives
Areas to Cover
Your design should explain:
- Data collection: What user signals do you capture, and how do you process them at scale?
- Architecture: How do you narrow millions of possible items down to a personalized ranked list? Break down the stages from retrieval through final ordering.
- Handling unknowns: What happens when a user is brand new, or when a piece of content just entered the system?
- Measuring success: Which metrics tell you whether the recommendation engine is working well?
Think through the full machine learning lifecycle—from data ingestion and feature engineering through model serving and feedback loops.
Hints
Hint 1
Start by establishing the scale: how many users, how many content items, how many events per second? These numbers drive your architectural choices.
Hint 2
A multi-stage funnel works well: first cast a wide net to find thousands of candidates quickly, then rank them carefully with a more expensive model.
Hint 3
The system creates its own feedback loop—you only observe outcomes for items you showed. Consider how this selection bias affects model training.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Content Discovery Recommendation Engine
Step 1: Establish Scale and Requirements
Begin by quantifying the problem. Suppose we have:
- 15M daily active users, each checking the feed 4 times per day = 60M requests/day ≈ 700 QPS average, 4k QPS peak
- 1.5M active content items in the catalog, with 8k new items added hourly
- 40 interaction events per user daily (views, clicks, time spent, shares) = 600M events/day ≈ 7k events/second
- Latency requirement: 95th percentile under 100ms end-to-end
Break the latency budget across stages:
| Component | Time Budget |
|---|---|
| User feature lookup | 10ms |
| Candidate retrieval | 25ms |
| Scoring model | 35ms |
| Reranking & diversity | 15ms |
| Buffer | 15ms |
Success definition: Optimize for meaningful engagement—time spent reading plus downstream actions like saving or sharing, not just raw clicks.
Step 2: API Design
GET /api/feed?user_id=<id>&page_token=<token>&count=25
Returns: {
items: [{id, title, type, snippet, reason}],
next_page_token,
session_id
}
POST /api/events (batched)
Body: [{
session_id, item_id, event_type,
position, duration_ms, timestamp
}]
The session_id connects every displayed item back to the exact model version and candidate set that produced it—essential for training data attribution.
Step 3: Data Schema
Content catalog (key-value store):
- Metadata: title, category, source, publication timestamp
- Text embedding (768-dim vector for semantic retrieval)
- Entity tags and topic classifications
- Quality signals: source credibility, content depth
User profiles (low-latency cache):
- Long-term interest embedding (updated daily)
- Topic preference distribution
- Recent interaction history (last 100 items)
- Bloom filter of previously seen items (prevents repetition)
Real-time aggregates (stream processing state):
- Per-item metrics in sliding windows (5min, 1hr, 24hr): view count, engagement rate, velocity
- Trending spike detection: compare recent rate to baseline
- Geographic and demographic breakdowns
Event stream (message queue → data warehouse):
- Raw impression and interaction logs for offline training
Step 4: Data Pipeline Architecture
Real-time path:
- Client batches events and sends to collector service
- Events flow into a stream processor (like Flink)
- Compute engagement labels: "satisfied click" = dwell time >30s or follow-up action
- Update item-level counters and user short-term features within seconds
- Trending detection: flag items whose engagement rate exceeds 3 standard deviations above baseline
- Push feature updates to online serving stores
Batch path:
- Daily/hourly jobs join logged impressions with outcomes
- Critical: log features at inference time to avoid training/serving skew
- Generate training examples with proper labels
- Retrain ranking models on GPUs
- Rebuild user long-term embeddings from interaction history
- Update content embeddings for new items
Addressing selection bias: The model only observes outcomes for items it chose to show. To correct this:
- Include position bias as a feature (then set to neutral value at inference)
- Apply inverse propensity weighting during training
- Reserve 2-5% of traffic for randomized exploration to gather unbiased data
Step 5: Three-Stage Ranking Pipeline
Stage 1: Candidate Retrieval (millions → thousands)
Run multiple retrieval strategies in parallel, each with a quota:
Semantic matching (~500 items): Use a two-tower neural network. The user tower encodes profile + recent behavior + context. The item tower encodes content. Store item embeddings in an approximate nearest neighbor index (HNSW). Query returns semantically similar items in <20ms. Incremental index updates ensure new content is searchable within minutes.
Collaborative filtering (~300): Find items popular among users with similar taste profiles using matrix factorization or learned embeddings.
Trending pool (~200): Pull from real-time trending lists, filtered by coarse topic alignment with user preferences.
Explicit signals (~100): Items from topics the user explicitly follows or searches frequently.
Exploration pool (~100): High-quality items from categories the user hasn't engaged with, supporting serendipity.
After merging, apply fast filters: remove already-seen items (bloom filter check), filter unsafe content, and drop stale items outside the relevance window.
Stage 2: Ranking Model (thousands → hundreds)
Model choice: Gradient boosted trees (LightGBM/XGBoost) or a neural architecture like Deep & Cross Network. Use multi-task learning to predict:
- P(click)
- P(long dwell | click)
- P(save or share)
- P(hide or negative feedback)
Scoring function: Combine predictions with tuned weights:
score = 0.25·P(click) + 0.45·P(dwell) + 0.35·P(share) - 0.8·P(hide) + freshness_boost
Features:
- User-item embedding cosine similarity
- Topic affinity scores
- Item velocity and trending signals
- Content age with decay
- Source authority score
- Real-time engagement rates
- Contextual: time of day, device type, user session state
- Cross features: user category preference × item category
Serving: Score ~2,000 candidates in a single forward pass. With batching and efficient inference (ONNX runtime or TensorRT), this fits the 35ms budget.
Stage 3: Re-ranking and Diversity (hundreds → final list)
Diversity injection: Use Maximal Marginal Relevance—iteratively select items that balance high score with low similarity to already-selected items. Enforce rules like maximum 3 items per topic in top 20.
Exploration slots: Allocate 2-3 positions to exploration using Thompson sampling or epsilon-greedy. Maintains discovery and gathers data on uncertain items.
Business rules: Deduplicate near-identical content, apply safety filters, boost breaking news during high-velocity events.
Step 6: Cold Start Strategies
New users:
- Show a popularity-based feed segmented by signup source, location, and device
- Optional onboarding quiz to capture initial interests
- First search query provides strong signal—immediately incorporate into retrieval
- Higher exploration rate (15% vs 5% for established users)
- Treat as a contextual bandit: optimize category allocation to find user preferences quickly
New content:
- Content-based features (text embedding, topic, source) enable immediate retrieval
- Guarantee minimum impressions (exploration budget) until statistical confidence builds
- Use upper confidence bound scoring: rank by optimistic engagement estimate to give new items a chance
Step 7: Evaluation Framework
Offline metrics:
- Recall@K and NDCG@20 on held-out logged data
- Prediction calibration for each task head
- Diversity: average pairwise cosine distance in recommended lists
- Counterfactual evaluation using propensity scoring on randomized traffic
Online metrics (A/B tests):
Primary: Engaged sessions per user (sessions with >60s dwell or downstream action)
Secondary:
- Click-through rate
- Average dwell time per item
- Share and save rates
- Session depth (items consumed per visit)
Long-term health:
- User retention (D7, D30)
- Topic diversity score: entropy of categories engaged over 30 days
- New vs returning content ratio consumed
Guardrails:
- Negative feedback rate (hides, reports)
- 99th percentile latency
- Fraction of low-quality sources shown
- Freshness: median age of content in feeds
Run experiments for 1-2 weeks to capture weekly patterns and longer-term retention effects.
Common Pitfalls
Ignoring position bias: Users click top items more regardless of relevance. Always log position and account for it.
Optimizing for clicks alone: Leads to clickbait. Measure downstream satisfaction.
Static embeddings: User interests drift. Update embeddings regularly from recent behavior.
No exploration: Model learns only about items it shows, creating information cascades. Deliberate randomization breaks this.
Cold start abandonment: New users who see generic content may never return. Aggressive personalization from minimal signals (first query, signup context) improves retention.
This design balances personalization with discovery, real-time responsiveness with computational efficiency, and short-term engagement with long-term ecosystem health.