Real-Time Harmful Content Screening for an Image-Sharing Platform
Machine LearningModel answerLast updated
Design an ML pipeline that screens uploaded images, captions and links for spam, phishing and unsafe imagery within a tight latency budget while keeping false positives low.
Screening Uploaded Posts for Harmful Content
You are building the safety layer for a large image-sharing platform that stores billions of user posts. Each post has an image, a title and description, and an optional outbound link. Design an ML system that decides, as part of the upload request, whether a post is harmful (spam, phishing, unsafe imagery, and similar).
Requirements
Functional
- Judge each post using both the image and its metadata (text and link URL).
- Produce a decision that the upload flow can act on immediately.
Non-functional
- Latency: the decision must be available within about 200 ms of the upload request.
- Throughput: thousands of requests per second, with peak bursts above the average.
- Quality: precision must be high, because wrongly punishing legitimate creators is expensive.
What your answer should cover
- Data strategy: where ground-truth labels come from, how you cope with harmful posts being rare, and how you avoid biased evaluation.
- Model and pipeline: feature extraction for images, text and links, how you combine them, and which models you pick.
- Serving: how the model plugs into the upload path, how you meet the latency target, and what happens when the model is slow or down.
- Feedback loop: how user reports and moderator decisions flow back into training and thresholds.
- Adversarial robustness: how you stop bad actors from probing the system to find blind spots.
State your assumptions about traffic, base rates and targets explicitly, and discuss the trade-offs behind your choices.
Hints
Hint 1
A yes/no verdict is too coarse. Consider a small set of graded actions (allow, limit reach, send to review, block) so that only very confident cases are blocked automatically.
Hint 2
Split the work: a fast synchronous path made of cheap checks that clears most traffic, and a heavier or slower asynchronous path that can retroactively remove content. Decide in advance whether each failure mode fails open, fails soft or fails closed.
Hint 3
Moderators only see what the model flagged, so the labels are biased by the system itself. Think about how a random audit sample, hard-negative mining and reporter reliability weighting would fix this, and what an attacker can learn from your API responses.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is a trust-and-safety system, not just a classifier. The four ideas that make the design work are graded actions instead of a binary verdict, a split between synchronous and asynchronous work, awareness that labels are biased by the system itself, and treating the adversary as a first-class concern.
1. Assumptions and targets
- Traffic: about 3-5K QPS average, peaks near 15K. Re-shares of existing posts can reuse cached verdicts.
- Base rate: harmful content is roughly 0.1-1% of uploads, mostly spam. Phishing and explicit imagery are rarer but more severe.
- Latency: p99 under 200 ms for the synchronous decision.
- Precision: about 95-98% or better at the auto-block threshold, with a lower bar for softer actions.
- Taxonomy: spam, phishing/malware, adult, violence, self-harm. Each policy gets its own head and threshold because costs differ.
Output is an action, not a label:
| Action | Use |
|---|---|
| Allow | Low risk |
| Allow with limited reach | Hidden from recommendations and search until rescored |
| Human review | Uncertain |
| Block | High confidence |
Borderline items go to softer actions, so the block threshold can be very strict without sacrificing overall recall.
2. Synchronous pipeline (a cascade, cheap to expensive)
- Stage 0, lookups (~5 ms). Perceptual hash (PDQ/pHash) match against known-bad images, URL and domain blocklists, and a cache of earlier verdicts. A hit gives a deterministic action.
- Stage 1, lightweight model (~10 ms). Gradient-boosted trees on cheap features: account age and trust, prior violations, upload velocity, domain reputation, URL lexical features (shorteners, odd TLDs, homoglyphs), and text n-grams. This clears the 80-90% of traffic that is obviously safe and catches blatant spam.
- Stage 2, multimodal model (~60-100 ms on GPU). Only for uncertain or low-trust content.
- Image embedding from a CLIP-style vision transformer.
- Text embedding of title and description from a multilingual encoder.
- Image-text similarity (a "free phone" caption on an unrelated picture is a spam signal) and OCR text extracted from the image, which catches text baked into pixels to dodge text filters.
- Concatenate embeddings with Stage 1 features and feed a small MLP with one head per policy.
- Calibrate each head (Platt or isotonic) so a threshold corresponds to a measured precision.
3. Asynchronous pipeline (seconds to minutes)
- A sandboxed crawler fetches the landing page and looks for credential forms, redirect chains, and brand-logo mismatches.
- Larger models and video-frame analysis run here.
- Graph models find coordinated rings through shared IPs, domains, and near-duplicate images across accounts.
- Results can retroactively demote or remove content.
4. Data strategy
Label sources, best to worst: moderator decisions, appeal outcomes (which correct false positives), hash-match hits, user reports (noisy and gameable, so weight by each reporter's historical accuracy), and rule-based labels for bootstrapping.
Imbalance: downsample easy negatives (e.g. 1:20), use class weights or focal loss, mine hard negatives (swimwear, medical images, coupon posts), and augment positives with crops, overlays and re-encodes.
Selection bias: reviewers only see flagged items, so a model trained and evaluated on them looks better than it is. Label a uniform random sample daily (a few thousand posts). Use it to estimate true prevalence, precision, and recall, and to pick thresholds.
Cold start: new accounts get stricter routing: always run Stage 2, use lower review thresholds, apply rate limits, and default to limited reach until scored. Trust is earned slowly and reset on anomalies (a new device followed by bulk link posting suggests account takeover).
5. Serving and failure handling
- Stage 2 has a hard timeout (~120 ms) so the total stays under 200 ms.
- On timeout or outage, fail soft: publish with limited reach (visible to the author, excluded from recommendations and search) and enqueue for async rescoring. This avoids both punishing legitimate users and spreading unscored content.
- Fail closed only for high-risk accounts or Stage 0 matches.
- Dynamic GPU batching (~5 ms window), embedding cache keyed by image hash, autoscaling on queue depth.
- Release via shadow mode, then canary, checking per-policy precision on the random-sample labels before promotion.
6. Feedback loop
- Reports and moderator decisions go into a labeling queue, prioritized by model uncertainty and potential reach (active learning).
- Appeals feed back as corrected negatives, which directly lowers false positives.
- Retrain on a schedule (weekly, or sooner when drift alarms fire) and recalibrate thresholds on fresh random-sample data.
- Monitor score distributions, flag rates per policy, review overturn rate, and prevalence from the random sample.
7. Anti-abuse
- Never expose scores. Return only an action and a coarse reason code, so attackers cannot do gradient-free search on confidence values.
- Rate-limit and detect probing: many near-duplicate uploads with small perturbations from one account or device cluster is a signal in itself. Slow responses or delay feedback for suspicious accounts.
- Robust training: augment with the adversarial tricks seen in the wild (noise, crops, overlays, homoglyph text, text-in-image), and add adversarial examples found by internal red-teaming.
- Defense in depth: perceptual hashes catch re-uploads, account and graph signals catch behavior that content alone hides, and delayed async checks mean an evader cannot tell instantly whether a post got through.
- Randomization: slight threshold jitter and random audits make boundary mapping harder and reveal evasion that worked.
Trade-offs and common mistakes
- Treating the problem as binary and then trying to hit both high precision and high recall with one threshold.
- Evaluating only on flagged items, which hides recall problems.
- Running the heavy model on all traffic, blowing the latency and cost budget.
- Failing closed on model outages, which blocks real users en masse.
- Returning raw scores from the API.
- Ignoring non-image signals such as account behavior and link reputation, which are often the strongest features for spam and phishing.