Design an Enterprise AI Gateway for Heterogeneous Models
System DesignModel answerLast updated
Design a high-throughput, multi-tenant AI proxy layer featuring unified OpenAI-compatible routing, token-aware rate limiting, low latency overhead, and PII masking.
Scenario
Modern enterprises utilize a mixture of commercial foundation models (such as OpenAI, Anthropic, or AWS Bedrock) alongside self-hosted open-source deployments (such as vLLM or TGI on Kubernetes). Exposing these diverse downstream providers directly to internal product teams creates strong coupling, makes budget control difficult, increases risk during provider outages, and makes security auditing challenging.
You are tasked with designing an enterprise-grade AI Gateway that functions as an intelligent proxy layer positioned between consumer applications and model execution backends.
Requirements
Functional Requirements
- Unified Interface: Expose a standardized OpenAI-compatible REST and SSE API (
/v1/chat/completions,/v1/embeddings) across all underlying backends. - Dynamic Routing & Resiliency: Support configuration-driven routing (by latency, unit price, or policy) with automated fallbacks (e.g., fallback to Claude 3.5 Sonnet if GPT-4o encounters a 429 rate limit or 5xx server error).
- Multi-Tenant Rate Limiting: Enforce API key authentication along with dual-dimension throttling: Requests Per Minute (RPM) and Tokens Per Minute (TPM) per client/team.
- Cost & Usage Telemetry: Accurately track input tokens, output tokens, cached tokens, and calculated monetary cost per tenant with minimal ingestion delay.
- Data Protection (PII Scrubbing): Sanitize sensitive or personally identifiable information (PII) from prompts prior to sending requests to external public providers.
Non-Functional Requirements
- Low Overhead: Added latency overhead introduced by the proxy must remain strictly under 15ms at the P99 level (excluding the model's actual inference time).
- High Availability: Maintain 99.99% overall service availability.
- Throughput & Concurrency: Support a peak load of 10,000 requests per second (RPS), where approximately 70% of active streams utilize Server-Sent Events (SSE).
What to Cover
- System Architecture & Data Flow: Diagram and detail the core data plane and control plane services.
- Streaming Protocol & Memory Management: Explain how incremental SSE chunk proxying works while maintaining token telemetry without buffering full responses in memory.
- Dual-Dimension Quota Strategy (RPM & TPM): Detail the data structures and algorithms used to manage dynamic token reservations across distributed nodes.
- Resiliency & Fallback Mechanics: Cover circuit breaker state management and how mid-stream connection breaks or upstream failures are mitigated.
- Data Storage & Schema Design: Outline schemas for tenant authentication, model pricing snapshots, and analytics aggregation pipelines.
Hints
Hint 1
Calculate concurrent open connections rather than focusing solely on RPS, as SSE streams are long-lived.
Hint 2
Token usage (TPM) is unknown when a request arrives; consider a 'reserve-then-reconcile' mechanism during request admission.
Hint 3
Decouple the synchronous hot data path from analytical usage logging by placing telemetry dispatch onto an asynchronous message bus.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. System Scale and Latency Budget
Capacity Analysis
- Traffic Profile: 10,000 RPS peak. 70% (7,000 RPS) are streaming requests using Server-Sent Events (SSE), and 30% (3,000 RPS) are standard unary RPCs/REST calls.
- Concurrent Connections:
- Average SSE stream duration: ~10 seconds.
- Average non-streaming call duration: ~3 seconds.
- Using Little’s Law ($L = \lambda W$): $$\text{Concurrent SSE Connections} = 7,000 \times 10 = 70,000$$ $$\text{Concurrent Unary Connections} = 3,000 \times 3 = 9,000$$ $$\text{Total Active Connections} \approx 80,000\text{ connections}$$
- Proxy Node Sizing: An asynchronous, non-blocking I/O proxy engine (e.g., written in Rust/Go or built on Envoy/Nginx core) handles roughly 10,000 active concurrent connections per 8 vCPU node.
- Baseline requirement: 8 to 10 instances.
- Multi-region deployment with $N+2$ redundant capacity across 3 Availability Zones (AZs) requires a fleet size of roughly 24–30 instances per active region.
Data Plane Overhead Budget (P99 $\le 15\text{ ms}$)
| Pipeline Stage | P99 Budget | Strategy |
|---|---|---|
| Ingress Parsing & TLS | 2.0 ms | HTTP/2 keep-alives, connection pooling |
| Auth & Policy Retrieval | 0.5 ms | In-memory local LRU cache (pushed from control plane) |
| Rate Limit Validation | 2.0 ms | Local token buckets + asynchronous Redis sync |
| PII Inspection / Scrubbing | 5.0 ms | Optimized regex patterns & lightweight local trie/NER |
| Dynamic Model Routing | 0.5 ms | In-memory routing table lookup |
| Upstream Connection Sockets | 1.0 ms | Warm connection pools to upstream endpoints |
| Total Overhead Target | 11.0 ms | Leaves ~4 ms safety margin under the 15 ms limit |
All asynchronous tasks—such as full token audit logging, analytics aggregation, and non-blocking security logging—must be offloaded to background threads or Kafka queues.
2. System Architecture & Request Lifecycle
The architecture explicitly separates the high-performance Data Plane (which proxies user requests) from the Control Plane (which manages configurations, tenant keys, and routing policies).
+--------------------------+
| Client Applications |
+------------+-------------+
|
(HTTPS/SSE)
v
+--------------------------+
| Global Load Balancer |
+------------+-------------+
|
v
+-----------------------------------------------------------------------------------+
| Data Plane (Stateless Edge Fleet) |
| |
| +--------------------+ +--------------------+ +-------------------------+ |
| | Ingress & Auth | -> | Dual Rate Limiter | -> | PII Sanitizer | |
| | (Local Memory Cache| | (RPM + TPM Reserve)| | (Regex/Fast-Trie Engine)| |
| +--------------------+ +--------------------+ +------------+------------+ |
| | |
| +--------------------+ +--------------------+ v |
| | SSE Pipe Handler | <- | Upstream Adapter | <- +-------------------------+ |
| | (Zero-Buffer SSE) | | (Warm Socket Pool) | | Dynamic Router | |
| +---------+----------+ +--------------------+ | (Circuit Breaker Check) | |
| | +-------------------------+ |
+------------|----------------------------------------------------------------------+
| ^
(Async Stream Telemetry) | (Config Push / Watch)
v |
+--------------------------+ +--------------------------+
| Kafka Telemetry Topics | | Control Plane Services |
+------------+-------------+ | (PostgreSQL + Admin API) |
| +--------------------------+
v |
+--------------------------+ v
| ClickHouse OLAP Engine | +--------------------------+
+--------------------------+ | Distributed Cache / Redis|
+--------------------------+
End-to-End Request Journey
- Ingress & Authentication: Client opens a connection. The node validates the
Authorization: Bearer <token>against a local thread-safe LRU cache populated by control plane updates. - Quota Check: The node checks local and distributed token buckets in Redis for Requests Per Minute (RPM) and Tokens Per Minute (TPM).
- Security Pipeline: The request payload is scanned for PII (e.g., SSNs, credit cards, emails) via compiled pattern matchers and scrubbed in place before transmission.
- Dynamic Routing: The router selects an operational downstream backend from an in-memory topology tree, filtering out backends marked as degraded by the local circuit breaker.
- Upstream Request Execution: The request is converted into the backend provider's schema and dispatched over a warm HTTP/2 socket.
- Streaming & Event Metering: The response is streamed back directly to the client while counting tokens on the fly.
- Telemetry Dispatch: On stream completion, request metrics (usage, cost, latency profiles) are published asynchronously to Kafka for processing into ClickHouse.
3. Streaming Engine & Backpressure
Standard proxy architectures buffer complete downstream HTTP response bodies before forwarding. For LLM responses, this destroys Time-to-First-Token (TTFT), increases latency, and causes memory spikes.
Upstream Provider ---> [Gateway Reader] ---> (Transform Delta) ---> [Gateway Writer] ---> Client Client
| |
+---> (Token Counter / Metric State) -------+
Technical Implementation
// Simplified conceptual implementation of the streaming proxy pipeline
func ProxySSEStream(w http.ResponseWriter, upstreamBody io.ReadCloser, metrics *StreamMetrics) {
defer upstreamBody.Close()
// Set headers to disable downstream proxy buffering
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("X-Accel-Buffering", "no") // Prevents Nginx downstream buffering
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
reader := bufio.NewReader(upstreamBody)
firstTokenCaptured := false
startTime := time.Now()
for {
line, err := reader.ReadBytes('\n')
if len(line) > 0 {
// Process SSE data frame without buffering full payload
if bytes.HasPrefix(line, []byte("data: ")) {
data := line[6:]
if !bytes.Equal(bytes.TrimSpace(data), []byte("[DONE]")) {
// Update running token counter incrementally
metrics.OutputTokens += ExtractOrEstimateTokens(data)
if !firstTokenCaptured {
metrics.TTFT = time.Since(startTime)
firstTokenCaptured = true
}
}
}
// Stream chunk immediately to client
w.Write(line)
flusher.Flush() // Flush socket buffer instantly
}
if err != nil {
if err == io.EOF {
metrics.Status = "COMPLETED"
} else {
metrics.Status = "DISCONNECTED"
}
break
}
}
}
Key Considerations
- Memory Overhead: Memory usage stays constant ($O(\text{chunk size})$) rather than scaling with response length ($O(\text{response size})$).
- Backpressure Handling: Reads from the upstream socket are tied to client write availability. If a client socket stalls, the TCP window closes, causing the proxy reader to pause. This triggers TCP backpressure back to the upstream LLM host, pausing token generation.
- Token Accounting: If the provider sends usage data in the final stream payload (e.g., OpenAI
stream_options.include_usage), the gateway uses that count. Otherwise, an incremental BPE tokenizer counts tokens as stream chunks pass through. - Early Abort Handling: If a client closes their connection early, the gateway catches the closed socket event, cancels the upstream HTTP context to halt generation costs immediately, and logs the partial token count.
4. Quota & Rate Limiting (RPM and TPM)
Rate-limiting LLM APIs requires managing two distinct metrics: Requests Per Minute (RPM) and Tokens Per Minute (TPM).
- RPM is deterministic and validated before execution.
- TPM depends on the total tokens generated, which is unknown when the request starts.
The Reserve-Then-Reconcile Algorithm
[ Incoming Request ]
|
v
+----------------------------------+
| Compute Input Tokens (Prompt BPE)|
| Estimate Max Output Tokens |
+----------------+-----------------+
|
v
+----------------------------------+
| Reserve Estimated TPM in Redis |
| (Input + Reserved Max Output) |
+----------------+-----------------+
|
+--------------+--------------+
| |
[Quota Exceeded] [Quota Granted]
| |
v v
(Return 429 Too Many Requests) (Execute Request & Stream Response)
|
v
+----------------------------------+
| Calculate Actual Total Tokens |
+----------------+-----------------+
|
v
+----------------------------------+
| Reconcile Difference in Redis |
| Refund = Reserved - Actual |
+----------------------------------+
Redis Quota Management (Atomic Lua Scripting)
To execute reservations across distributed instances without race conditions, quota checks use atomic Lua scripts in Redis Cluster, sharded by tenant_id:
-- KEYS[1]: Tenant RPM Key, KEYS[2]: Tenant TPM Key
-- ARGV[1]: Current Timestamp, ARGV[2]: Max RPM, ARGV[3]: Max TPM, ARGV[4]: Reserved Tokens
local current_rpm = redis.call("INCR", KEYS[1])
if current_rpm == 1 then
redis.call("EXPIRE", KEYS[1], 60)
end
if tonumber(current_rpm) > tonumber(ARGV[2]) then
return {0, "RPM_EXCEEDED"}
end
local current_tpm = redis.call("GET", KEYS[2]) or 0
if (tonumber(current_tpm) + tonumber(ARGV[4])) > tonumber(ARGV[3]) then
-- Rollback temporary RPM increment
redis.call("DECR", KEYS[1])
return {0, "TPM_EXCEEDED"}
end
-- Reserve the estimated tokens
redis.call("INCRBY", KEYS[2], ARGV[4])
if current_tpm == 0 then
redis.call("EXPIRE", KEYS[2], 60)
end
return {1, "ALLOWED"}
Redis Failure Strategy
If the Redis cluster becomes unavailable, proxy nodes switch to a local sliding-window fallback mode. Each node allows a fraction of the global quota ($\text{Quota}{\text{node}} = \frac{\text{Quota}{\text{global}}}{\text{Node Count}}$). This guarantees system availability over strict rate enforcement during infrastructure outages.
5. Resiliency & Dynamic Fallbacks
+-----------------------+
| Incoming Request |
+-----------+-----------+
|
v
+-----------------------+
| Try Target #1: |
| OpenAI gpt-4o |
+-----------+-----------+
|
+----------+----------+
| |
(Success 200) (Error 429/5xx/Timeout)
| |
v v
(Return Body) +-----------------------+
| Check Circuit Breaker |
+-----------+-----------+
|
+----------+----------+
| |
(Closed) (Open)
| |
v v
+------------------+ +-------------------+
| Retry Attempt #2:| | Try Target #2: |
| Azure gpt-4o | | Anthropic Sonnet |
+------------------+ +-------------------+
Routing Rules and Circuit Breaker State Machine
- State Tracking: Circuit breakers run locally on each gateway node using consecutive error counters and rolling window error percentages.
- Failover Triggers: Fallbacks execute when encountering HTTP 429 (Rate Limit), HTTP 5xx (Internal Server Errors), network timeouts, or connection pool exhaustion.
- Mid-Stream Fallback Policy:
- If a failure happens before writing bytes to the client (e.g., initial connection fails), the gateway transparently reroutes to an alternate target.
- If a failure happens mid-stream (after sending headers to the client), the gateway cannot change providers mid-response. It sends a formatted SSE error event (
event: error), closes the socket, and logs the issue.
6. Storage Schema & Telemetry Architecture
Operational Database (PostgreSQL Control Plane)
CREATE TABLE tenants (
tenant_id VARCHAR(64) PRIMARY KEY,
company_name VARCHAR(255) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE',
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE api_keys (
key_hash VARCHAR(64) PRIMARY KEY,
tenant_id VARCHAR(64) REFERENCES tenants(tenant_id),
name VARCHAR(128) NOT NULL,
rpm_limit INT NOT NULL DEFAULT 600,
tpm_limit INT NOT NULL DEFAULT 100000,
is_active BOOLEAN DEFAULT TRUE,
expires_at TIMESTAMP WITH TIME ZONE
);
CREATE TABLE model_pricing (
pricing_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
provider VARCHAR(64) NOT NULL,
model_name VARCHAR(128) NOT NULL,
input_price_per_mtok NUMERIC(10, 6) NOT NULL,
output_price_per_mtok NUMERIC(10, 6) NOT NULL,
cached_price_per_mtok NUMERIC(10, 6) NOT NULL,
effective_from TIMESTAMP WITH TIME ZONE NOT NULL
);
Analytics Engine (ClickHouse Usage Records)
To analyze volume efficiently at scale (860 million events/day), high-volume telemetry is recorded in a ClickHouse columnar database:
CREATE TABLE usage_telemetry
(
request_id UUID,
event_time DateTime64(3, 'UTC'),
tenant_id LowCardinality(String),
key_hash String,
requested_model LowCardinality(String),
served_model LowCardinality(String),
provider LowCardinality(String),
attempt_count UInt8,
prompt_tokens UInt32,
completion_tokens UInt32,
cached_tokens UInt32,
computed_cost_usd Float64,
ttft_ms UInt32,
total_latency_ms UInt32,
http_status UInt16,
is_stream UInt8
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(event_time)
ORDER BY (tenant_id, event_time, requested_model);
7. Trade-offs & Common Failure Modes
Design Trade-offs
-
Exact Quotas vs. Low Latency:
- Choice: Use local prompt tokenizers + optimistic Redis reservation over global synchronous locking.
- Trade-off: Temporary token bursts may exceed limits by 1–2% during Redis sync delays, but this preserves the sub-15ms latency budget.
-
In-Memory Config Sync vs. Database Queries:
- Choice: Load tenant configurations, keys, and routing rules directly into node memory via push updates.
- Trade-off: Key revocations take a few seconds to propagate across all edge instances.
Failure Modes & Edge Cases
-
Upstream Silent Hangs (Hanging SSE Connections):
- Symptom: The upstream model stops streaming mid-response without closing the socket.
- Mitigation: Enforce an Inter-Token Timeout (ITT) of 5 seconds. If no new token frame arrives within 5 seconds, close the upstream socket and return an SSE error event to the client.
-
Thundering Herd on Model Outages:
- Symptom: Primary model (e.g.,
gpt-4o) fails, causing thousands of concurrent requests to fall back to secondary providers simultaneously, overloading them. - Mitigation: Combine circuit breakers with exponential backoff and jitter on fallback paths, and apply max concurrency limits to secondary endpoints.
- Symptom: Primary model (e.g.,