skip to content
jaeaeichsysdes

Design an Enterprise LLM Gateway (Portkey)

Sub-20ms OpenAI-compatible proxy at 5K RPS with 30–60s SSE streams: in-memory Vault/policy caches, token-aware Redis budgets, per-provider circuit-breaker fallbacks, and decoupled ClickHouse cost analytics.

The whiteboard

Trace the 4 flows below to see how auth/secrets, non-blocking SSE proxying, token budgets, and cost analytics stay isolated. Builds on Rate Limiting, Load Balancing & Circuit Breakers, and Queues vs Event Logs.

whiteboard · press 1–5 to trace flows

Control Plane: Auth, Secrets & PoliciesHot Data Plane (<20ms Overhead · 5K RPS · 30–60s SSE)Decoupled Telemetry & Cost AnalyticsTTL cachepush policySSErouteCB opencheck tokenusedemit eventusage streamINCRBYIDP / MintingKeycloak + UUIDscoped API keysVault (mTLS)SPIFFE / SPIREprovider keysPolicy PGuser + orgbudgetsPolicy Svcwrite-throughpush updatesRedis Clusterapikey:tokenusedpolicy 5s fallbackCallerPOST /v1/chatsync / SSELLM Gatewayin-mem keys · CB · retrynon-blocking SSEPrimary LLMAnthropic / OpenAIFallback LLMBedrock / Azure (CB)Kafkaresponse eventspost-[DONE]ClickHousequeries + MVshourly costAnalytics APIread-throughcost / TTFTToken Updaterasync INCRBYTPM / budget

Full gateway: in-mem Vault/policy caches · non-blocking SSE proxy with CB fallback · async Kafka token & ClickHouse cost pipeline5K RPS · <20ms overhead · zero analytics coupling

Scale & APIs

5K RPS

peak traffic · 30–60s SSE streams

< 20 ms

p99 gateway proxy overhead

0 coupling

analytics outages never block LLM calls

Proxy: POST /v1/chat/completions (sync JSON or stream: true SSE)
Headers: Authorization: Bearer <internal_scoped_key>
Redis Keys: apikey:tokenused (TPM / budget counter)
Analytics: ClickHouse queries(id, userId, cost, input_tok, output_tok, trace_id, ttft)

How it works

1. Auth, key minting & centralized secrets

  • Scoped internal keys: IDP (Keycloak) and minting service issue internal API keys (UUID + signed/hashed policy) so callers never hold raw OpenAI or Anthropic credentials.
  • Vault locked by mTLS + SPIFFE/SPIRE: Only minting service and LLM gateway can read raw upstream provider keys from Vault.
  • In-memory key cache: LLM gateway caches provider and public verification keys in RAM (refreshed on lease TTL) so Vault is never a SPOF or latency hit at 5,000 RPS.

2. Low-latency policy validation

  • Write-through control plane: policies writes User Policies and Org Policy to Postgres and write-through caches them in Redis.
  • Push + 5s poll fallback: policies pushes instant updates to LLM gateway RAM; a 5-second background poll against Redis heals any missed push without touching Postgres.

3. Token-aware rate limiting & budgets

  • Why tokens, not RPS: One prompt can burn 100K tokens while another burns 50 — raw RPS limiting cannot protect upstream TPM quotas or tenant spend.
  • Pre-flight check + async update: Before forwarding, LLM gateway checks apikey:tokenused in Redis; after response completion (or the final SSE [DONE] chunk), it emits a response event to Kafka so token updater runs INCRBY in Redis.
  • Soft cap vs. hard cap: Async Kafka updates keep the hot path fast with slight concurrency overshoot; for strict hard caps, reserve estimated max_tokens pre-flight in Redis and reconcile actual usage post-flight.

4. Multi-provider routing, retries & SSE streaming

  • Jittered retries for blips: Brief 429/5xx spikes trigger exponential backoff with jitter before failing over.
  • Per-provider circuit breaker: Sustained provider errors or quota exhaustion trip the breaker open and route immediately to the policy’s fallback (e.g., Anthropic Direct → AWS Bedrock Claude → OpenAI).
  • Non-blocking SSE: The gateway streams chunks directly to the caller over non-blocking I/O (150K–300K concurrent 30–60s connections) without buffering full completions, and optionally runs lightweight local regex/NER PII redaction before prompts leave the VPC.

5. Decoupled observability & cost analytics

  • Kafka → ClickHouse: response events flow asynchronously into ClickHouse queries with hourly per-user materialized views for sub-second cost, token, and TTFT dashboards (served via Redis read-through).
  • Zero hot-path impact: If ClickHouse or the analytics API goes down, Kafka buffers events and live LLM traffic continues unaffected.

lesson

Interview pacing: Keep Auth/PKI/SPIFFE/Vault to one box during your 10–15 minute MVP so you leave time for token-aware rate limiting, SSE connection concurrency, and circuit-breaker failover. Only unpack mTLS and key minting if the interviewer digs into security.

Check yourself

interactive · stress-test this LLM gateway against classic infra & AI platform probes

01 · Soft cap vs. hard cap on concurrent token budgets

5K RPS · async Kafka INCRBY · concurrent burst

A tenant has 5,000 tokens left in their monthly budget and fires 20 parallel 4,000-token requests at the exact same millisecond. With async Kafka updates to Redis, what happens — and how do you enforce a strict hard cap?

02 · Why cache Vault secrets in gateway RAM instead of fetching per request?

5,000 RPS · <20ms p99 · zero SPOF

Security asks why the LLM gateway caches upstream OpenAI/Anthropic keys in memory instead of calling Vault over mTLS on every /v1/chat/completions request.

03 · Why does standard RPS rate limiting break down for LLM gateways?

100K-token context · upstream TPM limits · cost control

Your API gateway already enforces 100 RPS per tenant. Why must the LLM gateway still add token-aware (TPM) rate limiting in Redis?

esc
⌘B sidebar[ ] prev/next1–5 flowsc copyt theme