Architecting a News Feed Comment Ranking System
Machine LearningModel answerLast updated
Design an end-to-end machine learning system to rank comments on high-traffic posts, balancing user engagement, content quality, low latency, and cold-start handling.
Problem Statement
Design an end-to-end machine learning architecture to rank user comments on a high-traffic social news feed. The objective is to surface high-quality, engaging discussions while actively filtering out toxic content, spam, and low-effort noise.
The system serves a platform with hundreds of millions of active users where viral posts can quickly rack up thousands of comments.
Key Requirements
-
Functional Requirements:
- Deliver a personalized, ordered list of top-level comments and nested reply previews whenever a user expands a comment thread.
- Boost constructive engagement (likes, high-quality replies, long dwell time) while suppressing negative interactions (reports, hides, block actions, toxicity).
- Address the cold-start problem for newly posted comments so good content rises quickly.
-
Non-Functional Requirements:
- Low Latency: p99 latency must be under 100ms for thread retrieval and ranking.
- Scalability: Handle high read traffic (10,000+ QPS at peak) and rapid incoming comment velocity during breaking news events.
- Freshness: Newly created comments must be eligible for candidate generation within seconds, and interaction counters (e.g., vote counts) must update within minutes.
System Scope & Expectations
Walk through the complete system lifecycle, covering:
- Problem Formulation & Optimization Objectives
- Data Pipeline & Feature Engineering
- Multi-Stage Serving Architecture (Retrieval, Filtering, Heavy Ranking, Policy)
- Machine Learning Model Architecture & Loss Functions
- Offline & Online Evaluation Strategy (including guardrail metrics and bias mitigation)
Hints
Hint 1
Break the serving workflow into distinct stages: lightweight candidate generation, hard integrity filtering, deep ranking, and business rule re-ranking.
Hint 2
Consider how to combine multiple distinct interaction probabilities (likes, replies, reports) into a single composite score while maintaining modular control.
Hint 3
Address position bias explicitly in your training strategy; otherwise, top-ranked comments will dominate engagement loops artificially.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Scale Estimation
Traffic & Volume Scale
- Daily Active Users (DAU): ~200 Million.
- Thread Open Load: ~25% of users open 4 comment threads daily $\rightarrow$ 200M thread views/day (~2,300 average QPS, ~10,000 QPS peak).
- Comment Creation Load: ~50M new comments created daily (~600 writes/sec average, with spikes up to 3,000/sec during viral events).
- Thread Distribution: Median post contains $<20$ comments; tail posts exceed $100,000$ comments.
System Constraints
- Latency Budget: End-to-end p95 $< 60\text{ ms}$, p99 $< 100\text{ ms}$.
- Data Freshness: New comments indexed within $< 5\text{ seconds}$; engagement counts updated within $< 1\text{ minute}$.
2. Problem Formulation
We model comment ranking as a Personalized Multi-Task Pointwise Learning-to-Rank (LTR) problem.
Given a tuple $(U, P, C, E)$ representing User $U$, Post $P$, Comment candidate $C$, and Context $E$ (device, time, network), the model predicts the probabilities of distinct user interactions:
$$\hat{y}{\text{like}} = P(\text{like} \mid U, P, C, E)$$ $$\hat{y}{\text{reply}} = P(\text{constructive reply} \mid U, P, C, E)$$ $$\hat{y}{\text{dwell}} = P(\text{dwell time} > 5\text{ seconds} \mid U, P, C, E)$$ $$\hat{y}{\text{report}} = P(\text{report/hide/dislike} \mid U, P, C, E)$$ $$\hat{y}_{\text{toxic}} = P(\text{violates safety policy} \mid C)$$
Composite Utility Score
Rather than optimizing a single opaque implicit metric, we combine predictions into a configurable value function:
$$\text{Score}(U, P, C) = w_1 \cdot \hat{y}{\text{like}} + w_2 \cdot \hat{y}{\text{reply}} + w_3 \cdot \hat{y}{\text{dwell}} - w_4 \cdot \hat{y}{\text{report}} - w_5 \cdot \hat{y}_{\text{toxic}}$$
- Why non-learned linear weights? Decoupling task probability estimation from business utility allows product and safety teams to adjust demotion penalties (e.g., tightening toxic content weighting during elections) without retraining multi-gigabyte neural networks.
Position Bias & Label Quality Strategy
- Position Bias Correction: Users naturally click and like the top 3 comments. We handle this during training by adding
position_loggedas an explicit input feature to the ranker. During online inference, this feature is set to a fixed baseline constant (e.g.,position = 0or average median index) to evaluate intrinsic item quality. - Impression Sanity: Unseen items logged below the user's viewport scroll boundary are excluded from negative loss calculations.
- Reply Weight Filtering: A reply to a comment only counts as a positive $\hat{y}_{\text{reply}}$ signal if the downstream reply itself does not get reported or deleted within 24 hours.
3. System & Serving Architecture
To achieve sub-100ms p99 latency on posts with 100k+ comments, we execute a multi-tier pipeline:
[ Client Request ]
│
▼
┌───────────────────────────┐
│ API Gateway / Router │
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Candidate Retrieval │
│ (~500 items, < 10ms) │
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Fast Hard-Filter Stage │
│ (Toxicity/Block lists) │
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Feature Hydration Engine │
│ (Redis / Feature Store) │
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Multi-Task Heavy Ranker │
│ (DNN / MMoE, < 35ms) │
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Re-Ranking & Business │
│ Rules (Diversity/Explore) │
└─────────────┬─────────────┘
│
▼
[ Final Output ]
Stage 1: Candidate Generation (Retrieval)
For threads with $> 200$ comments, we retrieve a max candidate set of $N = 500$ via multi-channel heuristics:
- Top-Quality Candidates (250): Fetched from Redis Sorted Sets indexed by a decay-smoothed engagement score (Bayesian smoothed upvote rate with exponential age decay).
- Recent Candidates (100): Chronologically newest comments to satisfy freshness requirements.
- Social Candidates (100): Comments made by the viewer's direct connections or replies directed to the viewer.
- Exploration Candidates (50): Random selection from low-exposure comments ($<50$ views) to solve cold-start sampling bias.
Note: For small posts ($< 200$ total comments), bypass candidate retrieval and send all candidates directly to filtering.
Stage 2: Hard Filtering
- Drop comments from accounts blocked by or blocking the viewer.
- Filter out candidates flagged by the asynchronous near-real-time toxicity classifier (score above absolute removal threshold $\tau_{\text{remove}}$).
Stage 3: Feature Hydration & Heavy Ranking
- Batch fetch dense real-time counters and static embeddings from low-latency cache stores (e.g., Redis cluster).
- Pass candidates to the Multi-Task Neural Network running on GPU/Triton Inference Server cluster.
Stage 4: Business Rules & Re-ranking
- Author Diversity: Cap at max 2 top-level comments per author in the top 10 items.
- Freshness Allocation: Reserve slot #4 or #7 for high-potential cold-start candidates.
- Thread Grouping: Attach top 2 nested sub-replies under their parent comments.
4. Feature Engineering
| Feature Category | Source | Features | Update Frequency |
|---|---|---|---|
| Comment Static | Natural Language Processing | Text embedding (128-d distilled Multilingual Transformer), text length, sentiment score, language, toxicity score | Compute once on write |
| Real-time Interaction Counters | Real-Time Stream (Apache Flink) | Short-term likes, replies, and reports over 5m, 1h, and 24h windows; interaction velocity | Streaming (seconds) |
| Author Profile | Batch Data Store | Historical report rate, account age, total upvotes received, verification status | Daily Batch |
| Viewer Profile | Feature Store | Language preferences, historical interaction distributions (like/reply ratios), activity tier | Daily Batch |
| Cross / Context | Online Compute | Viewer-Author Social Affinity Score (is_friend, follow_degree), Language Match boolean, Time elapsed since post creation, Device type | Computed at Request Time |
5. Model Architecture: Multi-Gate Mixture-of-Experts (MMoE)
Using separate models per task creates huge operational overhead. A naive shared-bottom architecture suffers from negative transfer when tasks conflict (e.g., predicting a High-Dwell vs. High-Report probability). We use an MMoE (Multi-gate Mixture-of-Experts) deep network.
[P(Like)] [P(Reply)] [P(Dwell)] [P(Report)] <-- Task Heads
│ │ │ │
┌───┴───┐ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐
│Tower 1│ │Tower 2│ │Tower 3│ │Tower 4│ <-- Task-Specific Layers
└───┬───┘ └───┬───┘ └───┬───┘ └───┬───┘
▲ ▲ ▲ ▲
└────────────┼────────────┼────────────┘
│ Softmax Gates
┌─────────┼─────────┐
│ Gating Networks │
└─────────┬─────────┘
│
┌────────────────┴────────────────┐
│ Expert Networks (1..K shared) │ <-- Feed-Forward Layers
└────────────────┬────────────────┘
│
▲
[ Input Dense Features ]
Architectural Breakdown
- Input Layer: Concatenation of sparse IDs (via embedding lookup layers), numerical real-time features (log-transformed and normalized), and precomputed text embeddings.
- Shared Experts: $K$ parallel feed-forward sub-networks that capture shared semantic representations across all tasks.
- Task Gates: Each task (Like, Reply, Dwell, Report) has a linear gating network with a softmax activation that dynamically weights the outputs of the $K$ shared experts for that specific task: $$g^k(x) = \text{Softmax}(W_g^k \cdot x)$$
- Task Towers: Independent multi-layer perceptrons (MLPs) sitting above the gating layers, leading to individual output nodes outputting probabilities normalized via Sigmoid function.
Loss Function
We optimize a combined Multi-Task Cross-Entropy Loss:
$$\mathcal{L}{total} = \sum{t \in \text{Tasks}} \alpha_t \cdot \text{Loss}_t (y_t, \hat{y}_t)$$
Where $\text{Loss}_t$ is Binary Cross-Entropy (BCE) for interaction tasks, and focal loss for highly imbalanced labels like severe toxicity or user reports.
6. Offline Evaluation & Online Experimentation
Offline Evaluation Strategy
- Metrics per Task: Measure ROC-AUC and PR-AUC independently for each task head. Track Calibration Error (Expected Calibration Error - ECE) to guarantee that absolute output probabilities maintain true statistical meaning prior to linear scoring combination.
- Ranking Metrics: Evaluate NDCG@5 and NDCG@10 on historical sessions using the linear utility score.
- Slice Analysis: Track offline performance across sub-populations:
- Cold-start comments ($< 15$ minutes old).
- High-traffic vs. niche posts.
- Non-English language segments.
Online Experimentation & A/B Testing
When deploying a new model candidate, evaluate across a 2-week window with post-level randomization (to avoid inter-user network interference effects):
- Primary Success Metrics:
- Meaningful Social Interactions (MSIs): Total quality replies and likes per thread view.
- Thread Return/Dwell Rate.
- Guardrail Metrics:
- Report/Hide Rate per 1,000 comment impressions.
- Prevalence of policy-violating content in top-3 slots (measured via continuous human review of random control/treatment samples).
- Latency Metrics ($p95, p99$ overall execution duration).
- Unique Author Impression Coverage (ensuring top positions aren't dominated by a tiny fraction of power users).
7. Key Trade-Offs & Failure Modes
- Personalization vs. Cache Efficiency:
- Trade-off: Generating candidate lists per-user maximizes relevance but eliminates shared server-side caching.
- Mitigation: Execute candidate retrieval and initial quality ranking globally per post (cacheable in Redis for 10–30 seconds), then apply personalized feature hydration and heavy multi-task ranking only on the final top 50 candidates at request time.
- Feedback Loop / Winner-Take-All Bias:
- Risk: Early top-ranked comments accumulate likes fast, starving new high-quality comments from receiving exposure.
- Mitigation: Apply an $\epsilon$-greedy or Upper Confidence Bound (UCB) exploration strategy to reserve top-10 slots specifically for low-impression candidates, collecting unbiased feedback to refine their real-time quality scores quickly.