Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Dynamic Multi-Model LLM Gateway
& Smart Router (50K RPS).

Design a 50K RPS multi-region LLM Gateway that unifies 10+ model providers, enforces per-tenant TPM/RPM quotas, cuts inference spend by 60%+ via smart routing, and guarantees <15ms gateway overhead.
Start the journey7 stages· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When batching and tail latency compete for accelerator cycles, keep the hot path in-memory/async (ONNX complexity router, Redis Lua TPM/RPM, EWMA health table) and offload FinOps metering and shadow evals to Kafka.

TL;DR30-second simplified summary
▾

To hit <15ms p99 overhead at 50K RPS, the gateway runs in Rust/Go with in-memory SHA-256 auth, KMS-backed BYOK secrets, and a single pipelined Redis call for atomic Lua RPM/TPM buckets and tenant-filtered HNSW semantic caching.

An embedded 384-dim ONNX classifier routes 70% of routine prompts to Tier-1 models, while probabilistic EWMA health scoring prevents herding oscillations across commercial and self-hosted vLLM upstreams.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Dynamic Multi-Model LLM Gateway & Smart Routing
A Dynamic Multi-Model LLM Gateway unifies heterogeneous model providers behind one OpenAI-compatible API, routing each prompt by semantic complexity, cost budget, and real-time EWMA provider health.
Full walkthrough · 7 stages
01
foundation

Scale Requirements & Sub-15ms Overhead Budget.

Why this matters: Establish throughput, latency overhead, and multi-cloud availability targets.

Think of Scale Requirements & Sub-15ms Overhead Budget as the intuition layer for Design a Dynamic Multi-Model LLM Gateway & Smart Router (50K RPS): Establish throughput, latency overhead, and multi-cloud availability targets.

At 50K RPS (avg 1,500 tokens/req = 75M tokens/min), the gateway itself must add <15ms p99 overhead before upstream dispatch. That rules out synchronous database lookups or remote Python microservices on the hot path: auth keys, routing rules, and provider health must live in-process (refreshed via async pub/sub) with at most 1 pipelined Redis round-trip (<3ms).

Stage 1 - Latency Budget

50K RPS Sub-15ms Hot Path

50K RPS IngresssourceIn-Memory Policycache1x Pipelined RedisprocessorEmbedded ONNXsinkCheck quota & cache

1.Zero Sync DB: Never query Postgres on the request path; push config updates via Redis Pub/Sub.

2.Memory Budget: Budget <15ms total gateway overhead across auth, rate limit, cache, and routing.

In-memory config and single-round-trip Redis keep gateway overhead under 15ms at 50K RPS.

02
foundation

Multi-Tenant Auth, Secret Vault & Token-Bucket Quotas.

Why this matters: Isolate tenant API keys, upstream provider credentials, and TPM/RPM fairness.

Tenants authenticate with gateway-issued bearer keys hashed (SHA-256) in an in-memory LRU backed by PostgreSQL.

Upstream provider keys (BYOK or platform-managed) are fetched from KMS/Vault and cached encrypted in memory.

Stage 2 - Auth & Quotas

Tenant Key & TPM/RPM Enforcement

Tenant Bearer KeysourceKMS / Secret CachecacheRedis Lua TPM/RPMrouter429 + Jitter HeadersinkCheck RPM & est. TPM

1.BYOK Isolation: Bring-Your-Own-Key tenants never share upstream rate-limit pools with other tenants.

2.Jittered Backoff: Add random jitter to Retry-After headers to prevent synchronized client retries.

In-memory SHA-256 auth and Redis Lua dual buckets protect upstream quotas at 50K RPS.

Engineering Decision Framework
Problem
How to implement Design a Dynamic Multi-Model LLM Gateway & Smart Router (50K RPS) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When batching and tail latency compete for accelerator cycles, keep the hot path in-memory/async (ONNX complexity router, Redis Lua TPM/RPM, EWMA health table) and offload FinOps metering and shadow evals to Kafka.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Dynamic Multi-Model LLM Gateway & Smart Router (50K RPS) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

Tenant-Scoped Semantic Cache (Redis Vector).

Why this matters: Cut redundant inference calls for repetitive enterprise prompts without cross-tenant leaks.

Think of Tenant-Scoped Semantic Cache (Redis Vector) as the intuition layer for Design a Dynamic Multi-Model LLM Gateway & Smart Router (50K RPS): Cut redundant inference calls for repetitive enterprise prompts without cross-tenant leaks.

For cacheable endpoints (x-cache-policy: semantic and temperature <= 0.2), the gateway embeds the prompt using a quantized 384-dim ONNX model (~4ms) and runs an HNSW nearest-neighbor query in Redis Vector filtered by tenant_id and system_prompt_hash. Hits (>=0.96 cosine) replay the stored SSE token sequence immediately.

Stage 3 - Vector Cache

Tenant-Filtered Redis Vector Cache

