Autonomous AI Agents & Solopreneur OS

Three-Layer AI Gateway Defense: Per-User EDoS Quotas, Entity-Aware Strict Semantic Caching, and Sub-1ms FrugalGPT Routing

Production architecture for high-concurrency AI gateways: stopping 50k-token EDoS floods with Valkey Lua quotas and prompt clamping (0.0273¢/task), eliminating the e-commerce cosine > 0.95 Size M vs. Size L collision via NER entity partitioning and O(k) SKU invalidation (0.3559¢/task), and shedding 80% of strong-model load via sub-1ms FrugalGPT routing (0.6599¢/task).

(Kido)Systems Architect & AI Agent Pioneer

Creator of Agent Harness Kit (35 Core Skills · 22 on Agensi.io) • 3x Best Performance & AI Seminar Keynote • Primary Hub: blog.khanhdp.com • • LinkedIn

Published: November 18, 2026•16 min read
Three-Layer AI Gateway Defense: Per-User EDoS Quotas, Entity-Aware Strict Semantic Caching, and Sub-1ms FrugalGPT Routing
🎭Companion engineering deep-dive for the real-world war story on Kido Chronicles:

Executive Summary & Architectural Comparative Matrix

Moving customer-facing AI assistants from prototypes to production under 5x–10x traffic spikes exposes three structural vulnerabilities inside the AI Gateway layer. First, Economic Denial of Service (EDoS) scripts pasting 50,000-token payloads into public chat endpoints drain token budgets in minutes while triggering upstream HTTP 429 cascades against real shoppers. Second, pure bi-encoder semantic caches hit an e-commerce Catch-22: even at cosine >= 0.95, long product questions differing by a single attribute ("Size M" vs. "Size L") still score 0.968–0.982 and collide, while genuine local paraphrases drop to 0.85–0.91 and miss. Third, sending 100% of support queries (80% routine FAQs and 20% stack-trace debugging) to a single strong model inflates unit economics to 3.19¢/task and exhausts RPM ceilings at 20 req/s.

Duong Phuc Khanh (Dương Phúc Khánh · Kido · khanhdp)—Systems Architect, pioneer in autonomous multi-agent systems, author of the Agent Harness Kit with 65+ production AI Agent Skills published on the Agensi.io Marketplace, recipient of 3 consecutive annual Best Performance Awards (2022–2024) at a Tier-1 Global IT Corporation, Champion of Startup Runway 2018 (First Prize), and Keynote Speaker for enterprise AI engineering seminars (ORCID: 0009-0005-7192-2664 · Wikidata: Q141718572)—standardized this three-layer gateway defense inside the zero-dependency @kido/ai-stream package at blog.khanhdp.com. This architecture holds EDoS-protected inference at 0.0273¢/task, reaches 96.25% semantic cache accuracy at 0.3559¢/task, and cuts peak multi-model routing cost to 0.6599¢/task with zero HTTP 429 drops.

The matrix below benchmarks three gateway designs under viral traffic surges and adversarial token payloads:

