2/10
Technical Architecture & AI Engineering · 7 min read

System Design: High-Throughput LLM Inference Gateway With Token Budgets and Failover

Design a 2,000-QPS multi-provider AI gateway with atomic streaming token reservations, ingress PII redaction, tiered model routing, and automatic circuit-breaker failover.

Why This Matters at Engineering Leadership Scale

When 15 product squads integrate OpenAI, Anthropic, or Bedrock directly, leadership quickly hits four failures: unattributed token bills, accidental customer PII sent to third-party endpoints, company-wide outages during upstream 429/500 spikes, and zero leverage to route simple tasks to cheaper models.

A central LLM Inference Gateway (X-as-a-Service) solves all four centrally. At L6/L7 scale, the real challenge is enforcing strict token budgets over streaming SSE responses, keeping gateway overhead <15ms at 2,000 QPS, and failing over across providers without violating regional data residency.

Core Mental Model & Architecture

Anchor the architecture in capacity and telemetry math first:

  • Workload & SLO: 20 internal products/tenants, 2,000 QPS peak (~670 avg, ~58M reqs/day), streaming SSE, 99.95% availability, <15ms added gateway overhead.
  • Token Throughput: At ~800 prompt + 300 completion = 1,100 tokens/req, peak throughput hits 2.2M tokens/sec (~64B tokens/day).
  • Telemetry & Cache Math: Usage logs (~500 bytes/req * 58M/day) generate 29 GB/day raw (~2.6 TB/year compressed in ClickHouse). Redis Cluster needs <50 MB for sliding-window quota buckets and ~20 GB for 1-hour exact-hash response caches.
ChoiceOption AOption B (Chosen)Rationale
Streaming Token BudgetCount after stream endsReserve prompt + max_tokens in Redis Lua; refund unused in finallyStops concurrent stream bursts blowing past TPM caps
Billing MeteringSync Postgres insertAsync Kafka -> ClickHouse (~5s lag)Keeps overhead <15ms and isolates analytics DB
Provider OutagesBackoff retry same vendorPer-provider circuit breaker (Bedrock -> Vertex -> OpenAI)Stops 429 retry storms; fails over in seconds
Squad AdoptionCustom gRPC SDKOpenAI-compatible HTTP/SDKProduct squads swap baseURL + key in 2 hours

Step-by-Step Implementation Tutorial

1. Separate Sync Enforcement From Async Metering

Keep auth, PII scrubbing, Redis quotas, caching, and failover <15ms; push billing asynchronously.

text
SYNC PLANE (<15ms overhead):
SDK -> Envoy/Kong -> Auth & Policy (L1 RAM) -> Ingress PII Scrubber (<5ms)
  -> Redis Lua Token Bucket (Atomic RPM + Pre-Reserve prompt + max_tokens TPM)
  -> Exact-Hash Cache (Redis 1h TTL) -> Policy Router (classify->small | synthesize->frontier)
  -> Circuit Breakers [Bedrock -> Vertex -> OpenAI] -> Stream SSE -> finally(): Refund unused + Emit event

ASYNC PLANE:
Gateway -> Kafka (llm-usage-events) -> ClickHouse (Cost/tenant dashboards)

2. Enforce Atomic RPM + TPM Pre-Reservation in Redis Lua

Never check TPM only after a stream finishes. Reserve upfront atomically and refund unused completion tokens when the stream closes.

lua
-- KEYS[1] = tenant:{id}:rpm, KEYS[2] = tenant:{id}:tpm
-- ARGV = { now_ms, rpm_cap, rpm_rate, tpm_cap, tpm_rate, reserve_tokens }
local now = tonumber(ARGV[1])
local function take(key, cap, rate, cost)
  local s = redis.call("HMGET", key, "t", "ts")
  local t = math.min(cap, (tonumber(s[1]) or cap) + math.max(0, now - (tonumber(s[2]) or now)) * rate)
  if t < cost then return 0 end
  redis.call("HMSET", key, "t", t - cost, "ts", now)
  redis.call("PEXPIRE", key, 120000)
  return 1
end

if take(KEYS[1], tonumber(ARGV[2]), tonumber(ARGV[3]), 1) == 0 then return {0, "RPM_LIMIT"} end
if take(KEYS[2], tonumber(ARGV[4]), tonumber(ARGV[5]), tonumber(ARGV[6])) == 0 then return {0, "TPM_LIMIT"} end
return {1, "OK"}

3. Handle the Minute-25 Curveball: Dropped SSE Streams & Accidental PII Leakage

