LLM firewall

Also known as: AI firewall

On this page 7

An LLM firewall is a security layer placed between users, data sources and a large language model that inspects inputs and outputs in real time and blocks, rewrites or flags traffic that violates a security policy. In AI security, it is the runtime control most often used against prompt injection, jailbreaks, sensitive data leakage and unsafe output handling, and it is also known as an AI firewall.

Unlike a classic network firewall, which filters packets by address and port, an LLM firewall works on natural language and structured tool calls. It therefore relies on classifiers, pattern rules and policy engines rather than fixed signatures, and it provides probabilistic rather than guaranteed protection, which shapes how it should be deployed.

How an LLM firewall inspects traffic

An LLM firewall works by intercepting every message at defined checkpoints and passing it through a chain of detectors before the message continues. It is usually deployed as a reverse proxy or gateway in front of the model API, or as a library that the application calls before and after each model request.

The table lists the main inspection points and the threats each one addresses in a typical retrieval-augmented or agentic application.

Inspection pointWhat is checkedMain threats addressed
User promptIncoming text and attachmentsDirect prompt injection, jailbreaks, abuse
Retrieved contentDocuments, web pages, emails added to contextIndirect prompt injection, RAG poisoning
Tool callsFunction names and arguments proposed by the modelUnauthorized actions, data exfiltration
Model outputGenerated text, code and linksPII leakage, toxic content, improper output handling
Conversation statePatterns across many turnsMulti-turn jailbreaks, gradual extraction
Inspection points in an LLM application

Each detector returns a score or a verdict, and a policy engine decides the action: allow, block, redact, ask for confirmation or route the request to a stricter model. Logging every decision is essential, because the logs feed incident response and detector tuning.

Detection techniques and their trade-offs

LLM firewalls combine several detection techniques, because no single method catches the wide variety of malicious inputs. The table compares the main families by cost and reliability.

TechniqueExampleAdded latencyMain limitation
Pattern rulesRegular expressions for keys, card numbers, known jailbreak phrasesUnder 1 msEasy to evade with paraphrase or encoding
Small classifiersFine-tuned encoder models for injection or toxicityAbout 5-50 msNeed retraining as attacks evolve
LLM-as-judgeA second model rates prompt or answer safetyAbout 100 ms to over 1 sCostly and itself injectable
Semantic similarityEmbedding match against a library of known attacksAbout 5-20 msMisses novel attack styles
Canary tokensSecret markers that must never appear in outputNegligibleDetects leakage only after it happens
Detection techniques compared

Thresholds set the balance between false positives and false negatives. A strict threshold frustrates legitimate users and blocks harmless requests about security topics, while a loose one lets attacks through. Teams usually tune thresholds per application and per inspection point using red-team datasets and production samples.

An LLM firewall is one control in a defense-in-depth design, and it is useful to separate it from neighboring measures that operate at other layers.

ControlWhere it actsWhat it provides
LLM firewallRuntime gateway around the modelFiltering and policy enforcement on traffic
Safety trainingInside model weightsBaseline refusal of harmful requests
Instruction hierarchyModel training and prompt structurePriority of system over user and tool text
SpotlightingPrompt constructionMarks untrusted content so the model can tell it apart
Dual LLM patternApplication architectureKeeps privileged model away from untrusted data
Web application firewallHTTP layerBlocks classic web attacks, not semantic ones
Comparison with related controls

Architectural defenses such as the dual LLM pattern or CaMeL limit what an attacker can achieve even when an injection succeeds. A firewall reduces how often attacks reach the model, while architecture limits how much damage a successful attack causes, and robust systems need both.

Deploying an LLM firewall

Effective deployment starts with a threat model for the specific application, because a public chatbot, an internal coding assistant and an email-reading agent face different risks. The policy should name the assets to protect, such as customer data, credentials or the ability to send messages.

  • Inspect untrusted content, not only user prompts, since indirect injection arrives through documents and web pages.
  • Apply least privilege to tools and require confirmation for irreversible actions such as payments or deletions.
  • Start in monitoring mode to measure false positives before switching to blocking.
  • Version the policies and detectors, and replay saved attack sets after every update.
  • Fail closed for high-risk actions, so that a detector outage does not silently disable protection.

Latency budgets matter in interactive products. Many teams run fast checks inline and slower judge-based checks asynchronously or only on high-risk requests, which keeps response times acceptable without dropping coverage.

Limitations and failure modes

An LLM firewall cannot fully prevent prompt injection, because instructions and data share the same natural language channel and attackers can phrase the same intent in unlimited ways. Overreliance on the firewall is therefore the most serious mistake.

Failure modeCauseMitigation
Encoded attacks passBase64, Unicode tricks or token smugglingNormalize and decode before inspection
Benign users blockedOverly strict thresholdsTune on real traffic and allow appeals
Multi-turn bypassEach message checked in isolationScore the whole conversation
Leak through tool outputOnly final answer inspectedInspect tool arguments and results
Judge model hijackedInjected text targets the checkerIsolate judge prompts and use classifiers
Common failure modes and mitigations

Teams should treat firewall verdicts as risk signals within a broader program that includes red teaming with tools such as garak or PyRIT, monitoring and incident response, and should map coverage to frameworks such as MITRE ATLAS and the OWASP guidance for LLM applications.

A plain-language summary

An LLM firewall is a security guard for an AI chatbot. It reads what people send to the AI before the AI sees it. It also reads what the AI answers before anyone else sees it.

If a message tries to trick the AI, the guard can stop it. If an answer contains private data, the guard can hide it. The guard is helpful, but it is not perfect. Clever tricks can still slip past, so other protections are needed too.

An example from practice

An insurance company runs a customer-service assistant that reads policy documents and incoming emails and can open claim tickets. The security team places an LLM firewall in front of the model with three checkpoints: user messages, retrieved email content and proposed tool calls.

During the first month in monitoring mode, the firewall flags about 0.4 percent of messages, and review shows that most flags on user messages are harmless questions about fraud. The team relaxes that threshold but keeps a strict injection classifier on email content. Soon after blocking is enabled, an incoming email hides the instruction to forward all open claims to an outside address. The classifier blocks the email text from entering the context, the tool-call check would also have rejected the unknown recipient, and the event is logged for the incident team. The result is an attempted data exfiltration stopped at two layers with no customer data exposed.