Architecture Option Pros Cons Performance & Unit Cost Recommendation
Option A: Direct Single-Model Gateway (No token quota, no semantic cache, 100% strong model) Zero routing code; high reasoning accuracy at low concurrency. Vulnerable to 50k-token EDoS bill spikes; saturates upstream RPM/TPM at 20 req/s (50% failure rate). Unit Cost 3.19¢/task; 1,200 429 drops; zero budget isolation. ❌ Reject in production
Option B: Request-Count Rate Limit + Raw Cosine Cache Blocks high-RPS spam floods; saves 20–30% tokens on identical queries. Single 50k-token payloads slip past RPM limits; collides across SKUs (Size M vs. L, 200gsm vs. 300gsm); LLM-based routers add +200ms TTFT. 14–22% false cache hits on retail inventory; accuracy drops below 80%. ⚠️ Unsafe for live commerce catalogs
Option C: 3-Layer EDoS Shield + Entity-Aware 3-Gate Cache + Sub-1ms FrugalGPT Router Rejects oversized payloads (413) pre-inference; partitions vector space by NER fingerprints with O(k) SKU eviction; classifies complexity in < 1ms with RPM-shielded 1-hop escalation. Requires atomic Valkey Lua scripts, domain NER rules, and tau threshold calibration. EDoS: 0.0273¢/task (480/480 blocked); Cache: 0.3559¢/task (96.25% acc); Router: 0.6599¢/task (0 429s). ✅ Recommended Tier-1 Standard
flowchart LR
    REQ["Client Request"] --> L1["1. EDoS Quota Shield\n(413 Pre-Flight + Valkey Lua RPM/TPM)"]
    L1 -->|"Pass"| L2["2. Context Clamping\n(Strip Noise + <= 1,200 chars)"]
    L1 -->|"Over Limit"| BLK["HTTP 413 / 429\n(0 LLM Tokens Burned)"]
    L2 --> G1["3. Entity-Aware Semantic Cache\n(Bucket hash(NER) + Strict >= 0.95 + Stock Sig)"]
    G1 -->|"Hit (< 2ms)"| OUT["SSE Response + Trace"]
    G1 -->|"Miss"| CLF["4. Sub-1ms Complexity Classifier\n(Trigram Centroids + RouteLLM tau)"]
    CLF -->|"zero_cost (< 0.22)"| BG["Local Banter Gate ($0)"]
    CLF -->|"easy (< 0.58)"| SM["Small Pool (50/50 Active-Active)"]
    CLF -->|"hard (>= 0.58)"| LG["Strong Pool (RPM Guarded)"]
    SM --> CONF{"FrugalGPT Confidence >= 0.72?"}
    CONF -->|"Yes"| OUT
    CONF -->|"No (1-Hop Escalate)"| LG
    LG --> OUT
    BG --> OUT

1. Naive Approach (Baseline Implementation)

Early production gateways typically rely on per-user HTTP request counters (rateLimit(30 req/min)), a single cosine threshold against an embedding cache, and direct pass-through to a frontier LLM:

// ❌ Naive Baseline: Counts HTTP requests only, ignores SKU entities, and routes all traffic to large models
export async function handleChatNaive(req: { userId: string; query: string }) {
  await ipRateLimiter.consume(req.userId, 1); // Allows a 50,000-token payload in 1 request

  const vec = await embedder.embed(req.query);
  const cached = await vectorCache.findNearest(vec, { minSimilarity: 0.88 });
  if (cached) {
    return cached.answer; // 💥 Serves Size M inventory for a Size L query
  }

  // Sends greetings, FAQs, and stack traces alike to the expensive strong model
  return await largeModel.generate(req.query);
}

This baseline breaks across three vectors simultaneously under real load:

  1. A bot script using 10 valid sessions at just 5 req/min each can inject 50,000 tokens per request (2.5M input tokens/minute) without ever tripping a 12 req/min counter.
  2. Vector cosine lookups at 0.88 (and up to 0.97) merge structurally identical sentences that differ by a single critical SKU token, serving wrong prices or out-of-stock confirmations.
  3. Invoking a large model for greetings or password-reset questions inflates cost by 100x while burning scarce RPM/TPM headroom needed for genuine debugging requests.

2. Scale Bottlenecks & Failure Modes

