Design: content moderation system

In one sentence

A tiered funnel: hash matching and cheap per-category classifiers settle ~97% of items in milliseconds, a policy-prompted LLM judges the borderline few percent, and humans handle the uncertain, the severe and appeals.

Analogy: Airport security: everyone is checked against the watch list, every bag goes through the X-ray, only the few bags the scanner flags are searched by hand, and a supervisor steps in when the officer isn't sure.

Cost per item rises as volume falls: hashes and classifiers settle most items inline, the LLM and humans take the ambiguous few, and every human decision feeds the hash bank.

How it works

  • Scale: ~100k items/min (~5k/s at peak), with inline decisions in ≤ 100 ms p99 before publishing.
  • Borderline items publish with limited distribution while the LLM and humans judge them asynchronously.
  • Policy-as-prompt changes behavior in hours; distill its labels back into the cheap classifiers.
  • The worst failure is illegal content staying up; each confirmed removal adds a hash, so reposts die instantly.
  • Set thresholds per category from error cost; estimate recall by labeling a random sample of allowed content.

Check yourself

Answer to mark it learned; your answers aren't scored.

A week after reviewers removed a hateful meme, copies keep flooding your LLM tier: each one slightly cropped and recompressed, with a new caption. Every copy lands in the classifiers' borderline band. Highest-leverage fix?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: score every text and image item (~100k a minute) against a written policy with categories such as spam, nudity, violence, hate, harassment, self-harm, child sexual abuse material (CSAM) and terrorism. Actions: allow, limit distribution, remove, strike the account, report to authorities. Support user reports, appeals and a notice that names the policy clause.

Non-functional: inline decisions in ≤ 100 ms p99 on surfaces screened before publishing; per-category precision and recall targets; every decision traceable to a policy version and model versions; many languages; legal duties (in the US, CSAM must be reported to NCMEC; the EU Digital Services Act requires a statement of reasons and an appeals process).

What I'd ask first:

  1. Which surfaces must be screened before they go live (ads, live video, new accounts) and which can be checked after?
  2. Which categories and languages, and which carry legal duties?
  3. Per category, which is worse: a wrongful takedown or a miss?
  4. How much reviewer capacity is there, in which languages and time zones?
  5. How often does the policy change, and must past decisions be re-run?

Highest-cost failure: illegal content (CSAM, terrorism) staying up; second, a bad threshold or policy deploy that removes legitimate posts by the million.

High-level design

A funnel where cost per item rises as volume falls:

  1. Normalize: Unicode folding, strip zero-width characters, OCR the text inside images.
  2. Hash match: perceptual hashes (PhotoDNA, PDQ) against industry and internal banks of known-bad content; a match removes and reports in milliseconds.
  3. Cheap classifiers: one small model per category for text and images, plus account signals (age, prior strikes, posting velocity). Scores fall into three bands per category: clear allow, clear violation, borderline.
  4. LLM judge: borderline items (~3%) go to an LLM whose prompt is the policy itself; it returns the category, the clause violated and a rationale (Guardrails: input, output, action).
  5. Human review: uncertain or high-severity LLM outputs, appeals, and random QA samples (Human-in-the-loop & approvals).

Pre- vs post-publication: steps 1–3 run inline within the publish budget. The LLM (0.5–2 s) and humans run async: borderline items publish with limited distribution, or are held on high-risk surfaces. Every confirmed removal adds a hash to the bank, so reposts die at step 2. LLM and human labels retrain the classifiers (Knowledge distillation).

Code Per-category bands, not one global score
pythonPer-category bands, not one global score
# Tuned per category, language and surface on labeled samples.
# auto: remove at/above it (precision target); review: send to the LLM (recall target).
BANDS = {
    "spam":      {"auto": 0.97,  "review": 0.80},
    "nudity":    {"auto": 0.98,  "review": 0.60},
    "hate":      {"auto": 0.995, "review": 0.40},  # context-heavy: lean on LLM + humans
    "self_harm": {"auto": None,  "review": 0.30},  # never auto-remove: route to support
}

def route(item, scores: dict[str, float]) -> str:
    if hash_bank.match(item.media_hashes):   # PhotoDNA / PDQ, milliseconds
        return "remove_and_report"
    borderline = False
    for cat, s in scores.items():
        band = BANDS[cat]
        if band["auto"] is not None and s >= band["auto"]:
            return f"remove:{cat}"
        borderline |= s >= band["review"]
    if borderline:
        return "llm_review"   # async; publish with limited distribution meanwhile
    return "allow"
