Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 105/ 160
06. AI Security

Input Guardrails

Filters and classifiers that catch unsafe or out-of-policy requests before model calls.

BeginnerPre-filters · Classifiers3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Input guardrails check what people send to the AI before it answers, stopping unsafe or off-topic requests early and cheaply.

Think of it like…

A venue entrance: a quick bag check and ticket scan for everyone (rules), a metal detector for most (classifier) and a manual search only for the few who set off the alarm (judge), because searching everyone would be slow and expensive.

Where you’ve seen it

A chat service handles 1,000,000 requests a day. Stage 1 (regex, allowlists, length limits, Unicode normalisation) is free and blocks 1.5% of traffic. Stage 2 is a 15 ms classifier (injection, PII, toxicity) costing $0.00002 per request on the remaining 985,000 requests ($19.70 a day) and flags 3% as borderline. Stage 3 is an LLM judge at $0.0008 per call on only those 29,550 borderline requests ($23.64 a day), versus $800 a day if the judge ran on everything: the cascade costs $43.34, 94.6% less. The classifier, tested on 10,000 labelled attacks and 100,000 benign requests, has 91% recall and a 0.4% false-positive rate. But the real attack rate is 0.1% (1,000 attacks a day): it catches 910, and also wrongly flags 999,000 × 0.4% = 3,996 benign requests, so precision is 910 / (910 + 3,996) = 18.5%. Because most alerts are false, the team uses graded actions: block only high-confidence attacks, send mid-confidence ones to a stricter prompt or a human queue and log the rest.

Words you’ll hear

Canonicalisation
Normalising text (Unicode, whitespace, encodings) so filters see what the model sees.
Tiered guard
Cheap rules first, then classifiers, then model judges for hard cases.
Base-rate effect
When attacks are rare, even accurate detectors produce mostly false positives.
Graded response
Block, sanitise, route, flag or allow depending on confidence and risk.

Visual diagram

Loading interactive diagram

Theory & deep dive

What to check and in what order

Start with deterministic checks: maximum length and token count (caps cost and long-context attacks), allowed content types, canonicalisation (Unicode normalisation, removal of zero-width and control characters, decoding of obvious encodings so filters and the model see the same text), language and intent allowlists (the bot supports billing and shipping questions only), rate limits and quota checks per user and tenant. These are fast, explainable and cover a lot. Then detectors: prompt-injection classifiers, PII and secret scanners (patterns plus entity recognition), toxicity and policy-category classifiers, and topic or intent routers that send off-topic questions to a canned reply.

Escalate only uncertain cases to a model-based judge that reads the request with a policy and returns a verdict and reason; cache decisions for repeated inputs. Design actions per outcome: block with a clear message, sanitise (redact PII, strip hidden characters), route to a stricter system prompt or to a human queue, reduce capabilities (disable tools for this request) or just log and monitor. Preserve context: guard the whole prompt you send (including retrieved content and tool results), not only the user message, since indirect injection arrives through other channels. Version policies and thresholds, and keep an audit trail of decisions.

Cascade economics

Judge-on-everything: 1,000,000 × $0.0008 = $800/day. Cascade: classifier on 985,000 × $0.00002 = $19.70 plus judge on 3% of those (29,550 × $0.0008 = $23.64) = $43.34/day, a 94.6% saving with the same judge quality on the hard cases.

Key takeaway: Use cheap deterministic checks, then classifiers, then judges, and apply the guard to the entire assembled prompt.

Evaluation, base rates and failure modes

Evaluate guards on labelled attack and benign sets, reporting recall (attacks caught), false-positive rate and latency, and break results down by category and language. Then translate to production using the base rate: if only 0.1% of traffic is malicious, a detector with 91% recall and 0.4% FPR yields 910 true catches and 3,996 false alarms per million requests: precision 18.5%. That doesn't make it useless, but it determines the action: blocking on every flag would reject thousands of legitimate users, so reserve hard blocks for high-confidence scores or high-risk contexts and use softer responses elsewhere. Tune thresholds on cost: the cost of a missed attack versus a blocked legitimate user, per route.

