Slides · GenAI system design

Designing content moderation and guardrail systems

Designing content moderation and guardrail systems

Moderation is a trade, not a switch. This deck designs the system around the trade: layers, thresholds, a human lane, and safe tuning.

By the end you can:

  • design layered input and output moderation, and choose serial, windowed or parallel output checks from harm severity and latency,
  • work out precision and recall from counts at two thresholds, and explain why the threshold per category is a business decision,
  • design escalation, appeals and logging, sizing human review from reviewer capacity,
  • tune thresholds with shadow mode and labelled samples, and diagnose and roll back a threshold change that doubled the block rate.

Concept

Two errors, and you can only move them

  • Block too little and harmful output reaches users.
  • Block too much and honest users are refused, lose trust and leave.
  • Neither error can be removed, only moved. The design question is who bears the cost of each mistake, and who decides where the line sits.
  • All counts and capacities in this deck are illustrative assumptions, not measurements of any real classifier.

Mental model: airport security with three lanes. Most travellers walk through, a few are clearly stopped, and a middle band gets a manual check. Staffing the manual lane limits how wide that band can be. The detector’s sensitivity is a dial that someone with authority sets.

Diagram

Two thresholds make three lanes

Diagram: Two thresholds create three lanes.

below low threshold

between the two

above high threshold

Classifier score
for one category

Where is the score?

Allow

Human review lane

Block

Diagram summary: Two thresholds create three lanes. Low scores pass, high scores are blocked, and the band between them goes to a person. The width of that band is limited by how many reviewers you can staff, and a person with authority sets where the thresholds sit.

Concept

Requirements for a consumer chatbot

AspectRequirement
PolicyA written list of categories (for example self-harm, hate, sexual content involving minors, regulated advice), each with a stated severity
CoverageScreen user input and model output
LatencyModeration adds only a small, stated share of response time; assume 100 ms for the input check
FairnessA blocked user gets a clear message and a way to appeal
AuditabilityEvery decision is logged with enough context to review
Out of scopePrompt-injection defence for agents with tools

Concept

A harm classifier is not an injection defence

  • A moderation classifier scores content against a policy. Llama Guard, for example, uses a safety risk taxonomy to classify user prompts and model responses.
  • Jailbreaks and prompt injection are attempts to get a model to disregard the rules its developer or operator set. Anthropic’s documentation treats them as their own problem with their own mitigations (screening, hardened prompts, safe handling of untrusted tool content).
  • A message can be harmless by the policy and still try to steer the model. It can also be harmful and carry no steering at all.
  • So keep the two designs separate, and do not claim the moderation layer covers injection.

Sources1 Mitigate jailbreaks and prompt injections2 Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations

Compare

The layers are a menu, not a script

Anthropic’s guidance describes combining several strategies rather than relying on one: a lightweight input screen, input validation, prompt engineering, and monitoring.

LayerCatchesCost and weakness
Input classifierClearly harmful requests before the model runsAdds latency; false positives refuse honest users
System prompt policyCheap steering toward policyIt is a request to the model, so it can be talked around
Output classifierHarmful text produced despite earlier layersAdds latency or buffering; may be wrong
Human reviewBorderline and disputed casesSlow and costly; limited capacity
Logging and appealsFalse positives and new failure patternsStores sensitive text, so needs access controls and retention limits

Each layer catches a different failure. Combine them by risk, not by habit.

Sources1 Mitigate jailbreaks and prompt injections2 Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations

Compare

Serial, windowed or parallel: choose by harm severity

PatternHow it worksLatencyChoose it when
SerialGenerate the whole answer, check it, then show itHighest: wait for the full generationSevere harm: even a brief display is unacceptable
Windowed streamingCheck the text so far every N tokens; release with a small lag; cancel on violationSmall added lagMixed risk: a short lag is acceptable
Parallel and retractStream at once, check alongside, remove if flaggedLowestLow severity: a flagged message shown for a second is tolerable
  • A stream that has already shown text cannot be un-shown, only retracted. Parallel checks are weak where severity is high.
  • Check the service you use. OpenAI’s moderation guide notes that for a streamed response the scores are delivered only once generation has finished, not with the partial chunks. That pushes you toward buffering or your own check on partial text.

