---
title: Moderation pipeline for user prompts and model outputs
url: https://gurkanozkan.ai/learn/design/applied-llm-sd-10/
markdown: https://gurkanozkan.ai/learn/design/applied-llm-sd-10.md
kind: design
role: Applied LLM
json: https://gurkanozkan.ai/api/learn/design/applied-llm-sd-10.json
---

# 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.

## What to cover

- **Requirements**: policy taxonomy; legal requirements (e.g. UK Online Safety Act duties if user-to-user features exist); latency budget; volumes; appeal process; languages
- **Estimates**
- **API**
- **Data model**
- **Architecture**: policy 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
- **Deep dives**: a new jailbreak trend appears — how fast can you respond?; How do you measure recall without labelling everything?
- **Trade-offs**: latency vs accuracy (cascade); recall vs false positives per category; centralised vs per-product policies; on-the-fly LLM judging cost
- **Evaluation**: cascade design with measured thresholds per category; multilingual evaluation; human review and appeals; continuous red-teaming

## Reference design

### 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

```
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

**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.*