Real example

A user posts a meme: a photo with overlaid text, captioned ‘lol accurate’. Normalize + OCR pulls out the overlay text (~40 ms); no hash match. The classifiers score hate at 0.71: above the review band (0.40), below auto-removal (0.995). The post goes live with limited distribution while the LLM reads image text, caption and policy v14 (~3k cached tokens) and returns clause H-2, a dehumanizing comparison of a protected group, with high confidence. It is removed 1.4 s after posting, with a notice citing H-2. A reviewer confirms it 20 min later in the high-reach QA queue, and its PDQ hash enters the bank: the next day's 340 reposts die at step 2 with no LLM cost. An appeal goes to a different reviewer, who upholds it.

Trade-offs +4 · −4

+ You gain

  • Cost tracks ambiguity, not volume: ~97% of items cost a fraction of a cent.
  • Policy-as-prompt follows a policy change in hours, not a retraining cycle.
  • The hash bank turns each human decision into instant protection against reposts.
  • Per-category bands make the error trade-off an explicit, reviewable policy decision.

− You pay

  • Four tiers, each with its own models, thresholds and drift to monitor.
  • An item a classifier wrongly calls a clear allow never gets a second look; only random sampling reveals those misses.
  • The LLM tier adds 0.5–2 s, so it cannot sit inline on most pre-publication surfaces.
  • Human review is the hardest capacity to scale, and it carries a real wellbeing cost.

Use it when

Any platform with user-generated content at a volume where people can't see everything, and where categories differ in severity and legal duty.

Avoid it when

Low volume (a few thousand items a day): a hosted moderation API plus a human queue is cheaper. And never build CSAM detection from scratch: join industry hash-sharing programs.

Numbers to know 6
  • Load: 100k items/min ≈ 1.7k/s; plan for ~3× peaks ≈ 5k/s; ≈ 4.3B items/month. Assume 80% text, 20% images.
  • Funnel (assumed): hashes + classifiers settle ~97%; ~3% → LLM ≈ 50 req/s; ~0.05% → humans ≈ 72k items/day.
  • LLM via API: 130M calls/month × (3k cached policy + ~300 fresh + 100 output tokens) at an assumed $0.10/$0.40/$1.60 per M ≈ $39k + $16k + $21k ≈ $75k/month.
  • Self-hosted instead: an 8B guard model with prefix caching on ~4 GPUs (with headroom) at an assumed $2.50/GPU-hour ≈ $7k/month.
  • Humans: 72k items/day × ~30 s ≈ 600 h/day ≈ 100 six-hour shifts/day ≈ ~140 reviewers on 5-day weeks.
  • Inline budget: normalize ~5 ms + hash ~5 ms + classifiers ~20–50 ms → ≤ 100 ms p99. The LLM (0.5–2 s) and humans (minutes to hours) run async.
Common pitfalls 4
  • One global threshold: categories differ by orders of magnitude in prevalence and harm. Tune per category, language and surface, and own each threshold like a policy decision.
  • Measuring precision only on flagged items: misses are invisible. Estimate prevalence weekly by labeling a random sample of allowed content.
  • Shipping a policy or model change straight to enforcement: run it in shadow mode on the golden set and live traffic, compare action rates per category, then ramp.
  • Evaluating in English only: recall usually drops on low-resource languages, dialects and code-switching. Set per-language targets and staff reviewers who speak them.
Interview questions 3

Answer out loud first, then reveal.

Why not just run an LLM on every item?Show answer

Cost, latency, and no gain on the easy cases. At 4.3B items a month, even a mini model with a cached 3k-token policy is ~$2.5M a month, against ~$75k for the 3% that are actually ambiguous. It also adds 0.5–2 s, which breaks the inline publish budget. For known-bad content a hash is cheaper and more precise, and clear spam is easy for a small classifier. So I spend the LLM where policy nuance matters, and use its labels to retrain the classifiers so the borderline band keeps shrinking.

The policy team changes the hate speech policy tomorrow. What happens in your system?Show answer