Source3 Moderation

Diagram

The three patterns side by side

Diagram: Serial checking shows nothing until the whole answer is checked, so it is safest and slowest.

Parallel

Stream at once

Check
alongside

Retract
if flagged

Windowed

Generate
N tokens

Check text
so far

Release
with lag

Serial

Generate
answer

Check

Show

Diagram summary: Serial checking shows nothing until the whole answer is checked, so it is safest and slowest. Windowed streaming releases text a little behind the checker and cancels on a violation. Parallel streaming shows text immediately and retracts it if flagged, so it is fastest and weakest where harm is severe.

Worked example

Worked: pick a pattern per category

Illustrative latency for a 400-token answer streamed at 50 tokens per second: the whole answer takes 40050=8\dfrac{400}{50} = 8 seconds to generate.

Category (judgment, not data)SeverityPatternFirst visible text
Instructions for self-harmSevereSerialAfter about 8 s of generation plus the check
Regulated advice claimsMediumWindowed, N=50N = 50 tokensAbout 1 s (5050\dfrac{50}{50}) plus a check, then a steady lag
Mild profanityLowParallel and retractImmediately
  • The input check can also be serial or parallel. Serial saves the cost of a generation you would discard; parallel saves latency and lets you cancel, at the price of some wasted work. For severe categories, serial is the safer choice.
  • The product owner and policy team confirm the severities. Engineering supplies the latency numbers.

Check yourself

Check: windowed checks without partial scores

Your moderation provider returns output scores only after the full output exists, but a category needs windowed streaming. What are your options?

Answer

Run your own check on the accumulated text every N tokens, using a classifier you operate or a separate call on the partial text, and release text with a small lag. If that is too costly or too weak for the category, fall back to serial buffering and accept the wait. Read the provider’s current documentation, because behaviour can change.

Source3 Moderation

Math

Precision and recall from counts

precision=tptp+fp\text{precision} = \frac{\mathrm{tp}}{\mathrm{tp} + \mathrm{fp}}recall=tptp+fn\text{recall} = \frac{\mathrm{tp}}{\mathrm{tp} + \mathrm{fn}}fpr=fpfp+tn\mathrm{fpr} = \frac{\mathrm{fp}}{\mathrm{fp} + \mathrm{tn}}
SymbolMeaning
tp\mathrm{tp}Violations that were blocked (true positives)
fp\mathrm{fp}Benign messages that were blocked (false positives)
fn\mathrm{fn}Violations that were let through (false negatives)
tn\mathrm{tn}Benign messages that were allowed
fpr\mathrm{fpr}False-positive rate: the share of benign messages blocked

scikit-learn’s documentation gives the first two definitions. Precision asks “of what we blocked, how much was a real violation”. Recall asks “of the real violations, how many did we catch”.

Source4 Metrics and scoring: quantifying the quality of predictions

Worked example

Worked: two thresholds on the same traffic

Assumptions: 1,000,000 messages a day, 0.5% truly violate policy: 5,000 violations and 995,000 benign messages.

RowThreshold A (lenient)Threshold B (strict)
Recall90%98%
Violations caught0.90×5,000=4,5000.90 \times 5{,}000 = 4{,}5000.98×5,000=4,9000.98 \times 5{,}000 = 4{,}900
Violations missed500100
False-positive rate1%3%
Benign blocked0.01×995,000=9,9500.01 \times 995{,}000 = 9{,}9500.03×995,000=29,8500.03 \times 995{,}000 = 29{,}850
Precision4,50014,450≈31%\dfrac{4{,}500}{14{,}450} \approx 31\%4,90034,750≈14%\dfrac{4{,}900}{34{,}750} \approx 14\%

Moving from A to B catches 4,900−4,500=4004{,}900 - 4{,}500 = 400 more violations and blocks 29,850−9,950=19,90029{,}850 - 9{,}950 = 19{,}900 more honest messages: about 50 honest messages (19,900400=49.75\dfrac{19{,}900}{400} = 49.75) for each extra violation caught.

