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
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)andminting serviceissue internal API keys (UUID + signed/hashed policy) so callers never hold raw OpenAI or Anthropic credentials. - Vault locked by mTLS + SPIFFE/SPIRE: Only
minting serviceandLLM gatewaycan read raw upstream provider keys from Vault. - In-memory key cache:
LLM gatewaycaches 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:
policieswritesUser PoliciesandOrg Policyto Postgres and write-through caches them in Redis. - Push + 5s poll fallback:
policiespushes instant updates toLLM gatewayRAM; 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 gatewaychecksapikey:tokenusedin Redis; after response completion (or the final SSE[DONE]chunk), it emits aresponse eventto Kafka sotoken updaterrunsINCRBYin 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_tokenspre-flight in Redis and reconcile actual usage post-flight.
4. Multi-provider routing, retries & SSE streaming
- Jittered retries for blips: Brief
429/5xxspikes 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 eventsflow asynchronously into ClickHousequerieswith 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?
Select an option to check the trade-off.
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.
Select an option to check the trade-off.
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?
Select an option to check the trade-off.
SPOFreliability
Single Point of Failure: any component whose failure stops the whole system because there is no independent fallback.
circuit breakerresilience
A state machine (closed, open, half-open) that trips to fail fast when a downstream dependency is failing, avoiding cascading stalls.