A stateless, zero-latency reverse proxy for real-time PII redaction in LLM streams.
8
stars
342
commits
Python
primary language
Sep 6, 2026
updated
📖 Read the full docs and try the interactive PII-redaction playground → Type real-looking PII into your browser and watch it get redacted before it ever reaches an LLM, then rehydrated on the way back — no signup, no server calls, entirely client-side.
Ultra-Low Latency Generative AI Sanitization for Highly Regulated Enterprise Infrastructure
LLM-Shield-Proxy is a hyper-fast, FastAPI-based streaming gateway designed specifically for environments where data privacy is paramount (Banking, Healthcare, Legal). It intercepts and sanitizes real-time LLM streams to prevent the leakage of Non-Public Personal Information (NPI), Protected Health Information (PHI), and Payment Card Industry (PCI) data without degrading the end-user streaming experience.
By utilizing a highly optimized Tiered Detection Approach, LLM-Shield-Proxy applies guardrails at the microsecond level, helping your AI applications meet strict InfoSec mandates (GLBA, PCI-DSS, HIPAA) while maintaining zero-perceived-latency.
Option 2: Zero-Internet Air-Gapped Mode
* Egress Gateway can be any standard network proxy (e.g., Squid, Envoy, LLMLite, NGINX).
Technical controls supporting SOC 2 Type II and HIPAA safeguards for LLM streams, without breaking real-time latency.
LLM-Shield-Proxy is an open-source, zero-egress PII redaction and compliance AI Gateway and LLM Firewall deployed directly within your corporate VPC. It intercepts OpenAI-compatible LLM API requests, redacts Personally Identifiable Information (PII) and raw secrets before they leave your infrastructure, and deterministically re-hydrates real-time Server-Sent Events (SSE) chat responses with ultra-low stream latency.
Designed to enforce Zero Trust AI and support enterprise privacy compliance programs (SOC 2 trust criteria, HIPAA, HITRUST technical safeguards) without breaking real-time streaming latency.
LLM-Shield-Proxy intelligently routes traffic through two distinct redaction pipelines based on the payload structure. This ensures that autonomous agents don't crash from broken syntax trees, while human prompts get the highest quality contextual masking.
For standard conversational text, the proxy respects your configured masking mode. You can choose from four strategies:
John -> Maya). Preserves LLM attention weights and token counts. Requires Redis.[PERSON_1]). Requires Redis.***). Cannot be rehydrated.When the proxy detects structured AI tool calls or JSON-RPC 2.0 payloads, it bypasses your configuration and strictly enforces an AST-Aware Semantic Firewall with STATELESS_SYNTHETIC.
{"_shield_val": "Maya", "_shield_ctx": "aesgcm..."}). This guarantees 100% valid JSON syntax without relying on Redis state.<85 MB RAM).policies.yaml) dynamically maps virtual_key_id identities to granular security roles, custom PII profiles, and thread-safe $O(1)$ setting overrides.gen_ai.* spans directly to your GRC platform (Vanta/Drata) or SIEM (Datadog) to support SOC 2 audit evidence, ISO 42001 AI Management System forensics, and comprehensive LLM Security Posture Management (LLM SPM).GET /api/v1/audit/pubkey); llm-shield-proxy compliance-report --framework=hipaa bundles verified audit evidence, NIST OSCAL results, and a SHA-256 integrity manifest into a single auditor-ready .zip.exec_sql, shell_exec) mid-stream using a zero-allocation JSON parser, enforcing fail-closed tool access controls backed by Redis, OPA, or Vault policy stores to prevent agent drift.ext_proc for zero HTTP network hops, paired with a zero-dependency Kubernetes Mutating Webhook.google-re2) guarantee linear execution time against adversarial regex payloads.Because LLM-Shield-Proxy natively mimics the OpenAI specification, you do not need to rewrite your application code. You simply change the base_url in your SDK or the endpoint in your curl command. The proxy intercepts the payload, redacts it, and translates the schema to the correct upstream provider automatically.
Option A: cURL
# ❌ Before: Sending raw PHI directly to OpenAI
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer sk-openai-key" \
-d '{"messages": [{"role": "user", "content": "My SSN is 000-00-0000"}]}'
# ✅ After: Sending payload through LLM-Shield (Zero Egress)
curl http://localhost:8000/v1/chat/completions \
-H "Authorization: Bearer shield-virtual-key" \
-d '{"messages": [{"role": "user", "content": "My SSN is 000-00-0000"}]}'
Option B: Python SDK (1-Line Change)
from openai import OpenAI
client = OpenAI(
api_key="your-openai-api-key",
base_url="http://localhost:8000/v1", # Point to LLM-Shield-Proxy
)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Contact Sarah Connor at sarah@example.com or 555-0199."}],
stream=True,
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="", flush=True)
Spin up the zero-egress proxy in seconds.
Option A: Run the Live Streaming Demo (Docker Compose)
# 1. Spin up the proxy container in background
docker compose up -d
# 2. Verify health probe
curl http://localhost:8000/healthz
# 3. Run the live demo script
python examples/demo.py
Option B: Standalone Container (Production Base)
docker run -d -p 8000:8000 \
-e OPENAI_API_KEY="sk-your-openai-api-key" \
-e HOST="0.0.0.0" \
-e PORT=8000 \
--name llm-shield-proxy \
ghcr.io/ninadphalak/llm-shield-proxy:latest
For architectural diagrams showing VPC and Air-Gapped Egress gateway setups, please refer to the Deployment Topologies guide.
LLM-Shield-Proxy is heavily modular. You can configure the engine based on your specific compliance ROI and memory constraints:
| Installation Tier | Command | Capabilities Included | Use Case / Trade-off |
|---|---|---|---|
| Standard Mode (Microsecond Proxy) | pip install llm-shield-proxy | Tier 1 (Regex) & Tier 2 (Shannon Entropy) | Best for DevOps & Secrets: Operates with ultra-low memory (<85 MB RAM) and maximum throughput. Coverage: 100% deterministic catch rate for structured compliance data (SSNs, Emails, IP/MAC) and high-entropy cryptographic secrets (API Keys, Hex tokens). Misses conversational/free-text names. |
| Full NLP Mode (Contextual NER) | pip install "llm-shield-proxy[ner]" | Adds Tier 3 (ONNX Runtime NER) | Best for HIPAA/GDPR: Adds a quantized BERT-NER model via ONNX runtime to extract conversational PII (Patient Names, Organizations) from free-text. Coverage: >95% F1 Recall for contextual entities on standard benchmark datasets, matching the accuracy of enterprise cloud NLP APIs (AWS Comprehend, Google Cloud DLP, Microsoft Presidio) at 10x lower memory. Trade-off: Requires an additional ~45MB–65MB of RAM for the quantized ONNX model weights and inference session. |
Enabling Tier 3 ONNX NER: When installed with
[ner], enable deep neural entity extraction by settingENABLE_TIER3_ONNX_NER=truein your.envor environment variables (and optionally pointONNX_MODEL_PATHto custom model weights). If disabled or not installed, the engine automatically and gracefully bypasses Tier 3 with zero startup overhead.
LLM-Shield-Proxy is highly extensible without risking latency or ReDoS.
custom_regex.yaml. Mathematically guaranteed O(N) execution for ReDoS immunity.| Existing Legacy Proxies | LLM-Shield-Proxy |
|---|---|
| Destroys Real-Time SSE Streaming: Buffers entire responses before scanning, causing multi-second UI latency stalls. | Ultra-Low Latency Streaming: Redacts and re-hydrates delta-by-delta as SSE packets stream. |
| Heavy Memory Footprint: Requires 1GB–2GB RAM for heavy spaCy or PyTorch NLP libraries. | Ultra-Lightweight <85 MB RAM: Runs on a microsecond compiled regex + Shannon entropy + synthetic generator engine. |
| Data Liability: Stores user PII in long-term databases. | Zero Long-Term Storage (Zero-Data Mode): Self-destructing TTL session vault built for zero data liability. Operates in strict "Zero-Data Mode"—no prompts, PII, or context windows are ever written to persistent disk or external storage. |
| Complex Cloud Egress: Routes data to 3rd-party SaaS inspection APIs. | 100% Zero-Egress VPC: All scanning happens locally inside your secure corporate boundary. |
Designed specifically for highly regulated enterprise environments, strict Zero Trust AI network architectures, and security-first engineering teams implementing LLM Security Posture Management (LLM SPM).
It's a crowded space. Here is exactly why you should deploy LLM-Shield-Proxy instead of the alternatives:
LLM-Shield-Proxy is not a model router. It is designed to deploy as a transparent edge proxy directly in front of industry-standard orchestration tools. It stacks with your existing AI routing infrastructure, requires zero code changes, and is compatible out-of-the-box with:
Drop LLM-Shield-Proxy directly in front of them to guarantee deterministic data masking, mapped to SOC 2 control evidence, before the payload ever reaches the orchestrator.
localhost:8000.[PER... SON_1]) ensuring split tokens never leak.LLM-Shield-Proxy delivers enterprise privacy and zero-trust security through highly optimized architectural breakthroughs.
View the Complete Architecture Deep Dive 🏛️: For an exhaustive breakdown of the streaming lexer, memory mechanics, and service mesh integrations.
Rust-backed orjson engine parses fragmented Server-Sent Events with mathematical overlap bounding, enabling high-throughput without Python GIL saturation and capping memory at <85 MB.
google-re2)All identifiers and custom dictionaries are pre-compiled into Deterministic Finite Automatons (DFAs) in C++, guaranteeing linear execution time to physically immunize the proxy against Regex Denial of Service (ReDoS).
Vectorized O(N) math loop evaluating H(S) bit density to instantly intercept unstructured 64-char cryptographic keys in <6 µs.
Dynamically intercepts OpenAI/MCP tool schemas on the fly, injecting cryptographic hidden fields (like _ctx_hash_prop) into the JSON Schema required array. This mathematically forces the LLM to echo back the reversible cipher, enabling infinite horizontal scalability without any Redis dependency.
LLM-Shield-Proxy is validated against an exhaustive, continuously growing suite of 170+ automated unit, integration, and adversarial fuzzing tests.
Below is a high-level summary of our defense architecture. For the complete 18-vector Threat Matrix, detailed implementation specifications, and vulnerability coverage, view our Deep Dive Security & Threat Model Documentation.
LLM-Shield-Proxy is engineered specifically to help enterprises adopt Generative AI while supporting data privacy regulations like HIPAA and SOC 2 audit requirements. These are technical controls that map to specific framework requirements — deploying this proxy is one control among many a full compliance program requires, not a certification or a substitute for legal/compliance review.
Below is a summary of our compliance mappings. For the exhaustive deep-dive mapping, view our Enterprise Compliance Documentation.
If you are deploying LLM-Shield to satisfy a compliance audit, map the proxy's features directly to your Trust Services Criteria. See our complete Auditor Evidence Mapping.
| Compliance Domain | Supported Features & Capabilities |
|---|---|
| 🏥 HIPAA Transmission Security | Local O(1) Redaction, Tier-2 Shannon Entropy + canonical locale synthetic substituting. No raw PHI traverses public internet to third-party APIs. |
| 🛡️ SOC 2 Audit Controls | WORM-Compliant Cryptographic SHA-256 Hash Chaining. Emits tamper-evident structured logs with strict RFC 6902 differential patching. |
| ⚖️ Legal & Egress Provenance | Cryptographic Proof of Non-Egress Cryptographic Attestation. Dynamic Canary Watermarking for insider leak forensics. |
| 🔐 Data Integrity & Storage | Zero long-term storage. In-Band Stateless AES-256-GCM masking or ephemeral Redis TTL Vault mapping with Deterministic HMAC masking. |
Based on extreme stress testing, the Proxy scales highly efficiently across multi-core architectures. The proxy engine is fully asynchronous and achieves its highest throughput on Linux environments utilizing epoll.
<85 MB per worker, memory-optimized instances are completely unnecessary. Standard compute-optimized instances provide vastly more RAM than the proxy will ever consume.[!NOTE] Windows Deployment Note (
SO_REUSEPORT): While the proxy runs efficiently on Windows, scaling to extreme high-concurrency with multiple workers is constrained by the Windows TCP stack. Windows does not natively support theSO_REUSEPORTsocket option. Under massive load, this can result in less efficient connection routing across Uvicorn workers. For maximum enterprise production scale, Linux deployments are generally recommended. In rigorous load tests, a single Python core on Windows tops out around ~800 to 900 concurrent streaming users before encounteringaccept()backlog saturation (ConnectionRefusedError).
LLM-Shield-Proxy is engineered for sub-millisecond overhead and ultra-lightweight resource usage. Numbers from the automated benchmark suite (python benchmark.py):
=================================================================
LLM-Shield-Proxy Enterprise Latency & Proof Benchmark
=================================================================
1. ISOLATED SHANNON ENTROPY SECRET SCANNER (<6 µs Proof):
-----------------------------------------------------------------
• Mean Latency: 2.60 µs
• Median (p50): 2.60 µs
• 95th Percentile:2.70 µs
• 99th Percentile:3.30 µs
[VERIFIED] Shannon Entropy executes in <6 µs: True
2. MASSIVE PAYLOAD REDACTION (10,000 Words / 50 Adversarial Secrets):
-----------------------------------------------------------------
• Mean Latency: 25.96 ms
• Median (p50): 25.80 ms
• 95th Percentile:26.73 ms
• 99th Percentile:32.08 ms
3. RESIDENT MEMORY BASELINE:
-----------------------------------------------------------------
• Active RSS Footprint: 82.45 MB (<85 MB Target: True)
=================================================================
ALL AUDIT BENCHMARKS COMPLETED AND VERIFIED
=================================================================
| Metric | Average Latency | Median Latency | Footprint / Notes |
|---|---|---|---|
| Tier 1 Regex Overhead | 0.0379 ms | 0.0366 ms (36.60 µs) | Microsecond pattern scan |
| Tier 2 (Shannon Entropy) Overhead | 0.0026 ms | 0.0026 ms (2.60 µs) | Math-bound loop execution |
| Tier 3 (ONNX NER) Overhead | ~12.50 ms | ~11.80 ms | Inference on 50-token chunk (Optional NLP Mode) |
| Total SSE Stream Overhead | 0.0043 ms | 0.0042 ms (4.23 µs) | Added latency per SSE delta chunk |
| AES-256-GCM Encrypt + Decrypt | 0.0017 ms | 0.0017 ms (1.76 µs) | Authenticated vault cipher cycle |
| Process RAM Footprint | - | - | <85 MB Resident Set Size (82.45 MB verified) |
To achieve microsecond latencies, LLM-Shield-Proxy bypasses heavy legacy NLP frameworks in favor of aggressive low-level algorithmic optimizations:
Counter and math-bound loop, avoiding heavy regex backtracking. It executes in <6 µs.orjson, processing high-throughput LLM streaming chunks up to 10x faster than standard libraries.tool_calls is hard-capped at max_depth = 40, preventing adversarial stack-overflow latency attacks in <1ms.@lru_cache, guaranteeing 0ms latency impact during proxy routing.Engineered on an asynchronous, non-blocking event loop with HTTP/2 persistent connection pooling, LLM-Shield-Proxy scales effortlessly under high enterprise load:
<85 MB) under sustained multi-hour stress testing without garbage collection bloat.To run the automated benchmark and stress test suites locally:
# Automated latency & unit benchmarks
python benchmark.py
# Locust concurrent stream stress suite
locust -f load_test.py --headless -u 500 -r 50 --run-time 10m --host http://localhost:8000
Building a microsecond-latency reverse proxy requires low-level architectural optimizations:
data: delta chunks. LLM-Shield-Proxy implements a custom async generator buffer retaining prefix overlap (L = max_token_length - 1), guaranteeing 100% interception of fragmented packets without stream stalling.<85 MB footprint and starts instantly.orjson vs. Standard json: Standard json parsing introduces CPU overhead during high-concurrency streaming. orjson executes deserialization in native code without GIL contention, delivering up to 10x faster parsing on large payloads.<6 µs.Please be aware of the following current limitations:
ONNX_MODEL_PATH). By default, the proxy falls back to an English-optimized NLP model.Run the full automated test suite using pytest:
# Run all unit and integration tests
py -m pytest -v
# Run specific modules
py -m pytest tests/test_streaming.py -v
py -m pytest tests/test_pii_engine.py -v
py -m pytest tests/test_security_hardening.py -v
Designed for zero-friction adoption by DevOps, Site Reliability Engineers (SREs), and Network Administrators:
Built-in liveness, readiness, and metrics endpoints explicitly support enterprise orchestrators:
/healthz and /livez return an immediate HTTP 200 OK liveness probe. Requests to /readyz verify Redis connectivity and proxy health./metrics with optional Bearer token authentication.OPTIONS preflight requests, returning standard CORS headers and HTTP 204 No Content to unblock secure frontend applications without triggering auth failures.$ curl -X GET "http://localhost:8000/health"
# Output: {"status":"ok","service":"llm-shield-proxy","version":"1.3.4"}
$ curl -X GET "http://localhost:8000/readyz"
# Output: {"status":"ready","service":"llm-shield-proxy","version":"1.3.4","redis_connected":false}
curl -X OPTIONS http://localhost:8000/v1/chat/completions
# Returns 204 No Content with Access-Control-Allow-* headers
pydantic-settings)100% compliant with 12-factor app standards. All upstream target routing, keys, thresholds, and pool sizes are managed via validated pydantic-settings:
| Environment Variable | Type | Default | Description |
|---|---|---|---|
HOST | str | 0.0.0.0 | Socket host to bind |
PORT | int | 8000 | Socket port to bind |
UPSTREAM_BASE_URL | str | https://api.openai.com | Target upstream LLM provider base URL |
OPENAI_API_KEY | str | None | Centralized enterprise OpenAI API key |
REDIS_URL | str | None | Redis connection URL for distributed vault state |
TELEMETRY_ENABLED | bool | False | Enable OpenTelemetry tracing and audit logging to OTLP collector |
Note: For a full list of all configuration flags and advanced feature toggles, refer to the Deployment Guide.
LLM-Shield-Proxy runs completely stateless by default. For high-volume enterprise deployments, instances scale horizontally behind edge proxies (NGINX, Traefik, AWS ALB):
# Spin up 5 load-balanced instances of the proxy
docker compose up -d --scale llm-shield-proxy=5
When configured with REDIS_URL, session vaults are shared across all proxy replicas via redis.asyncio, ensuring seamless session isolation across multi-instance clusters.
Every published release includes automated SHA-256 checksums (checksums.txt) and GPG detached signatures (checksums.txt.asc) signed by maintainer Ninad Phalak. You can verify checksums and cryptographic authenticity before deployment using:
# 1. Verify SHA-256 Checksums (Linux / macOS):
sha256sum -c checksums.txt
# On Windows (PowerShell):
Get-FileHash llm-shield-proxy-source-v1.3.4.zip -Algorithm SHA256
# 2. Verify Cryptographic GPG Signature:
gpg --verify checksums.txt.asc checksums.txt
Abstracts configuration fatigue away from the global environment variables by mounting a policies.yaml file to dynamically map virtual_key_id client identities to distinct security roles. The engine supports zero-downtime hot-reloading updates for live, enterprise-grade RBAC without dropping active proxy streams.
I am committed to maintaining LLM-Shield-Proxy as the fastest ultra-low latency redaction engine for LLMs. I am actively looking for open-source contributors and collaborators to help execute the following technical roadmap. If you submit a PR, I will personally review and merge your architecture contributions:
streaming.py) into a C-extension binary to aggressively drive down tail latencies for high-throughput enterprise deployments.If you want to contribute to enterprise AI security, check out CONTRIBUTING.md and claim an issue (e.g., Help Cythonize the proxy! #15)!
If your organization is evaluating, benchmarking, or deploying LLM-Shield-Proxy to unblock LLM streaming and support compliance programs (like SOC 2/HIPAA), I encourage you to engage with the community:
LLM-Shield-Proxy is actively gathering feedback from CISOs, DevOps engineers, and Cybersecurity professionals to shape the open-source compliance roadmap.
LLM-Shield-Proxy is an original engineering work authored and maintained by Ninad Phalak.
If you reference this architecture, benchmark methodology, or sliding-window buffer implementation, please cite:
Phalak, N. (2026). Quantifying Latency and Token Overhead in Real-Time LLM Stream Sanitization: A Tiered Detection Approach (Version 1.0.0). Zenodo. https://doi.org/10.5281/zenodo.21955770
@misc{phalak2026quantifying,
author = {Phalak, Ninad},
title = {Quantifying Latency and Token Overhead in Real-Time LLM Stream Sanitization: A Tiered Detection Approach},
month = aug,
year = 2026,
publisher = {Zenodo},
doi = {10.5281/zenodo.21955770},
url = {https://doi.org/10.5281/zenodo.21955770}
}
334 commits
8 commits
Python
86.7%
TypeScript
8.4%
CSS
2.9%
A stateless, zero-latency reverse proxy for real-time PII redaction in LLM streams.
8
stars
342
commits
Python
primary language
Sep 6, 2026
updated
📖 Read the full docs and try the interactive PII-redaction playground → Type real-looking PII into your browser and watch it get redacted before it ever reaches an LLM, then rehydrated on the way back — no signup, no server calls, entirely client-side.
Ultra-Low Latency Generative AI Sanitization for Highly Regulated Enterprise Infrastructure
LLM-Shield-Proxy is a hyper-fast, FastAPI-based streaming gateway designed specifically for environments where data privacy is paramount (Banking, Healthcare, Legal). It intercepts and sanitizes real-time LLM streams to prevent the leakage of Non-Public Personal Information (NPI), Protected Health Information (PHI), and Payment Card Industry (PCI) data without degrading the end-user streaming experience.
By utilizing a highly optimized Tiered Detection Approach, LLM-Shield-Proxy applies guardrails at the microsecond level, helping your AI applications meet strict InfoSec mandates (GLBA, PCI-DSS, HIPAA) while maintaining zero-perceived-latency.
Option 2: Zero-Internet Air-Gapped Mode
* Egress Gateway can be any standard network proxy (e.g., Squid, Envoy, LLMLite, NGINX).
Technical controls supporting SOC 2 Type II and HIPAA safeguards for LLM streams, without breaking real-time latency.
LLM-Shield-Proxy is an open-source, zero-egress PII redaction and compliance AI Gateway and LLM Firewall deployed directly within your corporate VPC. It intercepts OpenAI-compatible LLM API requests, redacts Personally Identifiable Information (PII) and raw secrets before they leave your infrastructure, and deterministically re-hydrates real-time Server-Sent Events (SSE) chat responses with ultra-low stream latency.
Designed to enforce Zero Trust AI and support enterprise privacy compliance programs (SOC 2 trust criteria, HIPAA, HITRUST technical safeguards) without breaking real-time streaming latency.
LLM-Shield-Proxy intelligently routes traffic through two distinct redaction pipelines based on the payload structure. This ensures that autonomous agents don't crash from broken syntax trees, while human prompts get the highest quality contextual masking.
For standard conversational text, the proxy respects your configured masking mode. You can choose from four strategies:
John -> Maya). Preserves LLM attention weights and token counts. Requires Redis.[PERSON_1]). Requires Redis.***). Cannot be rehydrated.When the proxy detects structured AI tool calls or JSON-RPC 2.0 payloads, it bypasses your configuration and strictly enforces an AST-Aware Semantic Firewall with STATELESS_SYNTHETIC.
{"_shield_val": "Maya", "_shield_ctx": "aesgcm..."}). This guarantees 100% valid JSON syntax without relying on Redis state.<85 MB RAM).policies.yaml) dynamically maps virtual_key_id identities to granular security roles, custom PII profiles, and thread-safe $O(1)$ setting overrides.gen_ai.* spans directly to your GRC platform (Vanta/Drata) or SIEM (Datadog) to support SOC 2 audit evidence, ISO 42001 AI Management System forensics, and comprehensive LLM Security Posture Management (LLM SPM).GET /api/v1/audit/pubkey); llm-shield-proxy compliance-report --framework=hipaa bundles verified audit evidence, NIST OSCAL results, and a SHA-256 integrity manifest into a single auditor-ready .zip.exec_sql, shell_exec) mid-stream using a zero-allocation JSON parser, enforcing fail-closed tool access controls backed by Redis, OPA, or Vault policy stores to prevent agent drift.ext_proc for zero HTTP network hops, paired with a zero-dependency Kubernetes Mutating Webhook.google-re2) guarantee linear execution time against adversarial regex payloads.Because LLM-Shield-Proxy natively mimics the OpenAI specification, you do not need to rewrite your application code. You simply change the base_url in your SDK or the endpoint in your curl command. The proxy intercepts the payload, redacts it, and translates the schema to the correct upstream provider automatically.
Option A: cURL
# ❌ Before: Sending raw PHI directly to OpenAI
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer sk-openai-key" \
-d '{"messages": [{"role": "user", "content": "My SSN is 000-00-0000"}]}'
# ✅ After: Sending payload through LLM-Shield (Zero Egress)
curl http://localhost:8000/v1/chat/completions \
-H "Authorization: Bearer shield-virtual-key" \
-d '{"messages": [{"role": "user", "content": "My SSN is 000-00-0000"}]}'
Option B: Python SDK (1-Line Change)
from openai import OpenAI
client = OpenAI(
api_key="your-openai-api-key",
base_url="http://localhost:8000/v1", # Point to LLM-Shield-Proxy
)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Contact Sarah Connor at sarah@example.com or 555-0199."}],
stream=True,
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="", flush=True)
Spin up the zero-egress proxy in seconds.
Option A: Run the Live Streaming Demo (Docker Compose)
# 1. Spin up the proxy container in background
docker compose up -d
# 2. Verify health probe
curl http://localhost:8000/healthz
# 3. Run the live demo script
python examples/demo.py
Option B: Standalone Container (Production Base)
docker run -d -p 8000:8000 \
-e OPENAI_API_KEY="sk-your-openai-api-key" \
-e HOST="0.0.0.0" \
-e PORT=8000 \
--name llm-shield-proxy \
ghcr.io/ninadphalak/llm-shield-proxy:latest
For architectural diagrams showing VPC and Air-Gapped Egress gateway setups, please refer to the Deployment Topologies guide.
LLM-Shield-Proxy is heavily modular. You can configure the engine based on your specific compliance ROI and memory constraints:
| Installation Tier | Command | Capabilities Included | Use Case / Trade-off |
|---|---|---|---|
| Standard Mode (Microsecond Proxy) | pip install llm-shield-proxy | Tier 1 (Regex) & Tier 2 (Shannon Entropy) | Best for DevOps & Secrets: Operates with ultra-low memory (<85 MB RAM) and maximum throughput. Coverage: 100% deterministic catch rate for structured compliance data (SSNs, Emails, IP/MAC) and high-entropy cryptographic secrets (API Keys, Hex tokens). Misses conversational/free-text names. |
| Full NLP Mode (Contextual NER) | pip install "llm-shield-proxy[ner]" | Adds Tier 3 (ONNX Runtime NER) | Best for HIPAA/GDPR: Adds a quantized BERT-NER model via ONNX runtime to extract conversational PII (Patient Names, Organizations) from free-text. Coverage: >95% F1 Recall for contextual entities on standard benchmark datasets, matching the accuracy of enterprise cloud NLP APIs (AWS Comprehend, Google Cloud DLP, Microsoft Presidio) at 10x lower memory. Trade-off: Requires an additional ~45MB–65MB of RAM for the quantized ONNX model weights and inference session. |
Enabling Tier 3 ONNX NER: When installed with
[ner], enable deep neural entity extraction by settingENABLE_TIER3_ONNX_NER=truein your.envor environment variables (and optionally pointONNX_MODEL_PATHto custom model weights). If disabled or not installed, the engine automatically and gracefully bypasses Tier 3 with zero startup overhead.
LLM-Shield-Proxy is highly extensible without risking latency or ReDoS.
custom_regex.yaml. Mathematically guaranteed O(N) execution for ReDoS immunity.| Existing Legacy Proxies | LLM-Shield-Proxy |
|---|---|
| Destroys Real-Time SSE Streaming: Buffers entire responses before scanning, causing multi-second UI latency stalls. | Ultra-Low Latency Streaming: Redacts and re-hydrates delta-by-delta as SSE packets stream. |
| Heavy Memory Footprint: Requires 1GB–2GB RAM for heavy spaCy or PyTorch NLP libraries. | Ultra-Lightweight <85 MB RAM: Runs on a microsecond compiled regex + Shannon entropy + synthetic generator engine. |
| Data Liability: Stores user PII in long-term databases. | Zero Long-Term Storage (Zero-Data Mode): Self-destructing TTL session vault built for zero data liability. Operates in strict "Zero-Data Mode"—no prompts, PII, or context windows are ever written to persistent disk or external storage. |
| Complex Cloud Egress: Routes data to 3rd-party SaaS inspection APIs. | 100% Zero-Egress VPC: All scanning happens locally inside your secure corporate boundary. |
Designed specifically for highly regulated enterprise environments, strict Zero Trust AI network architectures, and security-first engineering teams implementing LLM Security Posture Management (LLM SPM).
It's a crowded space. Here is exactly why you should deploy LLM-Shield-Proxy instead of the alternatives:
LLM-Shield-Proxy is not a model router. It is designed to deploy as a transparent edge proxy directly in front of industry-standard orchestration tools. It stacks with your existing AI routing infrastructure, requires zero code changes, and is compatible out-of-the-box with:
Drop LLM-Shield-Proxy directly in front of them to guarantee deterministic data masking, mapped to SOC 2 control evidence, before the payload ever reaches the orchestrator.
localhost:8000.[PER... SON_1]) ensuring split tokens never leak.LLM-Shield-Proxy delivers enterprise privacy and zero-trust security through highly optimized architectural breakthroughs.
View the Complete Architecture Deep Dive 🏛️: For an exhaustive breakdown of the streaming lexer, memory mechanics, and service mesh integrations.
Rust-backed orjson engine parses fragmented Server-Sent Events with mathematical overlap bounding, enabling high-throughput without Python GIL saturation and capping memory at <85 MB.
google-re2)All identifiers and custom dictionaries are pre-compiled into Deterministic Finite Automatons (DFAs) in C++, guaranteeing linear execution time to physically immunize the proxy against Regex Denial of Service (ReDoS).
Vectorized O(N) math loop evaluating H(S) bit density to instantly intercept unstructured 64-char cryptographic keys in <6 µs.
Dynamically intercepts OpenAI/MCP tool schemas on the fly, injecting cryptographic hidden fields (like _ctx_hash_prop) into the JSON Schema required array. This mathematically forces the LLM to echo back the reversible cipher, enabling infinite horizontal scalability without any Redis dependency.
LLM-Shield-Proxy is validated against an exhaustive, continuously growing suite of 170+ automated unit, integration, and adversarial fuzzing tests.
Below is a high-level summary of our defense architecture. For the complete 18-vector Threat Matrix, detailed implementation specifications, and vulnerability coverage, view our Deep Dive Security & Threat Model Documentation.
LLM-Shield-Proxy is engineered specifically to help enterprises adopt Generative AI while supporting data privacy regulations like HIPAA and SOC 2 audit requirements. These are technical controls that map to specific framework requirements — deploying this proxy is one control among many a full compliance program requires, not a certification or a substitute for legal/compliance review.
Below is a summary of our compliance mappings. For the exhaustive deep-dive mapping, view our Enterprise Compliance Documentation.
If you are deploying LLM-Shield to satisfy a compliance audit, map the proxy's features directly to your Trust Services Criteria. See our complete Auditor Evidence Mapping.
| Compliance Domain | Supported Features & Capabilities |
|---|---|
| 🏥 HIPAA Transmission Security | Local O(1) Redaction, Tier-2 Shannon Entropy + canonical locale synthetic substituting. No raw PHI traverses public internet to third-party APIs. |
| 🛡️ SOC 2 Audit Controls | WORM-Compliant Cryptographic SHA-256 Hash Chaining. Emits tamper-evident structured logs with strict RFC 6902 differential patching. |
| ⚖️ Legal & Egress Provenance | Cryptographic Proof of Non-Egress Cryptographic Attestation. Dynamic Canary Watermarking for insider leak forensics. |
| 🔐 Data Integrity & Storage | Zero long-term storage. In-Band Stateless AES-256-GCM masking or ephemeral Redis TTL Vault mapping with Deterministic HMAC masking. |
Based on extreme stress testing, the Proxy scales highly efficiently across multi-core architectures. The proxy engine is fully asynchronous and achieves its highest throughput on Linux environments utilizing epoll.
<85 MB per worker, memory-optimized instances are completely unnecessary. Standard compute-optimized instances provide vastly more RAM than the proxy will ever consume.[!NOTE] Windows Deployment Note (
SO_REUSEPORT): While the proxy runs efficiently on Windows, scaling to extreme high-concurrency with multiple workers is constrained by the Windows TCP stack. Windows does not natively support theSO_REUSEPORTsocket option. Under massive load, this can result in less efficient connection routing across Uvicorn workers. For maximum enterprise production scale, Linux deployments are generally recommended. In rigorous load tests, a single Python core on Windows tops out around ~800 to 900 concurrent streaming users before encounteringaccept()backlog saturation (ConnectionRefusedError).
LLM-Shield-Proxy is engineered for sub-millisecond overhead and ultra-lightweight resource usage. Numbers from the automated benchmark suite (python benchmark.py):
=================================================================
LLM-Shield-Proxy Enterprise Latency & Proof Benchmark
=================================================================
1. ISOLATED SHANNON ENTROPY SECRET SCANNER (<6 µs Proof):
-----------------------------------------------------------------
• Mean Latency: 2.60 µs
• Median (p50): 2.60 µs
• 95th Percentile:2.70 µs
• 99th Percentile:3.30 µs
[VERIFIED] Shannon Entropy executes in <6 µs: True
2. MASSIVE PAYLOAD REDACTION (10,000 Words / 50 Adversarial Secrets):
-----------------------------------------------------------------
• Mean Latency: 25.96 ms
• Median (p50): 25.80 ms
• 95th Percentile:26.73 ms
• 99th Percentile:32.08 ms
3. RESIDENT MEMORY BASELINE:
-----------------------------------------------------------------
• Active RSS Footprint: 82.45 MB (<85 MB Target: True)
=================================================================
ALL AUDIT BENCHMARKS COMPLETED AND VERIFIED
=================================================================
| Metric | Average Latency | Median Latency | Footprint / Notes |
|---|---|---|---|
| Tier 1 Regex Overhead | 0.0379 ms | 0.0366 ms (36.60 µs) | Microsecond pattern scan |
| Tier 2 (Shannon Entropy) Overhead | 0.0026 ms | 0.0026 ms (2.60 µs) | Math-bound loop execution |
| Tier 3 (ONNX NER) Overhead | ~12.50 ms | ~11.80 ms | Inference on 50-token chunk (Optional NLP Mode) |
| Total SSE Stream Overhead | 0.0043 ms | 0.0042 ms (4.23 µs) | Added latency per SSE delta chunk |
| AES-256-GCM Encrypt + Decrypt | 0.0017 ms | 0.0017 ms (1.76 µs) | Authenticated vault cipher cycle |
| Process RAM Footprint | - | - | <85 MB Resident Set Size (82.45 MB verified) |
To achieve microsecond latencies, LLM-Shield-Proxy bypasses heavy legacy NLP frameworks in favor of aggressive low-level algorithmic optimizations:
Counter and math-bound loop, avoiding heavy regex backtracking. It executes in <6 µs.orjson, processing high-throughput LLM streaming chunks up to 10x faster than standard libraries.tool_calls is hard-capped at max_depth = 40, preventing adversarial stack-overflow latency attacks in <1ms.@lru_cache, guaranteeing 0ms latency impact during proxy routing.Engineered on an asynchronous, non-blocking event loop with HTTP/2 persistent connection pooling, LLM-Shield-Proxy scales effortlessly under high enterprise load:
<85 MB) under sustained multi-hour stress testing without garbage collection bloat.To run the automated benchmark and stress test suites locally:
# Automated latency & unit benchmarks
python benchmark.py
# Locust concurrent stream stress suite
locust -f load_test.py --headless -u 500 -r 50 --run-time 10m --host http://localhost:8000
Building a microsecond-latency reverse proxy requires low-level architectural optimizations:
data: delta chunks. LLM-Shield-Proxy implements a custom async generator buffer retaining prefix overlap (L = max_token_length - 1), guaranteeing 100% interception of fragmented packets without stream stalling.<85 MB footprint and starts instantly.orjson vs. Standard json: Standard json parsing introduces CPU overhead during high-concurrency streaming. orjson executes deserialization in native code without GIL contention, delivering up to 10x faster parsing on large payloads.<6 µs.Please be aware of the following current limitations:
ONNX_MODEL_PATH). By default, the proxy falls back to an English-optimized NLP model.Run the full automated test suite using pytest:
# Run all unit and integration tests
py -m pytest -v
# Run specific modules
py -m pytest tests/test_streaming.py -v
py -m pytest tests/test_pii_engine.py -v
py -m pytest tests/test_security_hardening.py -v
Designed for zero-friction adoption by DevOps, Site Reliability Engineers (SREs), and Network Administrators:
Built-in liveness, readiness, and metrics endpoints explicitly support enterprise orchestrators:
/healthz and /livez return an immediate HTTP 200 OK liveness probe. Requests to /readyz verify Redis connectivity and proxy health./metrics with optional Bearer token authentication.OPTIONS preflight requests, returning standard CORS headers and HTTP 204 No Content to unblock secure frontend applications without triggering auth failures.$ curl -X GET "http://localhost:8000/health"
# Output: {"status":"ok","service":"llm-shield-proxy","version":"1.3.4"}
$ curl -X GET "http://localhost:8000/readyz"
# Output: {"status":"ready","service":"llm-shield-proxy","version":"1.3.4","redis_connected":false}
curl -X OPTIONS http://localhost:8000/v1/chat/completions
# Returns 204 No Content with Access-Control-Allow-* headers
pydantic-settings)100% compliant with 12-factor app standards. All upstream target routing, keys, thresholds, and pool sizes are managed via validated pydantic-settings:
| Environment Variable | Type | Default | Description |
|---|---|---|---|
HOST | str | 0.0.0.0 | Socket host to bind |
PORT | int | 8000 | Socket port to bind |
UPSTREAM_BASE_URL | str | https://api.openai.com | Target upstream LLM provider base URL |
OPENAI_API_KEY | str | None | Centralized enterprise OpenAI API key |
REDIS_URL | str | None | Redis connection URL for distributed vault state |
TELEMETRY_ENABLED | bool | False | Enable OpenTelemetry tracing and audit logging to OTLP collector |
Note: For a full list of all configuration flags and advanced feature toggles, refer to the Deployment Guide.
LLM-Shield-Proxy runs completely stateless by default. For high-volume enterprise deployments, instances scale horizontally behind edge proxies (NGINX, Traefik, AWS ALB):
# Spin up 5 load-balanced instances of the proxy
docker compose up -d --scale llm-shield-proxy=5
When configured with REDIS_URL, session vaults are shared across all proxy replicas via redis.asyncio, ensuring seamless session isolation across multi-instance clusters.
Every published release includes automated SHA-256 checksums (checksums.txt) and GPG detached signatures (checksums.txt.asc) signed by maintainer Ninad Phalak. You can verify checksums and cryptographic authenticity before deployment using:
# 1. Verify SHA-256 Checksums (Linux / macOS):
sha256sum -c checksums.txt
# On Windows (PowerShell):
Get-FileHash llm-shield-proxy-source-v1.3.4.zip -Algorithm SHA256
# 2. Verify Cryptographic GPG Signature:
gpg --verify checksums.txt.asc checksums.txt
Abstracts configuration fatigue away from the global environment variables by mounting a policies.yaml file to dynamically map virtual_key_id client identities to distinct security roles. The engine supports zero-downtime hot-reloading updates for live, enterprise-grade RBAC without dropping active proxy streams.
I am committed to maintaining LLM-Shield-Proxy as the fastest ultra-low latency redaction engine for LLMs. I am actively looking for open-source contributors and collaborators to help execute the following technical roadmap. If you submit a PR, I will personally review and merge your architecture contributions:
streaming.py) into a C-extension binary to aggressively drive down tail latencies for high-throughput enterprise deployments.If you want to contribute to enterprise AI security, check out CONTRIBUTING.md and claim an issue (e.g., Help Cythonize the proxy! #15)!
If your organization is evaluating, benchmarking, or deploying LLM-Shield-Proxy to unblock LLM streaming and support compliance programs (like SOC 2/HIPAA), I encourage you to engage with the community:
LLM-Shield-Proxy is actively gathering feedback from CISOs, DevOps engineers, and Cybersecurity professionals to shape the open-source compliance roadmap.
LLM-Shield-Proxy is an original engineering work authored and maintained by Ninad Phalak.
If you reference this architecture, benchmark methodology, or sliding-window buffer implementation, please cite:
Phalak, N. (2026). Quantifying Latency and Token Overhead in Real-Time LLM Stream Sanitization: A Tiered Detection Approach (Version 1.0.0). Zenodo. https://doi.org/10.5281/zenodo.21955770
@misc{phalak2026quantifying,
author = {Phalak, Ninad},
title = {Quantifying Latency and Token Overhead in Real-Time LLM Stream Sanitization: A Tiered Detection Approach},
month = aug,
year = 2026,
publisher = {Zenodo},
doi = {10.5281/zenodo.21955770},
url = {https://doi.org/10.5281/zenodo.21955770}
}
334 commits
8 commits
Python
86.7%
TypeScript
8.4%
CSS
2.9%