"If clients drop mid-stream, how do you stop leaked TPM reservations, and how do you stop engineers sending customer PII to external models?"

  1. Stream Reservation Leaks: Wrap every SSE stream with a 30s idle timeout and a guaranteed finally hook that reads the provider's final usage frame (or counts emitted SSE tokens locally on client abort) and refunds (max_tokens - actual) into Redis capped at tpm_cap.
  2. Ingress PII Redaction: Run a deterministic <5ms redaction filter before cache lookup and upstream dispatch that masks emails, credit cards, JWTs, and AWS keys with reversible in-memory tokens ([EMAIL_1]), ensuring external provider logs stay 100% PII-free.

4. Split Multi-Squad Ownership

  • Platform AI Gateway Squad (6 engineers): Owns gateway runtime, Redis quota scripts, PII redaction, residency-aware failover, ClickHouse cost dashboards, and the OpenAI-compatible internal SDK.
  • Product Squads (15+ teams): Own prompt templates, task-tier hints (classify vs. synthesize), offline accuracy evals, and team budget caps via self-service policy PRs.

Worked Production Scenario: Before vs. After

A 15-squad SaaS org saw LLM spend climb from $14,000 to $68,000/month while a 45-minute primary provider outage broke AI features company-wide and an audit flagged raw customer emails in external logs. Launching a central LLM Gateway with small-model routing, exact-hash caching, PII redaction, and Bedrock -> Vertex failover transformed reliability and unit cost in 5 weeks.

MetricBefore (Direct SDKs)After (Central LLM Gateway)Net Impact
Upstream Provider Outage Impact45-min outage across 15 products1.8s failover to secondary provider99.97% availability
Monthly LLM Inference Spend$68,000 / month$26,500 / month-61% via routing + cache
Added Gateway Overhead (p95)N/A11.4msNegligible vs. 800ms LLM TTFT
External PII Audit Violations14 / quarter0 (redacted at ingress)Clean SOC 2 compliance
New Squad Integration Time1 to 2 weeks2 hours (baseURL swap)Self-service platform velocity

Common Failure Modes & Anti-Patterns

1. Failing Over Across Data-Residency Boundaries

The trap: Failing an Australian fintech tenant from Bedrock ap-southeast-2 over to OpenAI US-East during a 500 spike, breaching residency contracts. The structural fix: Bind every tenant policy to an explicit allowed_regional_endpoints[] list (for example, Bedrock ap-southeast-2 -> Vertex australia-southeast1).

2. Caching High-Temperature Prompts or Buffering Full Streams

The trap: Caching creative temperature > 0.2 responses or buffering full streams before sending the first byte (destroying perceived speed). The structural fix: Only cache when temperature <= 0.1, and tee live SSE chunks to the client immediately while populating Redis asynchronously on stream completion.

3. Writing Billing Rows Synchronously to Postgres

The trap: Inserting usage rows into Postgres on the hot path so database lock contention stalls all 2,000 QPS of AI inference. The structural fix: Emit usage envelopes asynchronously to Kafka/ClickHouse; never couple live inference availability to analytics databases.

How to Handle Pushback in the Room

Product Tech Lead: "A central gateway slows us down when we want to test a newly released model tomorrow."

Calm Executive Response: "The gateway adds under 12ms on top of an 800ms LLM call and gives you failover and PII redaction for free. To keep experimentation fast, we expose a sandbox pass-through route in staging so your squad can benchmark any new model on Day 1 before adding it to production policy."

VP of Finance: "If ClickHouse billing lags by 5 seconds, can a runaway bug burn $50,000 before we notice?"

Calm Executive Response: "No - enforcement does not wait for ClickHouse. Hard RPM and TPM token buckets execute synchronously in Redis Lua before every upstream call, plus an hourly dollar-equivalent token ceiling automatically returns HTTP 429 long before a loop can create a major spike."

Key Takeaways & This Week's Action Rep

  • Pre-reserve tokens for streaming SSE: Reserve prompt + max_tokens atomically in Redis Lua and refund unused tokens in finally.
  • Keep sync overhead <15ms: Enforce quotas, PII scrubbing, caching, and circuit breakers synchronously; stream billing asynchronously to ClickHouse.
  • Make failover residency-safe: Restrict fallback chains strictly to contractually approved regional endpoints.
  • Expose an OpenAI-compatible SDK: Make the compliant platform path a 2-hour drop-in swap for product squads.
  • This Week's Action Rep: Inventory every service calling LLM APIs directly today and draft a 1-page LLM Gateway RFC covering your Redis Lua quota schema, residency-safe fallback chain, and first pilot squad.