Content moderation classifier for social platforms
Machine LearningModel answerLast updated
Design an ML system to flag inappropriate user posts in real time, covering data collection, model architecture, threshold tuning, and production monitoring.
You're building a machine learning pipeline to automatically detect inappropriate content in user-generated posts on a social platform.
Context
Your platform receives approximately 100 million posts daily. A small fraction (well under 1%) violates community guidelines. Human moderators can review roughly 50,000 flagged items per day. The system must make decisions quickly enough not to degrade the user posting experience.
Your Task
Design the end-to-end ML system. Address each of these dimensions:
-
Data collection and labeling. The rate of policy-violating posts is very low, and human raters often disagree on borderline cases. How will you gather training data? How will you handle annotation disagreement and ensure label quality?
-
Model selection. Compare at least two modeling approaches—one lightweight (such as logistic regression with text features) and one deeper (such as a compact transformer). What are the trade-offs for a high-traffic production service? Which would you choose and why?
-
Evaluation and threshold setting. Letting harmful posts through is more costly than incorrectly flagging benign ones. Which metrics matter most? How will you choose classification thresholds when you have actions like auto-remove, send to human review, and allow?
-
Deployment and monitoring. Inference must complete in under 50 milliseconds at the 99th percentile, and language evolves constantly. How will you meet the latency requirement? How will you detect when the model's performance degrades over time?
Assumptions
- You have access to a team of trained human moderators for labeling.
- The platform supports multiple languages.
- You can define what "inappropriate" means for this exercise (hate speech, harassment, spam, etc.).
Hints
Hint 1
Think about mixing random sampling with targeted sampling strategies—relying only on random samples wastes your annotation budget when the base rate is so low.
Hint 2
Consider a tiered architecture: a fast model handles every post synchronously, while a slower, more accurate model processes uncertain cases asynchronously.
Hint 3
Accuracy is a misleading metric when 99%+ of posts are fine—focus on precision-recall curves and measure performance on a holdout set that reflects true prevalence.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This question tests your ability to take a vague product need and turn it into a concrete ML system with realistic constraints. Structure your answer by clarifying scope, then walking through data, modeling, evaluation, and production concerns.
1. Clarify Scope and Scale
Start by asking:
- Pre- or post-publication filtering? Pre-publication blocking enforces the strict 50ms latency limit. Post-publication allows more compute but exposes users to harmful material. Assume pre-publication scoring with an async second pass for borderline cases.
- Policy taxonomy. Is "inappropriate" a single label or does it break into hate speech, harassment, graphic violence, spam, etc.? Design for a multi-label output (one score per category) with a shared encoder, then combine scores into a single routing decision.
- Available actions. Typical options: auto-block, downrank, route to human moderators, or allow.
Scale estimates:
- Average traffic: 100M posts / 86,400 seconds ≈ 1,200 QPS
- Peak traffic (assume 3–5× average): ~5,000 QPS
- Violating posts per day (0.5–1% prevalence): 500k–1M
- Human review capacity: 50k/day (this caps how many borderline items you can route to moderators)
The review-capacity constraint directly shapes your threshold choices.
2. Data Strategy
Collection
Random sampling alone is wasteful when violating content is under 1%. Use a hybrid sampling strategy:
- Random sample (~10% of annotation budget). Provides unbiased prevalence estimates and calibration. Never used to set business thresholds directly, but critical for measuring true performance.
- Targeted samples. User reports, keyword/hash hits, and posts scored high by the current model.
- Active learning. Sample posts with scores near decision thresholds (uncertainty sampling) and posts from underrepresented clusters in embedding space (diversity sampling).
This mix ensures you collect enough positive examples to train on while retaining unbiased slices for evaluation.
Handling Annotation Disagreement
Policy boundaries are subjective. Expect rater disagreement, especially on sarcasm, reclaimed slurs, and cultural context.
- Multiple raters per item. Collect 3–5 labels for contested cases. Measure inter-rater agreement with Fleiss' kappa (extends Cohen's kappa to more than two raters).
- Track annotator quality. Maintain a gold set labeled by policy experts. Measure per-annotator accuracy against it and retrain or down-weight low-performing raters.
- Use soft labels. If 3 of 5 annotators flag a post, train with a target of 0.6 instead of forcing a binary label. Low-agreement items often reveal ambiguous policy—send these to expert adjudication rather than discarding them, since the model must learn exactly these boundary cases.
Handling Class Imbalance
- Downsampling and class weights. Downsample the majority class (for example, to a 1:10 ratio) and apply class weights or focal loss to focus learning on hard examples. Then recalibrate probabilities on a prevalence-matched validation set, because downsampling inflates predicted scores.
- Hard negatives. Collect benign posts that superficially resemble violations—satire, news quotes, reclaimed language—to teach the model nuance.
- Data augmentation. Paraphrase and back-translate to generate variations. Avoid synthetic oversampling like SMOTE; interpolating sparse text vectors produces unrealistic examples.
- Deduplication and hygiene. Use MinHash for near-duplicate detection. Split train/test by time and by author to prevent leakage. Normalize Unicode and handle obfuscation (l33tspeak, zero-width characters).
3. Model Selection
| Approach | Logistic regression + n-grams | Distilled transformer (DistilBERT, XLM-R small) |
|---|---|---|
| Latency | <1ms on CPU | 5–15ms with INT8 quantization, batching |
| Context understanding | Poor (misses negation, sarcasm) | Strong |
| Multilingual | Separate model per language | Single multilingual model |
| Robustness to obfuscation | Weak with word n-grams; char n-grams help | Better with subword tokenization |
| Infrastructure cost | Negligible | Manageable (dozens of GPU instances or hundreds of CPUs) |
Recommendation: Tiered Architecture
- Tier 0 (microseconds): Exact hash and perceptual hash matching against known violating content; blocklists.
- Tier 1 (synchronous, <50ms): Quantized distilled transformer (6 layers, 128 tokens, INT8) runs on every post. Outputs one score per policy category.
- Tier 2 (asynchronous, borderline band only): Larger teacher model with full post thread and author history context. Runs on ~2–5% of posts scored in an uncertain range. Output feeds human review queue.
Distillation approach: Train a large teacher model (XLM-R base or large) on all labeled data. Distill into a 6-layer student by training on the teacher's soft logits over hundreds of millions of unlabeled posts, plus hard labels. This preserves much of the teacher's accuracy in a fraction of the latency.
Keep the logistic regression model as a fallback if the transformer service degrades, but the transformer is your primary path.
4. Evaluation and Threshold Selection
Accuracy is meaningless when 99%+ of posts are fine. A model that predicts "safe" for everything achieves 99% accuracy. Track these instead:
- Precision-Recall AUC (PR-AUC) per policy and per language.
- Recall at fixed precision (e.g., recall at 90% precision) and precision at fixed recall (e.g., precision at 80% recall).
- Prevalence of harmful content seen by users, measured via the random sample (this is the business metric).
- Calibration (Expected Calibration Error), since threshold decisions depend on well-calibrated probabilities.
- Fairness slices: false positive rate across dialects, communities, and identity mentions. For example, African American Vernacular English and reclaimed slurs are historically over-flagged.
Setting Thresholds
You have limited human review capacity (50k/day), so use two thresholds:
- Auto-action threshold (high). Set to achieve precision ≥ 95% to minimize wrongful takedowns. Posts above this are blocked immediately.
- Review threshold (low). Set as low as review capacity allows, maximizing recall. Posts in the middle band go to moderators.
With a calibrated probability p and costs C_FN (letting a violation through) and C_FP (wrongly blocking), the optimal threshold is p > C_FP / (C_FP + C_FN). In practice, C_FN >> C_FP, so this pushes the threshold down.
Critical: Always validate precision on a prevalence-matched evaluation set. Measuring precision on a 1:10 dev set vastly overstates production precision. Run an A/B test (monitoring prevalence, appeal rate, moderator load) before full rollout.
5. Deployment and Monitoring
Meeting Latency Requirements
- Quantization. Export to ONNX or TensorRT with INT8 quantization. Truncate inputs to 128 tokens.
- Batching. Use dynamic batching with a 2–5ms collection window to amortize GPU overhead.
- Caching. Cache scores for reshared or reposted content.
- Timeout fallback. If tier-1 exceeds budget, publish with the tier-0 or fallback score and rescore asynchronously.
Monitoring for Drift
Language and adversarial evasion evolve constantly. Monitor:
- Score distribution shifts. Plot daily histograms of predicted probabilities. A sudden shift suggests drift.
- Random-sample metrics. Track precision, recall, and PR-AUC on the ongoing random sample daily. Alert on drops.
- User appeals and overturns. Rising appeal rates signal calibration drift or policy ambiguity.
- Slice-level performance. Track metrics by language, policy category, and author reputation. New slang or obfuscation techniques often appear in specific communities first.
- Latency and availability. p50, p99, and p999 latency; error rates; fallback invocation rate.
Set up continuous retraining (weekly or biweekly) on fresh labels from the random sample, active learning, and appeals. Version every model artifact and log predictions to enable reproducible debugging.
Common Mistakes
- Relying solely on accuracy or ROC-AUC under extreme imbalance.
- Training on downsampled data but evaluating on the same distribution, inflating precision estimates.
- Ignoring annotator disagreement instead of modeling it.
- Choosing a threshold on a synthetic 1:1 or 1:10 dev set without adjusting for true prevalence.
- Not reserving a random sample for unbiased monitoring.
- Underestimating inference cost and latency at 5k QPS with a large model.
Summary
A production content-moderation system requires hybrid data sampling, soft labels to handle ambiguity, a tiered model architecture balancing latency and accuracy, precision-recall evaluation with prevalence-matched sets, dual thresholds constrained by review capacity, and continuous monitoring for linguistic drift. The key is treating this as a cost-sensitive, highly imbalanced problem where false negatives and false positives have asymmetric costs and must be tuned to operational constraints.