LearnSystem design

Moderation pipeline for user prompts and model outputs

Design the moderation system for a consumer generative-AI product (text, voice and images) that must block harmful prompts and outputs with low latency and few false positives across 30 languages.

Applied LLM8 parts

Contents

What to cover

Sketch your own design first. A complete answer has these parts; the notes say what each should settle.

  1. Requirementspolicy taxonomy; legal requirements (e.g. UK Online Safety Act duties if user-to-user features exist); latency budget; volumes; appeal process; languages
  2. Estimates
  3. API
  4. Data model
  5. Architecturepolicy definitions; fast first-stage classifiers (multilingual, per modality) on input and output; LLM-based second stage for ambiguous cases; streaming-output handling (buffered windows, retraction); user/account risk signals; human review queues; appeals; metrics dashboards (precision/recall per category and language); red-team and regression sets
  6. Deep divesa new jailbreak trend appears — how fast can you respond?; How do you measure recall without labelling everything?
  7. Trade-offslatency vs accuracy (cascade); recall vs false positives per category; centralised vs per-product policies; on-the-fly LLM judging cost
  8. Evaluationcascade design with measured thresholds per category; multilingual evaluation; human review and appeals; continuous red-teaming

Reference design

One way to answer it, part by part. Open a part once you have your own version of it.

Requirements

Functional: classify every user prompt and every model output (text, images, voice via transcripts) against a written policy; actions per category: allow, warn, safe-complete (e.g. self-harm support resources), block, escalate to review, account action; streaming outputs can be stopped or retracted; users can appeal.

Assumptions to confirm

  • Policy taxonomy with severity tiers: CSAM and child sexualisation (zero tolerance, hash matching, mandatory reporting); terrorism and violent extremism; self-harm; hate and harassment; sexual content (adult, age-gated); violence and gore; weapons, CBRN and cyber-attack uplift; fraud and scams; privacy (doxxing); impersonation.
  • Legal requirements: if users can share generations with each other, UK Online Safety Act duties apply (illegal-content risk assessment, a children’s access assessment and, where children are likely to use the service, children’s safety duties and age assurance, reporting and complaints routes); where the product hosts user content in the EU, DSA notice-and-action and statements of reasons; AI-generated content labelling.
  • Latency budget: input check adds < 100 ms p95 before generation; output checks add at most one buffered window to streaming.
  • Volumes: ~50M prompts/day, the same number of outputs, ~7M images, ~2M voice minutes.
  • Appeal process: users can appeal account-level actions and repeated blocks; decisions within 72 hours; overturns feed training data.
  • Languages: 30, with recall targets per language, not just English.

Estimates

  • Text items: 50M prompts + 50M outputs = 100M/day ≈ 1,160/s average, ~3.5k/s at a 3× peak.
  • Streaming windows: each output checked ~5 times as it streams → 250M checks/day ≈ 2.9k/s average, ~9k/s peak.
  • Fast classifiers: assume a ~300M-parameter multilingual encoder handles ~3k short items/s per GPU → (3.5k + 9k) / 3k ≈ 4–5 GPUs at peak, ~10 with regional redundancy.
  • Images: 7M/day ≈ 80/s average, ~250/s peak → 1–2 GPUs for classifiers plus perceptual hashing on CPU.
  • Second stage: escalating ~2% of text items = 2M LLM-judge calls/day × ~1.5k tokens (policy excerpt + content) ≈ 3B tokens/day ≈ $600/day at an assumed $0.2/M — cheap because it is gated.
  • Human review: high-severity confirmations, appeals and QA samples ≈ 20k items/day ≈ 100 reviewers at ~200 items/day each, with wellbeing limits on exposure to graphic content.
  • Latency budget (input): hash lookup 5 ms, classifiers in parallel 30–50 ms, risk-signal lookup 5 ms → p95 ≈ 70 ms; the 2% escalated to the LLM judge add 300–800 ms.
  • Logs: 350M decisions/day × ~300 bytes ≈ 100 GB/day of metadata; content stored only for flagged items, with short retention.

API

POST /v1/moderate
  {items: [{type: "text"|"image"|"audio", data | uri}], direction: "input"|"output",
   context: {product, surface, user_id_hash, conversation_id, locale, age_band}, policy_version?}
  → {decision: "allow"|"warn"|"safe_complete"|"block"|"escalate",
     categories: [{name, score, severity}], decision_id, policy_version, model_versions, latency_ms}