Cache Eligibilityrouter384-dim ONNX EmbedprocessorRedis HNSW IndexcacheSSE Chunk ReplayersinkTop-1 cosine >= 0.96

1.PII Scrubbing: Skip semantic caching automatically if regex/NER detects email, SSN, or bearer tokens.

2.Cache Warming: Pre-warm common system FAQ prompts during tenant onboarding.

Tenant-filtered HNSW caching eliminates duplicate inference for repetitive enterprise queries.

04
intermediate

Health-Aware Smart Router & EWMA Provider Scoring.

Why this matters: Continuously rank upstream providers by real-time TTFT, error rate, and cost.

Think of Health-Aware Smart Router & EWMA Provider Scoring as the intuition layer for Design a Dynamic Multi-Model LLM Gateway & Smart Router (50K RPS): Continuously rank upstream providers by real-time TTFT, error rate, and cost.

Each gateway pod maintains a lock-free EWMA table updated every 100ms from local response outcomes and shared across pods via lightweight Redis/gRPC gossip every 1s. The router scores candidate models matching the prompt's complexity tier using Score = w_cost * Cost + w_lat * EWMA_TTFT + w_err * ErrorPenalty, dynamically shifting traffic away from brownout regions.

Stage 4 - Dynamic Scoring

EWMA Multi-Objective Model Router

Complexity TiersourceEWMA Health TablecachePolicy WeightEnginerouterUpstream PoolsinkInject live health

1.No Oscillations: Use softmax/weighted probabilistic routing among top-2 healthy providers to avoid herding.

2.Self-Hosted Burst: Route overflow batch traffic to internal H100 vLLM pools when cloud APIs throttle.

Multi-objective EWMA scoring balances unit cost against live provider latency and error rates.

05
intermediate

Unified SSE Adapter & Hedged Speculative Retry.

Why this matters: Normalize streaming schemas and clip p99 pre-token stalls across providers.

Think of Unified SSE Adapter & Hedged Speculative Retry as the intuition layer for Design a Dynamic Multi-Model LLM Gateway & Smart Router (50K RPS): Normalize streaming schemas and clip p99 pre-token stalls across providers.

A streaming state machine translates provider-specific SSE events (Anthropic content_block_delta, Vertex JSON chunks, OpenAI choices[0].delta) into a canonical SSE stream. If token 1 has not arrived within 1.2s (and hedge budget <5%), the adapter opens a speculative secondary stream and aborts the slower upstream the instant token 1 arrives.

Stage 5 - Hedged Streaming

Unified SSE & Speculative Fallback

Primary StreamprocessorHedged BackupprocessorFirst-Token ArbiterrouterCanonical SSE OutsinkRace backup stream

1.Stream Safety: Close losing upstream HTTP connections immediately to avoid paying for full generation.

2.Partial Error Handling: If an upstream fails mid-stream, emit a typed SSE error event with retry guidance.

First-token arbitration and unified SSE adapters hide multi-vendor heterogeneity and p99 stalls.

06
advanced

Multi-Region Active-Active & Self-Hosted vLLM Overflow.

Why this matters: Survive entire cloud-region outages and absorb bursty batch workloads.

Gateway clusters run active-active across US-East, US-West, and EU-Central behind Geo-DNS.

EU-pinned tenants enforce data_residency: EU in policy rules so prompts never cross regional boundaries.

Stage 6 - Multi-Region Failover

Geo-Residency & vLLM Overflow

Geo-DNS RouterrouterData Residency GateprocessorCommercial LLM APIscacheSelf-Hosted H100PoolsinkRoute interactive

1.Residency Compliance: Hard-fail with 403/503 rather than violating EU data residency during outages.

2.Warm Standby: Keep 15% headroom on self-hosted vLLM pools for instant 429 absorption.

Data-residency enforcement and self-hosted vLLM overflow combine compliance with elasticity.

07
advanced

Async FinOps Ledger, Spend Caps & Shadow Quality Eval.

Why this matters: Provide real-time tenant chargeback, automated budget caps, and continuous quality auditing.

Every finished request publishes an idempotent UsageLedgerEvent to Kafka.

Apache Flink aggregates per-tenant spend in 1-minute windows into ClickHouse and updates Redis budget flags (triggering soft-downgrade to Tier-1 at 90% budget and hard-block at 100%).

Stage 7 - FinOps & Quality

Kafka-Flink Cost & Shadow Eval

UsageLedgerEventsourceFlink 1m WindowprocessorRedis Budget Flagcache1% Shadow JudgesinkUpdate gateway flags

1.Soft-Downgrade UX: Switching to Tier-1 at 90% budget avoids sudden production outages.

2.Exact Pricing Table: Version model pricing by timestamp in Flink for accurate historical billing.

Streaming FinOps aggregation and shadow judging close the loop on cost and quality.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

To keep gateway overhead under 15ms p99 at 50K RPS, how should tenant API keys, routing policies, and provider health scores be accessed on the hot path?

Recommended Learning Flow