Diagram

Where the messages go at threshold A

Diagram: At threshold A, 4,500 of the 5,000 violations are caught and 500 are missed, while 9,950 benign messages are blocked by mistake.

1,000,000 messages a day

5,000 violations

995,000 benign

4,500 caught

500 missed

9,950 wrongly
blocked

14,450 blocked:
31% real

Diagram summary: At threshold A, 4,500 of the 5,000 violations are caught and 500 are missed, while 9,950 benign messages are blocked by mistake. Of the 14,450 blocked messages only about 31% are real violations, because real violations are rare.

Concept

Why precision looks low: the base rate

  • Violations are 0.5% of traffic. A 1% false-positive rate is higher than that, so benign blocks (9,950) outnumber caught violations (4,500).
  • Most blocks are false positives when fpr×(benign messages)\mathrm{fpr} \times (\text{benign messages}) exceeds recall×(violations)\text{recall} \times (\text{violations}).
  • A much lower false-positive rate changes the picture. At 0.1% (illustrative), benign blocked = 0.001×995,000=9950.001 \times 995{,}000 = 995, and precision = 4,5004,500+995≈82%\dfrac{4{,}500}{4{,}500 + 995} \approx 82\%.
  • So a classifier that looks excellent on a balanced test set can disappoint on real, mostly benign traffic.

Concept

Who decides, and per category

  • Is 400 more catches worth about 19,900 more refused honest messages? There is no technical answer. It depends on the harm of one missed violation in this product.
  • A children’s education product, a medical-advice assistant and an internal developer tool should sit at different points.
  • The product owner and policy team set the threshold. Engineering supplies the counts of both error types.
  • Set a threshold per category, not one global number.
Category typeThresholdHuman laneOutput pattern
Severe harmStrictYesSerial
Medium harmModerateNarrow bandWindowed
Tone or styleLenientUsually noneParallel and retract

The last three columns are an illustrative starting point to adjust with the policy team.

Check yourself

Check: what false-positive rate do you need?

A product sees 800,000 messages a day, 1% of which truly violate policy (8,000). Recall is 85% and the false-positive rate is 0.5%. The policy team asks for at least 80% precision with recall unchanged. What false-positive rate does that require, and how many honest messages would then be blocked per day?

Answer

Caught violations: 0.85×8,000=6,8000.85 \times 8{,}000 = 6{,}800. For precision 0.8, tptp+fp=0.8\dfrac{\mathrm{tp}}{\mathrm{tp} + \mathrm{fp}} = 0.8, so fp=6,800×0.25=1,700\mathrm{fp} = 6{,}800 \times 0.25 = 1{,}700. Benign messages: 792,000, so the false-positive rate must be 1,700792,000≈0.21%\dfrac{1{,}700}{792{,}000} \approx 0.21\%. Today’s 0.5% blocks 3,960 honest messages, so the rate must fall by more than half. Recall stays 85%, so the 1,200 misses do not change.

Worked example

Capacity sizes the human lane

Assumptions (illustrative): 2,000 items a day fall in the middle band. A reviewer handles 120 items an hour over an 8-hour shift.

  • One reviewer per day: 120×8=960120 \times 8 = 960 items.
  • Reviewers needed: 2,000960=2.08\dfrac{2{,}000}{960} = 2.08, so 3, not 2.
  • Always round up, because a fraction of a person does not exist.
  • If you cannot staff it, narrow the band. An unstaffed queue grows, and “escalate” silently means “ignore”.

Failure signal: queue age. Responses: narrow the band, add staff, or apply a default rule that you chose in advance.

Check yourself

Check: what happens to an understaffed queue?

Each reviewer handles 90 items an hour for 6 productive hours a day. You have 3 reviewers and the borderline band holds 1,900 items a day. What is the largest band the team can clear, and how many items are waiting after 5 days?

Answer

