Charlie Roffe

Principal Architect & Engineering Director · Cloud & AI

Madrid, Spain · LinkedIn · GitHub

Defense-in-Depth for Public, Anonymous GenAI Endpoints on a $0 Standby Budget

Cloud FinOps · 9 min

GCP Billing Budgets only email you after the money is spent. Here is the 7-layer defense-in-depth architecture that keeps 9 public Gemini endpoints safe from denial-of-wallet attacks.

Exposing 9 live Google Gemini endpoints on a public portfolio site with no login wall creates an obvious threat: Denial of Wallet. A single script or distributed botnet can burn through thousands of dollars of LLM tokens before a GCP Billing Budget alert email even lands in your inbox (billing export alerts lag by hours and do not stop traffic).

To keep this site open to every visitor while bounding worst-case daily spend to a few euros (ADR-019, ADR-029, ADR-033), I layered seven independent controls from the network edge down to the model call.

Layer 1: Strict Request Body Caps Before JSON Parsing (`server.ts`)

Token cost scales with input length. Express mounts a tight 10kb JSON body limit on /api/* routes (with explicit 500kb and 2mb overrides only on the two upload routes that require them), and non-API routes skip body parsing entirely so scanner POSTs are dropped at zero memory cost.

Layer 2: IETF Draft-7 Per-IP Rate Limiting

Per-client express-rate-limit windows run in memory first (cheapest check) and cap each IP to 30 AI requests per 15 minutes while emitting standard RateLimit and RateLimit-Policy headers.

Layer 3: Firebase App Check Attestation (`server/appCheck.ts`)

Every /api/ai/* route verifies an X-Firebase-AppCheck token minted by reCAPTCHA v3 before touching the daily AI budget or model. Crucially, the middleware is placed before the daily AI budget counter so unattested bot traffic is rejected with 401 without depleting the legitimate daily quota for human visitors.

Layer 4: Site-Wide Daily Firestore Budget with Automatic Refunds (`server/aiBudget.ts`)

Per-IP limits stop a single abuser; they do not stop a distributed botnet across 500 IPs. Every POST /api/ai/* request (except /api/ai/copilot/resume, which applies approved graph diffs deterministically in TypeScript with zero model calls) runs an atomic Firestore transaction against ai_usage/<YYYY-MM-DD> (default cap: 300 model calls/day):

const ref = db.collection(AI_USAGE_COLLECTION).doc(day);
return await db.runTransaction(async (tx) => {
  const snap = await tx.get(ref);
  const used = Number(snap.exists ? snap.get('count') : 0) || 0;
  if (used >= cap) return false;
  tx.set(ref, {
    count: used + 1,
    expiresAt: new Date(now.getTime() + USAGE_RETENTION_DAYS * 86_400_000),
  }, { merge: true });
  return true;
});

What if a request fails Zod validation (400), hits a disabled feature flag (403), is blocked by the Red Team pre-model regex filter, or is served from my L1/L2 cache? No model call was made! My response wrapper automatically refunds the daily counter so invalid or cached requests never deplete the day's quota. When the cap is reached, the server returns 429 with a precise Retry-After header pointing to UTC midnight.

Layer 5: Coalesced Two-Tier L1/L2 Result & Embedding Cache (`server/cache.ts`)

Every single-call demo features a "Try a sample" button in the UI, which means a large fraction of visitors send identical inputs. withCache() checks an in-memory LRU map (L1, microseconds), coalesces concurrent in-flight requests for the same SHA-256 key so a traffic spike triggers only one Gemini call, and persists results to Firestore (L2, 30-day TTL) so cache hits survive Cloud Run scale-to-zero cycles.

Layer 6: Self-Healing Model Allowlist & Fixed EU Endpoints (`ADR-013`, `ADR-029`)

Clients can request a specific model (gemini-3.8-flash or gemini-3.5-flash-lite), and resolveDemoModel() validates it against the shared server-side allowlist in src/data/models.ts (falling back to the default model on unknown IDs). Generative calls are pinned to Vertex AI's eu multi-region endpoint (VERTEX_GEN_LOCATION = 'eu') and embeddings to Madrid (VERTEX_EMBED_LOCATION = 'europe-southwest1'), so a caller can never smuggle an expensive frontier model ID or force egress outside the EU.

Layer 7: Stream Deadlines and Client-Disconnect Cancellation (`server/ai.ts`)

Streaming routes (/api/ai/qa, /api/ai/cert-chat, /api/ai/contact) wrap generateContentStream in createStreamDeadline(): the first token must arrive within 25 seconds, the full stream within 60 seconds, and if the browser tab disconnects mid-stream (res.on('close')), the AbortController aborts the upstream Vertex AI generation immediately so I stop paying for tokens nobody is reading.

Back to all articles