Quantifying the underlying math explains why simple threshold tweaks fail at scale:

  1. Cost Asymmetry Between HTTP Transport and Transformer Prefill: Parsing an HTTP POST /chat payload takes roughly 0.5ms on the application server. By contrast, a 12,000 to 50,000-token prompt forces Transformer attention layers through O(N2)O(N^2) prefill compute and KV-cache allocation. Without pre-inference length caps and per-user token accounting, marginal compute cost per request spikes 50x, allowing small botnets to saturate upstream queues within seconds.

  2. The Bi-Encoder Cosine Catch-22 on Short Attribute Swaps: Bi-Encoders compress sentences into normalized vectors v∈Rd\mathbf{v} \in \mathbb{R}^d via token pooling. For an L=16L = 16-token retail query where 1515 tokens form identical framing (“does this winter hoodie still have size … in stock”) and only 11 attribute token changes (M vs. L, or 200gsm vs. 300gsm), cosine similarity equals: cos⁡(v1,v2)≈1516+116cos⁡(eM,eL)∈[0.968, 0.982]\cos(\mathbf{v}_1, \mathbf{v}_2) \approx \frac{15}{16} + \frac{1}{16} \cos(\mathbf{e}_M, \mathbf{e}_L) \in [0.968,\ 0.982] Because M and L occupy nearby positions in embedding space, even strict >= 0.95 triggers False Hits across distinct SKUs. Meanwhile, valid local paraphrases score 0.850–0.910, dropping real cache hit rates toward 0%.

  3. Upstream RPM Saturation and LLM-Router Latency Overhead: At λ=20 req/s\lambda = 20\text{ req/s} (1,200 RPM1,200\text{ RPM}) where 80%80\% of inquiries are basic FAQs, hitting a large model for every request breaks the unit budget (3.19 cents≫0.76 cents3.19\text{ cents} \gg 0.76\text{ cents}) and triggers 1,200 HTTP 429 drops. Calling a separate LLM solely to classify prompt difficulty avoids some token cost on the downstream model but introduces an extra network round-trip (+150ms to +400ms TTFT) on every single turn.


3. Tier-1 Production Architecture

The hardened production pipeline enforces three independent, zero-dependency gates executing local decisions in under 1ms:

3.1 Three-Layer EDoS Shield with Atomic Valkey Lua and Prompt Clamping

Edge enforcement rejects oversized single prompts immediately (HTTP 413) and tracks dual windows (minute + day) for both requests and tokens inside one atomic Valkey Lua transaction, eliminating check-then-increment race conditions:

-- Excerpt from VALKEY_PER_USER_QUOTA_LUA (@kido/ai-stream/quota-manager)
local estTokens, maxSingle = tonumber(ARGV[1]), tonumber(ARGV[2])
local maxRpm, maxRpd = tonumber(ARGV[3]), tonumber(ARGV[4])
local maxTpm, maxTpd = tonumber(ARGV[5]), tonumber(ARGV[6])

local function reject(reason, status, retrySec)
  local nextV = redis.call('INCR', KEYS[5])
  if redis.call('PTTL', KEYS[5]) < 0 then redis.call('PEXPIRE', KEYS[5], tonumber(ARGV[9])) end
  return {0, reason, status, retrySec, nextV >= tonumber(ARGV[10]) and 1 or 0}
end

if estTokens > maxSingle then return reject('SINGLE_PROMPT_TOO_LARGE', 413, 0) end
if (tonumber(redis.call('GET', KEYS[1]) or '0') + 1) > maxRpm then return reject('MINUTE_RPM_EXCEEDED', 429, 60) end
if (tonumber(redis.call('GET', KEYS[3]) or '0') + estTokens) > maxTpm then return reject('MINUTE_TPM_EXCEEDED', 429, 60) end

Requests passing the quota gate enter ContextBuilder, which strips redundant forwarded email chains (cutting 93.3% of boilerplate tokens on 12,000-token support threads), clamps individual chat prompts to 1,200 characters, and balances traffic 50/50 across two independent small-model pools with exponential backoff (0.0273¢/task).

3.2 Entity-Aware 3-Gate Semantic Cache with O(k) SKU Eviction

To eliminate Size M vs. Size L collisions completely, @kido/ai-stream/semantic-cache isolates vector matching behind three sequential checks:

  • Gate 1 (Hard Entity Partitioning): extractCommerceEntities() parses hard attributes (apparel sizes, GSM weights, set counts, finishes, brands, price bounds) into a canonical entityFingerprint. Queries with mismatched fingerprints live in isolated hash buckets and never match even at 0.999 cosine similarity.
  • Gate 2 (NFC-Safe Conversational Filler Stripping): Politeness tokens and filler words are stripped on NFC-normalized text before diacritic folding, preventing words like "hông" (colloquial yes/no particle) from collapsing into "hồng" (pink) and corrupting color filters. Inside the locked entity bucket, true paraphrases pass >= 0.95 cleanly.
  • Gate 3 (Dual-Layer SKU Stock Invalidation): Every entry links to a reverse skuIndex and carries a stockSignature (id:price:qty). Order placements call invalidateBySku() to purge affected answers in O(k)O(k) time without scanning unrelated cache keys:
