Home / AI Architecture & System Design / AI System Design
Design a content moderation service that inspects LLM outputs in real time.
30-second answer
Functional: classify streamed LLM output against a policy taxonomy, apply per-tenant actions (allow, redact, halt and replace) and log every decision for audit and human review. Non-functional: under ~300 ms added to first text with no stutter, 99.95% availability, per-category precision and recall targets, fail-open or fail-closed per surface. Design: a shared service the LLM gateway streams to; text is held in sentence-sized windows, a small classifier scores every window, an LLM judge handles uncertain ones, and a policy engine decides. Key trade-off: holding text keeps users safe but adds delay, so use a small first window and pipeline the checks.
Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.
New to these terms? 14 terms on this page are explained in the glossary
0–5 min Functional requirements
Don't start drawing boxes yet. Spend the first few minutes agreeing on what the service has to do. A short exchange like this sets the scope:
You Is this a moderation layer for one product, or a shared platform service that many products call?
Interviewer Shared. A consumer chat app, a coding assistant and enterprise customers on our API all go through it.
You Are we moderating model outputs only, or user prompts too?
Interviewer Focus on outputs. Mention prompts if there's time.
You Are outputs streamed to users token by token?
Interviewer Yes, almost everything is streamed.
You When something violates policy, what should happen? Block it, redact part of it, or just flag it for review?
Interviewer It depends on the product. That's part of what I want you to design.
You Do policies differ per customer? A children's education app and a security research tool shouldn't have the same rules.
Interviewer Right. Enterprise customers want to tune thresholds, within limits we set.
That's enough to write the functional requirements on the board:
| # | Functional requirement | Why it matters |
|---|---|---|
| F1 | Classify LLM output against a policy taxonomy (hate and harassment, sexual content, sexual content involving minors, violence, self-harm, dangerous instructions, PII leakage), with a severity for each category | The core job. Severity drives which action to take |
| F2 | Work on streamed output, not only complete responses | Most traffic is streamed. Checking only at the end means users have already read the text |
| F3 | Take an action: allow, warn, redact a span, halt the stream and replace it, or block a whole response | Different products need different responses to the same score |
| F4 | Per-tenant and per-surface policies (categories, thresholds, actions), versioned and changeable without a deploy, with platform minimums tenants can't lower | It's a shared platform with very different risk tolerances |
| F5 | Use context: the prompt and recent conversation, not only the output text | "How do poisons affect the liver?" in a toxicology course is not a threat. Quoting hate speech is not endorsing it |
| F6 | Record every decision and the reasons behind it | Compliance, appeals and debugging |
| F7 | Human review and appeals, with reviewer labels fed back into training and evaluation | Classifiers make mistakes and drift. Human labels are the ground truth |
| F8 | Shadow mode for new classifiers and policies | Test changes on real traffic without enforcing them |
Also say what's out of scope, so you don't run out of time: image and audio moderation, account-level enforcement (bans, limits on abusive users), and training the classifiers from scratch. Each is a good extension to mention at the end.
5–10 min Non-functional requirements and estimates
Next, the qualities the system must have. These drive most design decisions, so push for numbers.
You How much delay can moderation add before users notice?
Interviewer Time to first text matters most. Product says we can add about 300 ms there. After that, the stream shouldn't stutter.
You And if the moderation service is down, should products keep serving unmoderated output, or stop?
Interviewer What would you suggest?
You It should depend on the surface. A children's app should fail closed and show an error. An internal developer tool can fail open and be scanned afterwards. I'll make that a per-surface policy setting instead of a global rule.
| Requirement | Target | What it forces in the design |
|---|---|---|
| Added latency, streaming | ≤ 300 ms to first visible text, then no stutter | A small first window; each check must be much faster than generating the next window |
| Added latency, non-streaming | ≤ 50 ms at p95 for a typical response | Tier 1 must be a small model, batched on GPUs |
| Availability | 99.95% | Stateless replicas across zones, and defined behaviour when degraded |
| Failure mode | Fail-open or fail-closed, chosen per surface | It's part of the policy, not hard-coded |
| Quality | Per-category targets, e.g. ≥ 95% recall on the most severe categories and ≤ 0.5% false positives on benign traffic | Separate, calibrated thresholds per category; labelled evaluation sets |
| Consistency | Same input + same policy version + same model versions → same decision | Version everything and log the versions with each decision |
| Isolation and privacy | Tenants' policies and data are isolated; flagged text is kept with restricted access; benign text isn't stored | Store benign decisions as metadata only |
| Cost | LLM-judge escalations ≤ ~2% of checks | Escalate only uncertain cases, with a budget |
Back-of-envelope estimates. State your assumptions out loud. Interviewers care about the reasoning more than exact numbers.
- Traffic: at peak, 5,000 responses start per second, averaging 400 output tokens at ~50 tokens/s. Each response streams for about 8 s, so there are roughly 40,000 concurrent streams.
- Checks: with windows of ~40 tokens, that's 10 checks per response, or ~50,000 classifications/s.
- Tier 1 compute: each check reads the window plus ~90 tokens of context, about 128 tokens. A ~100M-parameter encoder needs about 2 × parameters × tokens ≈ 2.6 × 10¹⁰ FLOPs per check, so ~1.3 × 10¹⁵ FLOP/s in total. At ~100 TFLOP/s of real throughput per GPU, that's about 13 GPUs at perfect utilization; plan for 20–25 with headroom. Takeaway: Tier 1 must be small, and window size is a direct cost lever.
- Tier 2 cost: escalating 2% of checks means ~1,000 LLM-judge calls/s with ~500 prompt tokens each. That's expensive, so most escalations should be asynchronous, with only the most severe categories waiting inline.
- Audit storage: ~1 KB of metadata per response is ~5 MB/s, roughly 430 GB/day. Keep full text only for flagged and sampled responses.
10–18 min High-level design
Start with where the service sits, because it affects everything else.
You I see three options: a library inside the LLM gateway, a sidecar next to each product, or a separate service that the gateway calls. I'd build a separate service. Several products share it, it needs GPUs that scale differently from the gateway, and policy changes shouldn't require redeploying every product. It runs in the same region and zones as the gateway, so each call costs only a millisecond or two.
Interviewer Fine. Walk me through it.
Scroll sideways to see the whole diagram.
Components:
- LLM gateway (already exists): sits between products and models. For each response it opens a bidirectional stream to the moderation service and forwards text to the user only after it's released.
- Segmenter: buffers tokens into windows, closing each one at a sentence end, a maximum size or a timeout.
- Tier 1 classifiers: a small multi-label model plus rule-based detectors for PII and secrets. They score every window.
- Tier 2 LLM judge: a larger model with the written policy in its prompt. It only sees windows that Tier 1 is unsure about.
- Decision engine: turns scores into an action using the tenant's policy.
- Policy service: stores versioned policies and pushes them to decision-engine instances, which cache them so nothing is looked up per request.
- Audit log: an append-only event stream (e.g. Kafka) into a data warehouse, written off the critical path.
- Human review: a queue and tooling for sampled, borderline and appealed items. Reviewer labels flow back into training and evaluation sets.
Life of one streamed response:
- The product calls the gateway with
tenant_id,surfaceand the prompt. The gateway opens a moderation stream and pins the policy version for this response. - As the LLM produces tokens, the gateway forwards them to the moderation stream.
- The segmenter closes a window at a sentence end, at 40 tokens or after 300 ms, whichever comes first.
- Tier 1 scores the window with its context. Clear passes and clear violations go straight to the decision engine; uncertain scores go to Tier 2, inline or in the background depending on the policy.
- The decision engine returns
release,redactorhaltfor that window, and the gateway forwards released text to the user. - On
halt, the gateway cancels the generation, sends replacement text, and marks the turn so the partial text isn't sent back to the model next turn. - Every decision goes to the audit stream, and a sample goes to human review.
API sketch. Two shapes: one for complete responses and one for streams.
# Non-streaming
POST /v1/moderate
{ tenant_id, surface, prompt, context: [...recent turns], output: "..." }
→ { decision_id, action: "allow" | "redact" | "block",
categories: [{ name, score, severity }], redact_spans: [[start, end]],
policy_version, model_versions }
# Streaming: one bidirectional gRPC stream per response
client → Chunk { request_id, seq, text_delta, is_final }
server → Verdict { request_id, up_to_seq, action: RELEASE | REDACT | HALT,
replacement_text?, decision_id }
Sequence numbers tell the gateway exactly which text is safe to release, and make retries idempotent.
How it works: a worked example
A study aid: one streamed response traced window by window, with the actual messages between the gateway and the moderation service, including one window that gets halted.
The scenario. A teen-facing homework app (tenant=edu-01, surface=teen_chat, policy v42, fail-closed) asks the model about chemistry. The model's answer starts innocently and then drifts into instructions it shouldn't give.
1. The gateway opens a moderation stream for this response and pins the policy version:
OpenStream { request_id: "r_77ab", tenant: "edu-01", surface: "teen_chat",
policy_version: 42, context: [last user turn, ~90 tokens] }
2. Windows flow as tokens are generated (~40 tokens or a sentence end, at most 300 ms):
→ Chunk { seq: 1, text_delta: "Great question! Oxidation reactions happen when..." }
Tier 1 scores (12 ms): violence 0.01, self_harm 0.00, dangerous_chem 0.04, pii 0.00
← Verdict { up_to_seq: 1, action: RELEASE } → user sees the first sentence
→ Chunk { seq: 2, text_delta: "For example, rust forms when iron reacts with..." }
← Verdict { up_to_seq: 2, action: RELEASE }
→ Chunk { seq: 3, text_delta: "If you wanted to make something that releases a toxic gas, you would mix..." }
Tier 1: dangerous_chem 0.63 (uncertain band 0.35–0.85 for this surface)
Tier 2 (inline, because dangerous_chem is a severe category on teen_chat): LLM judge with
policy text → { "violation": true, "category": "dangerous_chem", "severity": "high" } (310 ms)
← Verdict { up_to_seq: 3, action: HALT,
replacement_text: "I can't help with that, but I'm happy to explain how these reactions work safely in a lab.",
decision_id: "d_5c19" }
3. The gateway acts on HALT: it cancels generation (saving the remaining tokens), sends the replacement text to the user instead of window 3, and marks the turn so the withheld text never goes back into the model's context next turn.
4. What the user saw: two sentences about oxidation, a pause of about a third of a second, then the safe redirect. They never saw any of window 3.
5. The audit event (written to the event stream asynchronously):
{ "decision_id": "d_5c19", "request_id": "r_77ab", "tenant": "edu-01", "surface": "teen_chat",
"policy_version": 42, "tier1_model": "mod-small-2026-10", "tier2_model": "judge-v3",
"window_seq": 3, "category": "dangerous_chem", "tier1_score": 0.63, "action": "HALT",
"latency_ms": { "tier1": 12, "tier2": 310 }, "text_ref": "restricted-store://d_5c19" }
Because it was flagged, the window's text is stored in the restricted store (access-logged, 90-day retention) and the case is sampled into the human review queue. Benign windows are stored as metadata only.
Where each piece runs:
| Component | Runs as | Example technology | Sizing (50k checks/s peak) | If it fails |
|---|---|---|---|---|
| Moderation front end | Stateless gRPC service, multi-zone | Go/Rust/C# service | Holds ~40k concurrent streams | Gateway applies the surface's fail-open/closed policy |
| Segmenter + decision engine | In the front-end process | — | Pure CPU, sub-millisecond | — |
| Tier 1 classifiers | GPU inference servers with dynamic batching | ~100M-parameter encoder on Triton/TorchServe | 20–25 GPUs | Shed to a CPU fallback for severe categories only |
| Tier 2 judge | LLM endpoint with a separate quota | Hosted or self-hosted mid-size model | ~1,000 calls/s at 2% escalation, mostly async | Inline: use Tier 1's conservative threshold; async: queue |
| Policy service | Config service pushing versions | Postgres + push to in-memory caches | Rare writes | Engines keep the last pinned version |
| Audit stream | Event log → warehouse | Kafka → BigQuery/Snowflake | ~5 MB/s metadata | Buffer locally; alert; never block releases |
| Review tooling | Internal web app + queue | — | A sample per category | Backlog grows; doesn't affect users |
18–32 min Deep dive
Rather than covering everything shallowly, offer a choice:
You The three areas I think matter most are streaming enforcement, the classifier tiers, and the policy and decision engine. Where would you like to start?
Interviewer Streaming. How do you stop harmful text reaching the user if you can only check it after it's generated?
Deep dive 1 · Streaming enforcement
Release strategy. There are two options:
- Hold, then release: the gateway holds each window until it's approved. Users never see unchecked text, but it appears one window late.
- Release, then retract: text goes out immediately. If a later check fails, the client removes it and shows a replacement. Faster, but users can briefly see harmful text.
I'd hold by default, and allow release-then-retract only for low-severity categories on surfaces that opt in, such as internal tools.
Interviewer Holding a 40-token window at 50 tokens/s is 800 ms. That blows your 300 ms budget.
You Two things fix that. First, the first window is small, about 12 tokens or the first clause, so first text appears about 250 ms after the model's first token instead of 800 ms. Later windows grow to 40 tokens. Second, checks are pipelined: while window 2 is being checked, window 3 is already generating. A check takes ~10 ms and a window takes ~800 ms to generate, so after the first window, holding adds no visible delay.
Scroll sideways to see the whole diagram.
One side effect: text arrives in sentence-sized chunks rather than token by token. Most users don't notice; if the product wants a typing effect, the client can animate each released chunk.
Context across windows. A single window can look harmless on its own: "Step 3: heat the mixture to…". So each check includes the previous one or two windows and a short summary of the prompt. Every few windows, and once at the end, a response-level check reads everything so far, to catch harm that only shows up in aggregate.
Halting cleanly. When a window fails:
- Cancel the generation upstream, which also stops paying for tokens.
- Send replacement text to the user.
- Mark the turn as moderated in conversation storage, so the partial output isn't fed back to the model as context. Otherwise the model may simply continue it next turn.
- Record the event with the window, scores and policy version.
Backpressure. If moderation falls behind, the gateway keeps holding text; it never releases unchecked text to catch up. If a window waits longer than a deadline (say 1 s), the surface's failure mode applies.
Interviewer OK. What's in Tier 1, and how do you decide when to call Tier 2?
Deep dive 2 · Classifier tiers
Tier 1 runs on every window and takes ~5–10 ms:
- A small multilingual encoder (around 100M parameters) fine-tuned for multi-label classification. One forward pass returns a score for every category.
- Rule-based detectors alongside it: PII patterns (emails, phone numbers, card numbers verified with the Luhn check), secret formats such as API keys, and short, high-precision blocklists.
- Normalization before classification: look-alike Unicode characters, zero-width characters, leetspeak and spacing tricks.
- Served on GPUs with dynamic batching: requests wait up to 2–5 ms to form a batch, which raises throughput a lot for little added latency.
Calibrated scores and an uncertainty band. Each category has two thresholds:
score < low → allow
low ≤ score < high → uncertain → Tier 2
score ≥ high → violation → action from the policy
Scores are calibrated (for example with temperature scaling on a held-out set), so a threshold of 0.8 means roughly the same thing after a model upgrade. Without calibration, every retrain silently changes every tenant's effective policy.
Tier 2 sees only uncertain windows and takes ~300–800 ms. It's an LLM judge given the written policy for the relevant categories, the window and its context. It returns a category, a severity and a short rationale, which reviewers and auditors can read later.
Interviewer 800 ms inline is a lot.
You Agreed, so Tier 2 runs inline only when the policy says so: severe categories on high-risk surfaces, where a short pause is better than the risk. Everywhere else it runs in the background. We release based on Tier 1, and if Tier 2 later finds a violation, we retract the text (where the surface supports it) and log it for review. Tier 2 also has a concurrency budget. When it's exceeded, uncertain windows fall back to Tier 1 with that category's stricter threshold.
Severity changes the rules. Sexual content involving minors has a very low threshold, can't be turned off by any tenant, and fails closed. Mild profanity is optional per tenant and may only trigger a warning.
Deep dive 3 · Policy and decision engine
- A policy is versioned configuration per tenant and surface: enabled categories, thresholds, the action for each severity, whether Tier 2 runs inline, the release strategy and the failure mode.
- Platform floor: the platform defines minimums (categories that are always on, maximum thresholds). Tenant changes are validated against them when saved.
- Policies are compiled into lookup tables and pushed to decision-engine instances, which cache them, so a decision is an in-memory lookup. The policy version is pinned when a response starts, so a policy change mid-stream can't produce mixed decisions.
- When several categories trigger, the most severe action wins: halt, then redact, then warn, then allow.
- Shadow policies: run a candidate policy next to the active one and log where they disagree before switching.
Deep dive 4 · Measuring quality (if time allows)
- Labelled evaluation sets per category and language, including hard cases: quotations, fiction, medical and security education, reclaimed slurs.
- Precision and recall per category, plus the false-positive rate on a random sample of benign traffic. Over-blocking is a real failure, not a safe default.
- Review queue sources: a random sample (~0.1%), uncertain windows, cases where Tier 1 and Tier 2 disagree, and user appeals and reports. Track how often reviewers agree with each other.
- New classifier versions go through offline evaluation, then shadow mode, then a canary, compared category by category.
- Alerts on sudden changes in block rate per tenant or category. It's either an attack or a regression, and both need attention.
32–37 min Trade-offs
Summarize the main decisions explicitly. This is often where seniority shows.
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Release strategy | Hold, then release | Release, then retract | Users never see unchecked text; a small first window keeps latency within budget |
| Window size | Small first window, then ~40 tokens | One fixed size | Small windows cut latency but cost more checks and carry less context; large windows are cheaper but slower |
| Classifier design | Small model on everything, LLM judge on uncertain cases | LLM judge on everything | Far cheaper and faster; the judge's quality goes where it matters |
| Tier 2 timing | Background by default, inline for severe categories | Always inline | Latency and cost versus a brief exposure to low-severity content |
| Deployment | Separate shared service | Library inside the gateway | Independent GPU scaling and policy changes, for the cost of one network hop |
| Failure mode | Chosen per surface | One global setting | A children's app and a developer tool carry different risks |
| Thresholds | Per category, calibrated | One threshold for all | Different harms need different precision–recall balances |
| Storage | Metadata for everything; text only for flagged and sampled items | Store all text | Privacy and cost, while keeping enough for audit and review |
Also say what you'd build first: non-streaming moderation with Tier 1 and audit logging, then hold-and-release streaming for one high-risk surface, then Tier 2 and self-service tenant policies.
37–40 min Wrap-up and likely follow-ups
Close with a short summary: "A shared moderation service checks streamed output in sentence-sized windows. A small classifier checks everything, an LLM judge checks the uncertain cases, and per-tenant policies decide the action. Text is held until approved, with a small first window to stay within the latency budget. Every decision is versioned and logged, and human review closes the loop."
Then expect follow-ups:
- What if a user spreads harmful instructions across many turns? Add a conversation-level check over a rolling summary, plus per-user signals such as repeated near-misses that tighten thresholds for that conversation.
- Would you moderate prompts too? Yes, with the same service and a different policy: jailbreak and prompt-injection detection, plus categories where the request itself is the problem. Checking the prompt can stop a generation before it starts, which also saves cost.
- What about tool calls and code? Treat tool-call arguments as output and check them too, for example secrets in arguments or destructive shell commands, with detectors suited to code.
- How do you roll out a new classifier? Offline evaluation per category, shadow mode on live traffic, a canary by tenant, and automatic rollback if block rates move unexpectedly.
- Images? Same architecture with different Tier 1 models. The policy and decision engine don't change.
What interviewers listen for
- Requirements first, with numbers, and design choices traced back to them.
- A concrete answer to "what happens to the stream": hold or retract, windowing, halting.
- Tiering for latency and cost, with calibrated thresholds per category.
- Per-tenant policies with a platform floor, versioning and audit.
- Honest trade-offs, including the cost of false positives.
Red flags
- Checking only the complete response after it's been streamed to the user.
- Running an LLM judge on every window with no cost or latency estimate.
- One global threshold for every category and customer.
- No plan for when the moderation service itself fails.
Discussion
Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.