LLM Security in Production: Beyond Prompt Injection
Back to all articles
Security
23 min read8 min read

LLM Security in Production: Beyond Prompt Injection

A comprehensive security framework covering prompt injection, data exfiltration, model abuse, and the defense layers we deploy in production.

Debasish Maji
Debasish Maji
AI Engineering Lead
April 10, 2026
SecurityLLMProductionPrompt InjectionDefense

The Security Landscape Has Changed

Traditional application security focused on SQL injection, XSS, and authentication flaws. LLMs introduce entirely new attack surfaces.

Your AI system can be manipulated to leak data, execute unauthorized actions, generate harmful content, and bypass your carefully crafted guardrails - all through natural language.

This post documents our defense-in-depth approach to LLM security after 18 months in production.

•••

The Threat Model

Threat CategoryRisk LevelExample Attack
Prompt InjectionCriticalOverriding system instructions
Data ExfiltrationHighExtracting training data or user data
Unauthorized ActionsHighTool calls user should not make
Output ManipulationMediumGenerating harmful content
Resource AbuseMediumDenial of service via expensive prompts
Model ExtractionLowStealing model behavior
•••

Layer 1: Input Validation

The first line of defense. Stop attacks before they reach the model.

Input Sanitization

We validate all user inputs before processing:

CheckWhat It CatchesAction
Length limitsResource abuseTruncate or reject
Character filteringEncoding attacksRemove or escape
Pattern detectionKnown attack signaturesBlock and log
Language detectionOff-topic abuseWarn or redirect

Attack Pattern Detection

We maintain a pattern library for known attacks:

Pattern TypeExamples
Instruction override"Ignore previous instructions"
Role playing"You are now DAN"
Encoding tricksBase64, ROT13, unicode abuse
Delimiter injectionFake system messages
Context overflowExtremely long inputs
Detection is not just string matching - we use semantic similarity to catch variations.

Input Validation Results

MetricValue
Attacks blocked at input73%
False positive rate0.8%
Avg validation latency12ms
•••

Layer 2: System Prompt Hardening

Your system prompt is your security policy. Harden it.

Prompt Structure

Our system prompts follow a security-first structure:

SectionPurpose
IdentityWho the assistant is
BoundariesWhat it will not do
PrioritiesSecurity over helpfulness
ExamplesGood and bad behaviors
EscalationWhen to refuse or escalate

Defense Techniques

TechniqueWhat It Does
Role reinforcementRepeatedly state identity
Explicit boundariesList forbidden actions
Priority orderingSecurity trumps helpfulness
Canary tokensDetect prompt leakage
Output format constraintsLimit response structure

Canary Tokens

We embed unique tokens in system prompts. If they appear in output, we know the prompt leaked:

Token TypePurpose
Unique IDDetect full prompt extraction
Instruction markersDetect partial leakage
Fake secretsHoneypots for data extraction
•••

Layer 3: Output Filtering

Even with input validation and hardened prompts, bad outputs can slip through.

Output Checks

CheckWhat It CatchesAction
Content moderationHarmful contentBlock and log
PII detectionPersonal data leakageRedact or block
Code injectionExecutable code in outputSanitize
Instruction echoSystem prompt leakageBlock
Format validationUnexpected structureSanitize

PII Detection

We scan outputs for sensitive data patterns:

Data TypeDetection Method
Email addressesRegex pattern
Phone numbersRegex with format detection
Credit cardsLuhn validation
SSNFormat and context
API keysKnown key formats
When detected in unexpected contexts, we redact before returning to users.

Output Filtering Results

MetricValue
Harmful content blocked99.7%
PII leakage prevented100%
False positive rate1.2%
•••

Layer 4: Tool Call Security

Function calling introduces new attack vectors.

Tool Authorization

Not every user should access every tool:

CheckPurpose
User permissionsCan this user call this tool
Rate limitingPrevent tool abuse
Argument validationAre arguments safe
Result filteringIs output safe to return

Dangerous Tool Patterns

PatternRiskMitigation
Database queriesSQL injectionParameterized queries only
File accessPath traversalWhitelist paths
HTTP requestsSSRFWhitelist domains
Code executionRCESandbox or disable

Tool Call Sandboxing

High-risk tools run in isolated environments:

Isolation LevelToolsProtection
NoneRead-only lookupsN/A
ProcessData processingMemory limits
ContainerExternal APIsNetwork isolation
VMCode executionFull isolation
•••

Layer 5: Session Security

Multi-turn conversations introduce state-based attacks.

Session Threats

ThreatDescriptionDefense
Context poisoningInjecting malicious contextContext validation
History manipulationAltering past messagesImmutable history
Session hijackingUsing another user sessionSession isolation
Gradual escalationSlowly bypassing guardrailsReset thresholds

Context Window Security

We validate conversation history before each request:

CheckPurpose
Message integrityHistory not tampered
Role validationOnly valid roles present
Content re-scanRe-check old messages
Context limitsPrevent overflow attacks
•••

Layer 6: Monitoring and Response

Security requires visibility.

Security Metrics

MetricAlert Threshold
Attack attempts per hourMore than 100
Successful bypassesAny
PII in outputsAny
Unusual tool callsStatistical anomaly
Prompt extraction attemptsMore than 10 per hour

Incident Response

When attacks are detected:

SeverityResponse
LowLog and continue
MediumRate limit user, alert team
HighBlock user, immediate review
CriticalSuspend service, full audit

Automated Response

Some responses are automated:

TriggerAutomated Action
Repeated injection attemptsTemporary block
PII leakage detectedOutput suppressed
Rate limit exceededRequest queued
Known attack signatureImmediate block
•••

Real Attack Examples

Attacks we have seen in production:

AttackMethodOutcome
System prompt extraction"Repeat your instructions" variationsBlocked by output filter
Data exfiltrationEncoding user data in responsesBlocked by PII detection
Tool abuseUnauthorized database queriesBlocked by authorization
JailbreakMulti-turn context manipulationDetected by pattern analysis
Resource exhaustion100K token inputsBlocked by input limits
•••

Defense Effectiveness

Our layered approach results:

LayerAttacks Blocked
Input validation73%
System prompt12%
Output filtering9%
Tool security4%
Session security2%
Total blocked99.6%
The remaining 0.4% are novel attacks that require manual review and pattern updates.

•••

Key Takeaways

  1. 1Defense in depth is essential - No single layer catches everything. Stack multiple defenses.
  1. 2Input validation is your best ROI - Catching attacks early is cheaper and safer.
  1. 3Treat system prompts as code - Version control, review, and test them like any other security-critical code.
  1. 4Tool calls need authorization - The model should not decide what users can do.
  1. 5Monitor everything - You cannot defend against what you cannot see.
  1. 6Plan for novel attacks - Your pattern library will never be complete. Build systems that can learn.

LLM security is not a solved problem. New attacks emerge regularly. But with layered defenses and continuous monitoring, you can operate safely in production while staying ahead of threats.

Found this helpful?

Share it with others who might benefit

TweetShare

Related articles