Case Study — AI Infrastructure

The Secure Bridge Between AI and Production

A JWT-authenticated FastAPI gateway that eliminated API key exposure across every frontend service — with circuit breaking, encrypted Redis sessions, and full Prometheus observability baked in from day one.

<50ms
Auth overhead
AES-256
Session encryption
5-fail
Circuit threshold
0
Keys in frontend
Role Lead Engineer
Stack Python / FastAPI / Redis / Docker
Context Internal AI Platform
Outcome Zero frontend key exposure
01 — The Problem

Direct Frontend-to-AI Calls Are a Security Liability

An AI automation agency running multiple client-facing products faced a structural problem: every dashboard, form, and internal tool was making direct API calls to AI providers and data backends. That meant AI provider keys lived in browser-accessible environment variables, and any compromised session meant a compromised key.

Worse, there was no centralized observability. When an AI call failed, the error vanished into the browser console. There was no circuit breaking — a single flapping AI provider endpoint could cascade into a full product outage. And because sessions were stateless, conversational AI features required the client to re-send full conversation history on every request.

The agency needed a single, hardened entry point that all internal services could trust — something that enforced authentication before a single byte reached any backend, encrypted every session at rest, and gave engineering a real-time view of what was happening across every AI call.

02 — Architecture

One Gateway. Every Service Routes Through It.

The bridge sits between every frontend client and every backend service. No direct connections. No exceptions.

CLIENTS Dashboard Forms Mobile App Internal Tool AG BRIDGE FastAPI + Uvicorn RS256 JWT Validation Circuit Breaker Prometheus Metrics structlog JSON Redis AES-256-GCM sessions BACKENDS Gemini 2.5 Flash AI provider NocoDB data backend Prometheus metrics sink Keycloak RS256 public key
01
Inbound
JWT Validate
RS256 · Keycloak JWKS
02
Gate
Circuit Check
5 failures = open
03
Session
Redis Lookup
AES-256-GCM decrypt
04
Dispatch
Backend Route
Gemini / NocoDB / etc.
03 — Engineering Decisions

Three Hard Choices That Defined the Design

Every security primitive has a cost. Here is the reasoning behind the three decisions that shaped the gateway's security posture.

Decision 01

RS256 over HS256 JWT

HS256 uses a shared secret — any service that verifies tokens can also forge them. RS256 uses asymmetric keys: Keycloak signs with its private key, the bridge validates with the public key fetched from Keycloak's JWKS endpoint. No service except Keycloak can ever produce a valid token.

Verdict: RS256 — asymmetric trust boundary enforced.
Decision 02

Circuit Breaker Pattern

AI providers flap. When Gemini returns 5xx, a naive retry loop hammers the provider and burns tokens. The circuit breaker pattern opens after a configurable failure threshold — returning 503 immediately to clients while the backend recovers, then entering half-open state to probe recovery before fully closing.

Verdict: Threshold at 5 failures, 60s recovery window.
Decision 03

AES-256-GCM Session Encryption

Redis stores conversation history per session. If Redis is compromised, plain-text sessions expose full conversation history. AES-256-GCM provides both confidentiality (encryption) and integrity (authentication tag) — any tampering is detected on decrypt. Each session gets a unique IV, preventing nonce reuse.

Verdict: AES-256-GCM, unique IV per session write.
Security Layers
1

JWT Validation Before Any Route Handler Executes

A FastAPI dependency on every router validates the Bearer token against Keycloak's RS256 public key. Expired, malformed, or missing tokens return 401 before touching any business logic. The public key is fetched once on startup and cached — JWKS rotation forces a restart, which is intentional.

2

No API Keys in Frontend Code — Ever

Every backend credential (AI provider keys, database tokens, webhook secrets) lives exclusively in the bridge's Coolify environment. Frontend services send only their JWT and request payload. The bridge resolves credentials server-side for every call. Zero secrets cross the network boundary to the browser.

3

Stateful Conversation Without Client-Side History

Gemini's conversational mode requires history. Naive implementations re-send full history on every request — increasing payload size quadratically and exposing history to network interception. The bridge stores encrypted history in Redis keyed to the session ID. Clients send only the latest message; the bridge rehydrates context server-side.

4

Structured JSON Logging on Every Request

structlog emits structured JSON on every request: method, path, user sub, latency, upstream status, circuit state. This feeds directly into observability dashboards without a log parsing step. Every AI failure produces a traceable structured event with correlation IDs, not a free-text stack dump.

5

Prometheus Metrics on Every Route

Each route exposes request count, error rate, and latency histograms as Prometheus metrics. The circuit breaker state is also exported as a gauge. This means a Grafana dashboard can alert on elevated error rates or a tripped circuit before users file a support ticket.

"Security isn't a feature you add at the end — it's the foundation you build the rest on top of."
Python 3.12 FastAPI Uvicorn / Gunicorn Gemini 2.5 Flash Redis AES-256-GCM python-jose RS256 structlog Prometheus Docker Keycloak 26 Traefik Coolify
04 — Proof

What It Delivered

Every metric here is a direct consequence of an architectural decision — not a coincidence.

<50ms
Auth overhead
AES-256
Session encryption
5
Failure threshold
0
Frontend key exposure

Cascade Failures Contained

The circuit breaker means a flapping AI provider endpoint returns 503 immediately after the threshold — rather than hammering the upstream and burning API quota during an outage. Recovery is automatic via half-open probe.

Stateful Chat Without History Payload Growth

Conversation history grows per message. Sending full history client-side grows payload quadratically. Server-side Redis session storage keeps every client request flat — one message, one response — regardless of conversation depth.

Prometheus Alerting From Day One

Every route emits latency histograms and error counters. Grafana alerts fire on elevated p95 latency or circuit open state — before users report degraded behavior. Engineering knows before the ticket is filed.

Single Point of Credential Rotation

Rotating an AI provider key, a database token, or a webhook secret requires updating one Coolify environment variable and redeploying one service. No frontend redeploy. No rebuild. No downtime for credential hygiene.

Want Infrastructure Built Like This?

I design and ship production-grade AI infrastructure — secure, observable, and built to last.

Let's Work Together
LIVE ENDPOINT

Health Check — Live

AG Bridge runs 24/7 as an internal gateway. The /health endpoint surfaces real-time status of Redis and Gemini circuit breaker.

GET /health

→ {
  "redis": "ok",
  "gemini_circuit": "closed",
  "uptime": "live"
}