Build a Real-Time Comment Ranking System
Machine LearningModel answerLast updated
Design an ML-powered system to rank comments in discussion threads, balancing quality, safety, and latency at scale.
Problem
You're building a ranking system for discussion threads on a social platform. Each thread contains comments organized hierarchically (replies to comments form a tree structure). Your goal is to order comments so that high-quality discussions appear prominently while minimizing exposure to harmful content.
Requirements
Functionality:
- Promote substantive, constructive comments over low-value ones
- Reduce visibility of toxic, spam, or rule-breaking content
- Support varied perspectives without creating echo chambers
Performance:
- End-to-end page load must complete within 100ms
- Newly posted comments should become rankable within a few seconds
- System must support millions of concurrent threads and billions of daily user interactions
What to Design
Provide a complete ML system design including:
- Architecture overview: How data flows from comment creation through to displaying ranked results
- Modeling approach: What type of model you'd use, what it predicts, and how you'd generate training labels
- Feature engineering: Key signals from comments, authors, viewers, and discussion context
- Trade-off analysis: How you'd handle competing constraints like computational cost versus data recency, and strategies for comments with little interaction history
Hints
Hint 1
Think about how comment ranking differs from feed ranking: the candidate pool is already scoped to one thread, and the structure is hierarchical rather than flat.
Hint 2
Consider separating expensive computations that can be shared across all viewers from lightweight personalization that runs per request.
Hint 3
New comments lack engagement history. What signals are available immediately, and how can you ensure they get enough exposure to gather feedback?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Real-Time Comment Ranking System
Understanding the Problem Space
Comment ranking differs fundamentally from typical feed ranking in three ways:
- Bounded candidate set – you're ordering comments within a single thread, not selecting from a global pool
- Tree structure – comments exist in parent-child hierarchies, not flat lists
- Quality-focused objective – pure engagement (replies, shares) can reward divisive content; you need nuanced quality signals
1. Scope and Scale Analysis
Start by establishing concrete numbers:
- Read traffic: Assume 1 billion thread views daily (~12K requests/second average, ~40K peak)
- User actions: 5 billion daily interactions (~60K events/second average, ~200K peak)
- New content: 10 million comments daily (~120/second average, ~1K/second during live events)
- Thread size distribution: Median thread has 15-20 comments; popular threads reach 10K-100K comments
- Latency budget breakdown: 10ms data fetch + 15ms feature retrieval + 40ms model inference + 10ms post-processing + 25ms margin
Key clarifications to establish:
- Personalization level (per-user versus shared global ranking)
- Handling of logged-out visitors
- Whether content moderation runs before or after ranking
2. System Architecture
Data Stores
Comment database (Cassandra): Core comment data including ID, thread ID, parent reference, author, nesting level, timestamp, and text
Thread index (Redis): Per-thread adjacency lists plus sorted sets (by preliminary score) for each parent's direct children
Real-time features (Redis/ScyllaDB): Streaming aggregates per comment: view count, positive votes, negative votes, response count, flag count, expansion events, cumulative read time
Content analysis cache: Pre-computed text embeddings, safety classifier outputs (toxicity, spam probability)
User profiles: Per-user preference vectors, historical interactions, content sensitivity preferences
Data Flow
Comment creation pipeline (must complete under 5 seconds):
- New comment published to message queue
- Content analyzers run:
- Safety classifiers (compact transformer models, ~5ms GPU inference)
- Text embedding generation
- Semantic relevance to parent and root post
- Features written to cache
- Initial score computed and comment inserted into thread index
Interaction processing:
- User events (votes, reads, flags) stream to message queue
- Stream processor (Flink) maintains windowed aggregates (1-minute, 1-hour, lifetime windows)
- Aggregates update feature store
- Batch job recomputes preliminary scores every 10-30 seconds for recently-active comments
Request serving:
- Retrieve thread structure from index
- Candidate generation:
- Threads under 300 comments: include all
- Larger threads: take top-K children per parent from pre-sorted sets, plus exploration budget (~500 total)
- Scoring: Run multi-task model with batched feature lookups
- Post-processing: Apply diversity constraints, business rules (moderator pins, author rate limits), collapse low-scoring subtrees
- Tree assembly: Order siblings at each level recursively, respecting depth/breadth display limits
- Instrumentation: Log impressions with position and depth for training data
Why Not Embedding-Based Retrieval?
Two-tower retrieval models are unnecessary here since candidates are already scoped to one thread. However, user-comment affinity embeddings remain valuable as input features for the final ranker.
3. Machine Learning Model
Architecture: Multi-task neural network with shared trunk and task-specific heads. Use Mixture-of-Experts structure if tasks have conflicting gradients. For v1, gradient-boosted trees work well.
Prediction heads (all conditioned on impression):
- P(upvote), P(downvote): Direct approval signals
- P(reply), P(high_quality_reply): Conversation generation; filter for non-toxic, substantive responses
- P(expand), P(dwell > threshold): Implicit interest indicators
- P(flag), P(author_block), P(hide): Strong negative signals
Label construction:
Use rate-based labels (actions per impression) rather than raw counts to avoid popularity bias. Handle position bias by either:
- Including position/depth as features during training, then fixing them to neutral values at inference
- Inverse propensity weighting using logged randomization experiments
Scoring function:
final_score = α₁·P(upvote) - α₂·P(downvote)·(1 - controversy_bonus)
+ α₃·P(quality_reply) + α₄·P(dwell)
- α₅·P(flag) - α₆·toxicity_score - α₇·spam_score
Tune coefficients through online A/B tests measured against northstar metrics (session-level quality participation, human rater assessments). Use flag rate and toxicity as hard guardrails with threshold-based demotion.
4. Feature Engineering
Comment-level signals:
- Text representation (embedding), character count, detected language
- Safety scores (toxicity, spam probabilities)
- Age since posting, nesting depth in tree
- Engagement velocity, confidence-adjusted positive ratio (Wilson score), response count and average response quality
- Flag count, whether edited
Author features:
- Reputation score within this community, account tenure
- Historical violation rate (flags, removals)
- Average historical comment quality
Viewer features:
- Community engagement history (affinity vector)
- Prior interactions with this specific author
- Typical reading depth in threads
- Content filter preferences, blocked authors, language
Contextual signals:
- Root post topic embedding, thread age, total comment count
- Semantic alignment with parent comment and root post (detects tangents)
- Sibling count, parent's score
- Whether author is original poster or moderator
- Ideological/stance clustering relative to peer comments
5. Key Trade-offs and Solutions
Computational Cost vs. Freshness
Challenge: Scoring 100K comments per thread per page view is prohibitively expensive.
Solution:
- Compute a shared base score (non-personalized) that updates only when comments receive new interactions, debounced to ~10-30 second intervals
- Cache fully-ranked pages for logged-out traffic (30-60 second TTL on active threads)
- Apply lightweight personalization only to top ~500 candidates
- Result: compute scales with interaction volume, not page views
Cold Start Problem
Challenge: New comments have no engagement history, yet early visibility often determines long-term prominence.
Solution:
- Content-based prior: Immediately available signals include text quality, relevance to parent, safety scores, and author reputation
- Exploration strategy: Treat each comment as a multi-armed bandit. Use Thompson sampling with a Beta prior seeded by content features
- Reserve 5-10% of premium positions (e.g., ranks 3-6) for exploration of recent comments
- Within 2-5 minutes, real engagement data dominates the prior
- Without exploration, early-posted comments capture permanent advantages regardless of quality
Quality vs. Engagement
Challenge: Highly controversial or inflammatory comments generate strong engagement but degrade discussion quality.
Solution:
- Distinguish between response quantity and response quality (filter for substantive, non-toxic replies)
- Incorporate negative signals (flags, hides, blocks) with substantial weight
- Use human raters to validate that high-scoring comments are substantive
- Monitor for "reply-bait" patterns and downweight them
Common Mistakes to Avoid
- Using raw counts instead of rates: Comments visible longer accumulate more votes regardless of quality
- Ignoring position bias: Early-ranked comments get more visibility, creating feedback loops
- Over-indexing on recency: Purely time-based sorting surfaces low-quality recent comments over high-quality older ones
- Neglecting tree structure: Scoring comments independently ignores valuable parent-child context
- Treating all engagement equally: Replies can indicate both interest and outrage
Validation Strategy
- Offline metrics: AUC for each prediction head, calibration curves
- Online metrics: Session quality (time spent, depth explored, return rate), content diversity consumed, flagging rate
- Human evaluation: Rater assessment of top-ranked comments for substantiveness, toxicity, relevance
- A/B testing: Incremental coefficient adjustments with guardrail monitoring
This design balances the three core constraints: promoting quality discussions, maintaining safety, and meeting strict latency requirements at scale.