Streaming output:  WS /v1/moderate/stream  {conversation_id}
  client → {"delta": "...", "offset": 1840}
  server → {"ok": true} | {"stop": true, "retract_from": 1600, "category": "..."}

POST /v1/appeals        {decision_id, statement}   → {appeal_id, status}
Review tool: GET /v1/queues/{queue}/next · POST /v1/reviews {item_id, label, policy_refs, notes}
Policy admin: PUT /v1/policies/{version} (thresholds per category × language × surface)

Data model

  • Policy / PolicyVersion: categories, definitions, examples, severity, actions; thresholds per category × language × surface; owner; effective date.
  • Decision: id, content hash, direction, modality, scores per category, action, policy and model versions, latency, timestamp. Content kept only for blocked or sampled items, with category-specific retention.
  • UserRisk: user, strikes, recent block rate, velocity, account age, age band, prior appeals.
  • ReviewItem / Label: item, queue, priority, reviewer, label, policy references, time spent, agreement checks.
  • Appeal: decision_id, statement, outcome, reviewer, turnaround.
  • HashSet: perceptual hashes of known illegal content from industry sources (child-abuse and terrorist content lists); never stores the content itself.
  • EvalSet: red-team cases, regression cases, multilingual benign look-alikes (for over-blocking), each tagged by category, language, attack type and date.

Architecture

Flow · 5 stepsInput and output moderation cascade

Input and output moderation cascadeA prompt enters the input stage, where hash matching, fast multilingual classifiers and risk signals run in parallel. Per-category thresholds allow, block or send ambiguous items to the LLM policy judge before generation. Outputs are checked as they stream, then logged and sampled for human review.User prompttext | voice | imageInput stageparallel ~50 msPer-category thresholdsallow | block | ambiguousLLM policy judgeambiguous onlyGenerationmodel safety trainingOutput stagesentence-sized bufferDecision logmetrics per category × languageHuman reviewsampling; appeals; red-teamallowambiguousdecisionblocksampling12345InputModerationGenerationOutput
  1. Input checks The prompt enters the input stage, where hash matching, fast classifiers and risk signals run in parallel.
  2. Thresholds Per-category thresholds allow, block or send ambiguous items to the LLM policy judge.
  3. Generation Allowed prompts reach generation.
  4. Output checks Outputs are checked as they stream; violations stop the stream and retract shown text.
  5. Review Decisions are logged; metrics and sampling feed human review.

Prompts are checked before generation and outputs after it, with only ambiguous items routed to the LLM judge.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Input checksThe prompt enters the input stage, where hash matching, fast classifiers and risk signals run in parallel.
2ThresholdsPer-category thresholds allow, block or send ambiguous items to the LLM policy judge.
3GenerationAllowed prompts reach generation.
4Output checksOutputs are checked as they stream; violations stop the stream and retract shown text.
5ReviewDecisions are logged; metrics and sampling feed human review.

Source: This page's text

Boxes
BoxGroupDetail
User promptInputtext | voice | image
Input stageModerationparallel ~50 ms
Per-category thresholdsModerationallow | block | ambiguous
LLM policy judgeModerationambiguous only
GenerationGenerationmodel safety training
Output stageOutputsentence-sized buffer
Decision logOutputmetrics per category × language
Human reviewOutputsampling; appeals; red-team

Source: This page's text

Flow · 4 stepsHow buffered windows stop and retract a stream

How buffered windows stop and retract a streamA model output streams into a sentence-sized buffer. Each window is checked by a fast classifier; a clean window continues to the user, while a violation stops the stream, retracts the shown text from the violation offset and sends a safe message.Model outputtext streamedSentence-sized bufferone window at a timeFast classifier per windowper modalityStream to userclean windowsStop streamviolationRetract shown textretract_from offsetSafe messagesent after retractionokviolation1234StreamCheckAction
  1. Buffer a window The output streams into the sentence-sized buffer.
  2. Check the window Each window is checked by the fast classifier.
  3. Clean window continues A clean window is shown to the user.
  4. Violation retracts A violation stops the stream, retracts the shown text and sends a safe message.