One reviewer clears 90×6=54090 \times 6 = 540 items a day, so three clear 1,620. The band of 1,900 leaves 1,900−1,620=2801{,}900 - 1{,}620 = 280 items unreviewed each day, so after 5 days 5×280=1,4005 \times 280 = 1{,}400 are waiting. The queue age keeps growing, which is why “escalate” quietly becomes “ignore”. Options: narrow the band to 1,620 or fewer, add a fourth reviewer (2,160 a day), or apply a default rule you chose in advance.

Process

Escalation, appeals and logging

  1. Clear refusal. Tell the user what happened without leaking the policy’s internals.
  2. Appeal that reaches a person. Blocked honest users have a path back.
  3. Log with context. Store blocked content and the decision so false positives can be found and classifiers improved.
  4. Protect the logs. They hold sensitive text: restrict access, minimise what is stored, set retention limits.
  5. Label and feed back. Review decisions and appeal outcomes become labelled examples for tuning.
  6. Repeat offenders. Anthropic’s guidance suggests responding to users who repeatedly try to bypass guardrails, for example by throttling or banning them.

Source1 Mitigate jailbreaks and prompt injections

Diagram

Components: the request path

Diagram: Input passes a classifier that blocks, queues for a person, or allows.

block

borderline

allow

violation

clean

User input

Input classifier
per-category

Refusal + log

Human review

LLM generates

Output check
by severity

Cancel or retract,
fallback, log

Deliver to user

Diagram summary: Input passes a classifier that blocks, queues for a person, or allows. Allowed input reaches the model, whose output is checked in a way chosen by severity: a violation is cancelled or retracted with a safe fallback and a log entry, and clean output is delivered. Retracted outputs can also go to the review queue.

Diagram

Components: the labels and tuning loop

Diagram: Blocks and retractions lead to appeals, and appeals plus review-queue decisions become labelled examples.

Blocks and
retractions

Appeal path

Labelled
decisions

Review queue
decisions

Threshold tuning
in shadow mode

Flagged rollout

Diagram summary: Blocks and retractions lead to appeals, and appeals plus review-queue decisions become labelled examples. Those labels feed threshold tuning in shadow mode, and a tuned threshold is released behind a flag.

Compare

Failure modes

FailureSignalResponse
Classifier service downTimeouts, error rateDecided in advance: fail closed for severe categories; fail open with logging for low-severity ones
Block rate spikesAlarm per categoryCompare versions and traffic; roll back the threshold or model
New attack phrasingUser reports, red-team missesAdd examples, retrain, tighten temporarily
Review queue backlogQueue ageNarrow the band, add staff, or use a default rule
Multilingual gapsHigher error rate on non-English slicesSlice metrics by language; add data
Logs leak sensitive textAccess auditMinimise stored text, restrict access, set retention

Check yourself

Check: the classifier is down for 20 minutes

The product has a severe category (sexual content involving minors) and a low-severity one (off-topic jokes). The classifier times out for 20 minutes. What should each category do, and what must have happened before the outage?

Answer

The severe category fails closed: hold or refuse rather than let unchecked content through. The low-severity category fails open, with logging so the unchecked traffic can be reviewed afterwards. The choice must have been made in advance, in the policy, with the product owner, not improvised during the incident, and an alarm on the error rate should have fired.

Process

Tune with shadow mode

  1. Run the new threshold or classifier on live traffic and record what it would have done. It acts on nothing.
  2. Compare its decisions with the current system and with human labels.
  3. Measure precision by labelling a sample of blocked items and counting false positives.
  4. Measure recall with care (next slides): misses are rare among passed messages.
  5. Report per slice: category, language and product surface.
  6. Put thresholds and classifier versions behind flags so promotion and rollback are config changes.

Worked example

Worked: sampling by score band

Illustrative split of the 985,550 messages that passed at threshold A (500 violations were missed in total, which gives recall 4,5005,000=90%\dfrac{4{,}500}{5{,}000} = 90\%).