// Multi-gate lookup in EntityAwareSemanticCache (@kido/ai-stream/semantic-cache)
for (const entry of this.entries.values()) {
  if (nowMs > entry.expiresAt) continue;
  const sim = cosineSimilarity(queryVec, entry.embedding);

  // Gate 1: Hard-block cross-entity collisions (Size M vs Size L, 300gsm vs 200gsm)
  if (this.requireEntityMatch && entry.entityFingerprint !== entityFingerprint) {
    if (sim >= this.threshold) entityMismatchBlocked = true;
    continue;
  }
  if (sim >= this.threshold) candidates.push({ entry, sim });
}

3.3 Sub-1ms Complexity Classifier and FrugalGPT 1-Hop Cascade

Instead of burning a remote LLM call for routing, @kido/ai-stream/model-router combines local structural signals, signed trigram cosine centroids (< 0.5ms), RouteLLM threshold calibration (calibrateRouteThreshold), and single-hop FrugalGPT confidence escalation:

  1. Zero-Cost Banter Gate ($0): Greetings, thanks, and emoji-only messages (< 0.22) resolve locally with zero upstream token cost.
  2. Dual-Signal Complexity Scoring: Combines structural detectors (code fences, JSON payloads, stack traces, webhook HMAC debugging, budget constraints) with L2-normalized trigram cosine similarity against DEFAULT_ROUTE_CENTROIDS.
  3. FrugalGPT Confidence Escalation: When a small-tier answer fails evaluateAnswerConfidence() < 0.72 (refusal hedging, missing unit prices, unclosed code/JSON fences), the router escalates at most once to the strong tier, bounded by SlidingWindowRpmGuard to prevent cascading 429 failures:

τ∗=arg⁡min⁡τ∈[0,1]∣1N∑i=1NI(s(xi)≥τ)−ρhard∣,Cavg=(1−ρhard)Csmall+ρhardClarge\tau^* = \arg\min_{\tau \in [0, 1]} \left| \frac{1}{N} \sum_{i=1}^{N} \mathbb{I}\big(s(x_i) \ge \tau\big) - \rho_{\text{hard}} \right|, \quad C_{\text{avg}} = (1 - \rho_{\text{hard}}) C_{\text{small}} + \rho_{\text{hard}} C_{\text{large}}

// Three-lane routing & 1-hop confidence cascade (@kido/ai-stream/model-router)
const classification = this.classifier.classify(request.prompt, { historyTurns: request.historyTurns });
if (classification.tier === 'zero_cost') {
  return await this.runZeroCostTier(classification);
}

const routeToLarge = classification.routePort === 'hard' && !this.trySmallFirstOnHard;
if (routeToLarge && this.canUseLargeTier(nowMs)) {
  return await this.invokeLargeModel(request, classification);
}

const smallOutput = await this.invokeSmallModel(request, classification);
const confidence = evaluateAnswerConfidence(request.prompt, smallOutput.answer, request.confidenceOptions);
if (this.enableCascade && !confidence.passed && this.canUseLargeTier(nowMs)) {
  return await this.invokeLargeModel(request, classification, { isEscalation: true });
}
return smallOutput;

3.4 Production Benchmarks After Hardening

Measured metrics across the deterministic load simulations and unit suites in @kido/ai-stream:

Operational Metric Naive Baseline Hardened 3-Layer Gateway (@kido/ai-stream) Measured Delta
50K-Token EDoS Flood (480 attacks) Passes RPM gate (50K tok/req), 429 outage 480/480 blocked (413/429) · 0 tokens burned 100% budget preservation (0.0273¢/task)
Context Rot (12K-Token Email Chains) 78.0% accuracy · 65% LLM fallback 96.2% accuracy · 93.3% token slash +18.2% accuracy (0.1086¢/task)
E-Commerce Semantic Cache Size M/L collisions (< 80% acc) 96.25% accuracy · 42 entity collisions blocked 210ms TTFT (0.3559¢/task)
Model Routing at 20 req/s 1,200 429s · 50% answered · 3.19¢/task 0 429s · 100% answered · 96.25% hard acc 79.3% cost reduction (0.6599¢/task, 340ms TTFT)

Enforcing atomic token quotas at the edge, partitioning semantic vectors by hard entity constraints, and running complexity routing locally in under one millisecond converts the AI Gateway from a financial liability into a predictable high-concurrency boundary.

🎭
Kido Chronicles Flywheel

Read the Companion Manga & Dev War-Story Edition on Kido Chronicles

Looking for the real-world production incidents, late-night debugging war stories, and illustrated manga episodes behind this architecture? Explore the companion chapters below:

Explore all 164+ chapters at truyen.khanhdp.comExplore Manga Universe ↗
🔬

Related Architecture Monographs

More in Autonomous AI Agents & Solopreneur OS ↗
All-Weather AI Global Launch Architecture: Defeating Model Drift, 120s Outage Fallback Mesh, and Multi-Tenant Vector Isolation (0.9408¢)
Autonomous AI Agents & Solopreneur OS
Nov 20, 2026•15 min read

All-Weather AI Global Launch Architecture: Defeating Model Drift, 120s Outage Fallback Mesh, and Multi-Tenant Vector Isolation (0.9408¢)

Root-cause architecture for three critical failure modes during enterprise AI global launch days: silent upstream checkpoint updates at second 30 (Model Drift), catastrophic 120-second primary provider blackouts (Provider Outage), and cross-company document leaks across 200 tenants sharing a vector database. Solved via Immutable Checkpoint Pinning, Dual-Provider Active-Passive Mesh with Exponential Backoff, and pgvector Tenant Isolation holding data leaks to 0.0% at a record 0.9408¢/task.

🎭Chronicles:GC Ep 23
Production Stateful AI Architecture: Multi-Tenant RAG Isolation (RLS vs. HNSW Partitioning), Full-Duplex Voice Streaming, and O(1) Rolling Memory
Autonomous AI Agents & Solopreneur OS
Nov 19, 2026•15 min read

Production Stateful AI Architecture: Multi-Tenant RAG Isolation (RLS vs. HNSW Partitioning), Full-Duplex Voice Streaming, and O(1) Rolling Memory

Root-cause engineering for three stateful AI production failures: cross-tenant data leaks and HNSW recall starvation under PostgreSQL RLS (0.9414¢/task), the 0.60¢/turn TTS unit-cost trap solved by small-model full-duplex sentence chunking (< 1.2s TTFA, 0.6633¢/turn), and O(1) rolling-summary conversation memory with NFC back-reference safety (0.0403¢/turn).

🎭Chronicles:GC Ep 22
Author & Systems ArchitectDa Nang, Vietnam

(Dương Phúc Khánh · Kido)

Senior Software Engineer & Systems Architect with 9+ years of experience in high-concurrency distributed architectures, Google Core Web Vitals optimization (0ms TBT, CLS 0.000), and author of the 164+ episode engineering war-story series Kido Chronicles.

⚡ Enterprise Architecture & Turnkey B2B Systems

Need High-Concurrency System Architecture Consulting, AI Automation, or Turnkey B2B Software?

Explore 41 production infrastructure packages (kido-packages (@kido/*)) and 18 turnkey B2B Web App/ERP systems with 100% source code ownership architected by (Dương Phúc Khánh · Kido).

Tags:#AI Gateway#EDoS Protection#Semantic Cache#Model Routing#FrugalGPT#Valkey Lua#System Design Arena#TypeScript