Each sentence-sized window is checked as it streams, and a violation stops the stream and retracts the text already shown.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Buffer a windowThe output streams into the sentence-sized buffer.
2Check the windowEach window is checked by the fast classifier.
3Clean window continuesA clean window is shown to the user.
4Violation retractsA violation stops the stream, retracts the shown text and sends a safe message.

Source: This page's text

Boxes
BoxGroupDetail
Model outputStreamtext streamed
Sentence-sized bufferStreamone window at a time
Fast classifier per windowCheckper modality
Stream to userStreamclean windows
Stop streamActionviolation
Retract shown textActionretract_from offset
Safe messageActionsent after retraction

Source: This page's text

Prompt: text | voice ─► ASR | image
  ─► Input stage (parallel, ~50 ms):
       perceptual hash match (images) ─► known illegal → block + report
       fast multilingual classifiers per modality
       user/account risk signals
     ─► per-category thresholds: allow | block | ambiguous band
     ─► ambiguous only ─► LLM policy judge (policy text in prompt) ─► decision
  ─► Generation (model has its own safety training)
  ─► Output stage:
       text streamed through a sentence-sized buffer ─► fast classifier per window
          violation → stop stream, retract shown text, safe message
       images checked before display; TTS text checked before synthesis
       final full-output check (context-dependent harms)
  ─► Decision log ─► metrics per category × language ─► sampling ─► human review
Review queues (severity × reach priority) · appeals · red-team & regression sets
  ─► CI gate for classifier, threshold and policy changes

One central service with per-product thresholds, so a children’s product can be stricter without a separate stack.

Deep dives

Flow · 5 stepsLayered response to a new jailbreak trend

Layered response to a new jailbreak trendThe flow runs from a new jailbreak trend to detection signals, then through a minutes, hours and days response ladder. Output-side checks feed missed blocks into detection and continue as defence in depth while input defences catch up.New jailbreak trendOutput-side checksdefence in depth whileinput defences catch upDetection signalsescalations, missed blocks, reports,red-teamMinutes responseembedding-similarity rule + tighterthresholdHours responsejudge prompt + policy update,canariedDays responseretrain classifier + regression set +reviewmissed blocks12345DetectRespondDefence in depth
  1. Detect Rising second-stage escalations, output-stage blocks the input stage missed, user reports, red-team intelligence and embedding-space clusters surface the trend.
  2. Minutes Within minutes: an embedding-similarity rule against the attack cluster and a tighter threshold on the affected category.
  3. Hours Within hours: a judge prompt and policy update with examples, versioned and canaried.
  4. Days Within days: retrain the fast classifier with new examples and variants; add to the regression set; write a post-incident review.
  5. Defence in depth Output-side checks keep running as defence in depth while input defences catch up.

A new jailbreak trend is detected from several signals and answered in minutes, hours and days, with output-side checks holding the line throughout.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1DetectRising second-stage escalations, output-stage blocks the input stage missed, user reports, red-team intelligence and embedding-space clusters surface the trend.
2MinutesWithin minutes: an embedding-similarity rule against the attack cluster and a tighter threshold on the affected category.
3HoursWithin hours: a judge prompt and policy update with examples, versioned and canaried.
4DaysWithin days: retrain the fast classifier with new examples and variants; add to the regression set; write a post-incident review.
5Defence in depthOutput-side checks keep running as defence in depth while input defences catch up.

Source: This page's text

Boxes
BoxGroupDetail
New jailbreak trendDetect
Detection signalsDetectescalations, missed blocks, reports, red-team
Minutes responseRespondembedding-similarity rule + tighter threshold
Hours responseRespondjudge prompt + policy update, canaried
Days responseRespondretrain classifier + regression set + review
Output-side checksDefence in depthdefence in depth while input defences catch up

Source: This page's text

Flow · 5 stepsStratified sampling for recall

Stratified sampling for recallA flow from score bands to a stratified sample, then human labelling, inverse-probability weighting, recall and prevalence estimates with confidence intervals, and per-language reporting. A calibrated LLM judge audits a much larger random sample and sends candidate misses back to humans for confirmation.Score bandsoversample near thresholdsStratified sampleslice of low-scoreallowed trafficLLM judge auditlarger random sampleHuman labellinga few thousand per category perweekInverse-probability weightsweight each stratumRecall estimateswith confidence intervalsPer-language reportingevery estimate per languagerandom samplecandidate misses12345SamplingLabelEstimate
  1. Stratify Oversample near thresholds and include a slice of low-score allowed traffic.
  2. Label Humans label a few thousand items per category per week.
  3. Weight and estimate Inverse-probability weights estimate prevalence and recall with confidence intervals.
  4. Audit A calibrated LLM judge audits a much larger random sample; candidate misses are confirmed by humans.
  5. Report Every estimate is reported per language; red-team sets measure recall on known attack types.