The policy is versioned like code, so the change is a new version of the LLM prompt plus a relabeled golden-set slice: a few hundred examples around the changed clause, labeled by the policy team. I run the new prompt in shadow for 24–48 hours and compare action rates per category and language. Meanwhile the classifiers still encode the old policy, so I widen their borderline band to send more traffic to the LLM, at a known cost. Reviewers train on the same version, every decision logs it, and I decide explicitly whether past removals are re-run. Later, the new labels retrain the classifiers and the band narrows again.

How do you set the auto-removal threshold for harassment?Show answer

I start from error costs with policy and legal: a wrongful takedown silences a user, a miss harms a target. Harassment is context-heavy, so I'd auto-remove only where precision is at least ~98% measured at real prevalence, and send everything above a lower, recall-oriented threshold to the LLM and humans, sized to reviewer capacity. Base rates matter: at 1% prevalence, even a 1% false-positive rate makes about half of all flags wrong. I set it per language, watch the appeal overturn rate and the misses found in random samples, and revisit it on every model change.

Deep dive 5

Tiers & model choice

Each tier exists because the one after it is too expensive for the volume it would see. Hashes catch resurfacing known content for almost no compute, and for CSAM you join industry programs (PhotoDNA, NCMEC hash lists) rather than build your own. Classifiers are small fine-tuned encoders (multilingual text, ViT-class image models) at ~10–50 ms on GPU: cheap, but frozen to the policy they were trained on. The LLM tier is policy-as-prompt: edit the policy text and behavior changes in hours instead of a retraining cycle, which is the main reason to have it (LLM-as-a-judge). Use a guard model such as Llama Guard, or a general model given the full policy and examples. Then distill its labels back into the classifiers so the borderline band shrinks over time.

Thresholds & evaluation

Thresholds are set per category, language and surface from what each error costs (Precision, recall, F1, ROC-AUC). Base rates dominate: at 1% prevalence, 99% recall with a 1% false-positive rate is only ~50% precision, so auto-action needs a very high score. Build golden sets per category, labeled by policy experts; oversample positives but report precision at real prevalence. Measure recall the only honest way: label a random sample of allowed content to estimate the prevalence of what slipped through. Reviewer agreement (Cohen's kappa) is your ceiling, since no model beats labels its humans disagree on. Online, watch action rates per category, the appeal overturn rate and user reports per 10k views. Every new model, prompt or policy runs in shadow mode first, then ramps.

Adversarial evasion

Moderation is the ML system with an active opponent who learns from your decisions. Expect leetspeak and homoglyphs (handle with Unicode NFKC plus a confusables map), zero-width characters, text moved into images (OCR everything), content split across posts or comments, images cropped or noised to break exact hashes (perceptual hashes like PDQ tolerate small edits), and coordinated accounts posting variants. Defenses: normalize before every model, score account and network behavior and not just the item, and feed new evasions into training within days. Keep thresholds and model details private, don't tell users which word triggered a removal, and red-team the pipeline every quarter (Jailbreaks). The hash bank is the cheapest counter: one human decision blocks every exact or near-duplicate repost.

Appeals, policy versions & audit

Treat the policy as code: every clause has an id, every policy has a version, and every decision logs the item, policy version, model and prompt versions, scores, thresholds and the deciding tier. That record is what you need for a regulator, a press inquiry or a re-run. Notices name the clause, which is what the EU DSA's statement of reasons asks for. Appeals go to a different, more senior reviewer who sees the original context; the overturn rate per category and tier is a quality metric, and every overturn becomes a training label. When the policy changes, relabel the affected golden-set slice, run the new prompt in shadow, widen the borderline band so more traffic reaches the LLM, retrain reviewers, and decide explicitly whether past removals get re-run.

Reviewer wellbeing & operations

Human review is the hardest capacity to scale and it has a human cost: in 2020 Facebook agreed to a $52M settlement with moderators who developed PTSD and other trauma on the job. Treat wellbeing as a design input. Blur and grayscale graphic media until the reviewer chooses to reveal it, mute audio, show the minimum needed to decide, cap daily exposure to the most severe queues, rotate people across queues, and provide counseling. Keep known CSAM away from general reviewers: hash matches are removed automatically, and any verification the law requires goes to a small specialist team. Prioritize queues by severity × expected reach, so a viral post waits minutes, not hours, and route by language. Track accuracy against gold items, not just throughput, which only rewards rushing.