Score band of passed messagesItemsMissesMiss rate
Just below the threshold10,0004004%
Far below the threshold975,550100about 0.01%
  • Label 1,000 items from each band. Near the threshold you expect about 40 misses, enough to estimate the rate. Far below you expect about 0.1, so the sample will probably show none.
  • Weight each band by its size. If the far-band sample shows no misses, the estimate is 10,000×4%=40010{,}000 \times 4\% = 400 misses, so recall is 4,5004,500+400≈91.8%\dfrac{4{,}500}{4{,}500 + 400} \approx 91.8\%, against the true 90%.
  • The gap is the far band’s hidden 100 misses. That is why a red-team set with known violations and user reports sit alongside the sample.

Diagram

An alarm fires: let a labelled sample decide

Scenario (illustrative): one category’s block rate goes from 0.8% to 1.6% of messages after a provider model update. No complaints yet.

Diagram: Going down, a block-rate alarm leads first to labelling a sample of the newly blocked items.

yes

no

Block-rate alarm

Label a sample of
the new blocks

Mostly honest
messages?

Revert or recalibrate
behind the flag

Keep; update
the baseline

Re-test in shadow mode

Diagram summary: Going down, a block-rate alarm leads first to labelling a sample of the newly blocked items. If most are honest messages, revert or recalibrate the threshold through its flag; if most are real violations, keep the change and update the baseline. Either way, re-test in shadow mode.
  • If honest users are already complaining, do not wait for the sample: switch the change off behind its flag first, then investigate.
  • Rule out a traffic change (a campaign or abuse wave) as well as a version change.
  • OpenAI’s guide says its moderation model will keep being upgraded, so thresholds built on its category scores may need re-tuning, and its scores are inputs to your policy rather than a verdict that blocks by itself.

Source3 Moderation

Concept

Cost and latency

  • Each classifier call costs time, and for model-based classifiers, money.
  • Run cheap rules first, a small classifier next, and the expensive model only on the middle band.
  • Cache decisions for identical inputs if the policy allows.
  • Budget the input check at 100 ms (the assumption above), and count windowed output checks against time to first token.

Trade-off: more layers catch more, and each adds latency, cost and its own false positives.

Compare

What strong answers contain

Weak answerStrong answer
One binary filterLayers chosen by risk
One global thresholdA threshold per category, set with the product owner
“Escalate to humans”A human lane sized from reviewer capacity
No path for blocked usersRefusal message, appeal and a stored label
Tune on a hunchShadow mode, labelled samples and a rollback flag

Interview note (common industry pattern, no company-specific claim): “design moderation for a chatbot” and “balance safety with annoying legitimate users” are typical prompts, and presenting moderation as a single binary filter is a common mistake.

Summary

Recap

  • Layers are a menu: input classifier, policy prompt, output check, human lane, logging and appeals.
  • Choose serial, windowed or parallel output checks by harm severity, because streamed text cannot be un-shown.
  • Thresholds are per category and set by the business; show the counts of both error types.
  • Most blocks are false positives when fpr×(benign messages)\mathrm{fpr} \times (\text{benign messages}) exceeds recall×(violations)\text{recall} \times (\text{violations}).
  • Size the human lane from reviewer capacity, and round up.
  • Tune in shadow mode; recall is hard to measure, so sample near the threshold and use red-team sets.
  • Keep thresholds behind flags so rollback is a config change.

References

References & Sources

  1. Mitigate jailbreaks and prompt injections (opens in a new tab)

    Anthropic2026Documentation

    Used for Jailbreaks and injection are a separate problem from harm classification; layered strategies; responding to repeat offenders; monitoring.

  2. Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations (opens in a new tab)

    Hakan Inan, Kartikeya Upasani, Jianfeng Chi, Rashi Rungta, et al.2023Preprint

    Used for An example of a safety classifier that uses a risk taxonomy to classify both user prompts and model responses.

  3. Moderation (opens in a new tab)

    OpenAI2026Documentation

    Used for Moderation scores are signals for your policy; streamed output scores arrive after the full output; the model is upgraded over time so thresholds may need recalibration.

  4. Metrics and scoring: quantifying the quality of predictions (opens in a new tab)

    scikit-learn2026Documentation

    Used for Definitions of precision and recall from true positives, false positives and false negatives.