Known failure modes: evasion (paraphrase, translation, encoding, typos, splitting payloads across turns), over-blocking of security education, medical or legal questions, bias across languages and dialects, latency added to every request (budget it: 20 to 50 ms for the guard stack), drift as attackers adapt and products change, and false confidence ("we have guardrails") that leads teams to relax controls on tools. Guardrails are one layer: pair them with least-privilege tools, output validation and approvals. Keep a feedback loop: sample blocked and allowed traffic for human review, add misses to the suite and publish a way for users to appeal blocks.

Base rate

1,000,000 requests, 1,000 attacks (0.1%). Recall 91% → 910 caught. FPR 0.4% of 999,000 = 3,996 benign flagged. Precision = 910 / 4,906 = 18.5%. Blocking everything flagged would reject about 4 legitimate users for every attack stopped.

Key takeaway: Measure recall and FPR, then compute production precision from the base rate and choose graded actions.

How it works, step by step

Step 1 of 4
Product + security

1. Define policy and routes

List supported intents, languages, limits and what to do for each violation category.

billing and shipping only
Key numbers at this step
Action per outcome
defined

When to use it & trade-offs

What it is

Input guardrails are checks applied to a request before it reaches the model (or its tools): length and format limits, canonicalisation of text, allowlists of supported intents and languages, detectors for prompt-injection patterns, PII and secrets, toxic or disallowed content classifiers and rate limits. They block, sanitise, route or flag requests according to policy. Because they run on every request, they must be fast and cheap, so practical designs are tiered: free rules first, a small classifier second and a model-based judge only for borderline cases.

Why it matters: Guardrails cut cost and risk early: they stop obviously abusive or out-of-scope traffic before paying for an LLM call, reduce exposure to injection and data leaks and give a consistent place to enforce policy. But they are also easy to over-trust: attacks evade filters, and at low attack base rates even accurate classifiers produce mostly false alarms, so they must be combined with controls on actions and designed to degrade gracefully (flag, route to review, or ask a clarifying question) rather than only block.

When to reach for it

  • Public chat and API endpoints
  • Reducing cost from abusive or out-of-scope traffic
  • Enforcing policy consistently across features

When to avoid or be careful

  • Checking only the user message and not retrieved content
  • Blocking on every flag regardless of base rate
  • Treating guardrails as a replacement for tool controls

Guardrail techniques

Rules and allowlists
Best for: Fast, explainable first-line checks

Strengths: Free, deterministic, low latency.

Watch out: Easy to evade; rigid.

Small classifiers
Best for: Scalable detection of injection, PII and toxicity

Strengths: Fast and cheap; learn patterns.

Watch out: Need data; false positives and drift.

LLM judge
Best for: Nuanced borderline decisions

Strengths: Flexible and context-aware.

Watch out: Slower and costlier; evadable by crafted input.

Interview signals & numbers to know

When this topic comes up

  • “Filter bad requests before they reach the model”
  • Allowlisted intents
  • Injection classifiers
  • False-positive rate
  • Guard latency budget

Benchmarks & rules of thumb

$43.34 vs $800 -
daily cost of the cascade versus a judge on all traffic
18.5% -
precision at a 0.1% attack rate with 91% recall and 0.4% FPR
20 – 50 ms -
typical latency budget for the guard stack

Common mistakes & follow-ups

Common interview mistakes

  • Ignoring the base rate and drowning in false alarms.
  • Not normalising Unicode so filters miss obfuscated payloads.
  • Running guards only on the first turn of a conversation.

Likely interviewer follow-ups

  • How would you design guardrails that are fast and cheap?
  • Why is precision low when attacks are rare?
  • What should happen to flagged but uncertain requests?
Interview tip: Compute production precision from the base rate. It's the detail that shows you've operated detectors, not just trained them.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Input Guardrails with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
OWASP Top 10 for LLMs
Next topic
Output Validation