Recall is estimated from a stratified sample of score bands, weighted by inverse probability, with an LLM judge auditing a larger random sample for candidate misses.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1StratifyOversample near thresholds and include a slice of low-score allowed traffic.
2LabelHumans label a few thousand items per category per week.
3Weight and estimateInverse-probability weights estimate prevalence and recall with confidence intervals.
4AuditA calibrated LLM judge audits a much larger random sample; candidate misses are confirmed by humans.
5ReportEvery estimate is reported per language; red-team sets measure recall on known attack types.

Source: This page's text

Boxes
BoxGroupDetail
Score bandsSamplingoversample near thresholds
Stratified sampleSamplingslice of low-score allowed traffic
LLM judge auditSamplinglarger random sample
Human labellingLabela few thousand per category per week
Inverse-probability weightsEstimateweight each stratum
Recall estimatesEstimatewith confidence intervals
Per-language reportingEstimateevery estimate per language

Source: This page's text

A new jailbreak trend appears — how fast can you respond? Detect it from rising second-stage escalations, output-stage blocks that the input stage missed (the clearest signal), user reports, red-team intelligence and clusters of near-duplicate prompts in embedding space. Respond in layers: within minutes, an embedding-similarity rule against the attack cluster and a tighter threshold on the affected category; within hours, a judge prompt and policy update with examples (versioned, canaried); within days, retrain the fast classifier with the new examples plus translations and obfuscated variants, add them to the regression set, and write a post-incident review. Output-side checks give defence in depth while input defences catch up.

Measuring recall without labelling everything. Stratified sampling over score bands — oversampling near thresholds and including a slice of low-score “allowed” traffic — labelled by humans (a few thousand per category per week), with inverse-probability weights to estimate prevalence and recall with confidence intervals. A calibrated LLM judge audits a much larger random sample to find candidate misses for humans to confirm. Red-team sets measure recall on known attack types; every estimate is reported per language.

Trade-offs

  • Latency vs accuracy (cascade): fast classifiers on everything, the LLM judge only on the ambiguous band; widening the band improves accuracy but adds latency for more users.
  • Recall vs false positives per category: maximise recall where harm is severe (child safety, weapons uplift), accepting more review load; favour precision for low-severity categories (profanity, mild violence) where over-blocking frustrates users and fails creative use cases.
  • Centralised vs per-product policies: one taxonomy, one classifier set and one audit trail; per-product thresholds and actions for audiences such as children.
  • On-the-fly LLM judging cost: judging everything would cost ~50× more and add hundreds of ms; gating to ~2% keeps it at hundreds of dollars a day.
  • Streaming retraction vs user experience: smaller windows catch harms sooner but cut more benign text mid-sentence; sentence-sized windows balance both.

Evaluation

  • Cascade with measured thresholds per category: thresholds chosen on labelled sets to hit target precision and recall per category, documented, re-validated monthly and on every model change.
  • Multilingual evaluation: per-language test sets built with native speakers; recall and false-positive rates per language on dashboards; low-resource languages get extra red-teaming and translated attack variants.
  • Over-refusal: a benign look-alike set (medical, historical, fiction, security education) tracks false positives.
  • Human review and appeals: reviewer agreement, appeal overturn rate per category (a high rate means thresholds or policy wording are wrong), turnaround times.
  • Continuous red-teaming: internal team plus external testers each month; every successful attack becomes a regression case; CI blocks releases that regress.
  • Operations: added latency p95, escalation rate, time to mitigate a new trend, prevalence estimates per category with CIs.

What a strong design shows

  • Designs a cascade with per-category, per-language thresholds that were actually measured.
  • Checks outputs as well as inputs, including buffered streaming with retraction.
  • Estimates recall with stratified sampling and weighting rather than labelling everything.
  • Includes human review, appeals and the relevant legal duties (Online Safety Act where users interact).
  • Has a concrete response ladder for new jailbreaks and continuous red-teaming feeding regression sets.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.