Skip to main content

Scenario: OpenAI LLM Gateway

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"Design an LLM gateway that routes requests across multiple model providers, enforces per-tenant budgets, and keeps p99 latency under 2 seconds for chat workloads."

2. Real-World Context​

DimensionDetail
Company / systemOpenAI API / enterprise AI platforms — routing, quotas, observability across heterogeneous inference backends
Scale500+ consuming apps; 2K req/sec peak; variable token lengths; GPU-bound inference; provider outages
Why architects careNew distributed systems constraints: token budgets, streaming SSE, semantic cache, KV cache on GPU side
Public referencesOpenAI API docs; vLLM; platform engineering blogs on LLM serving

AWS deployment context​

Typical enterprise LLM gateway on AWS: Amazon API Gateway or ALB + ECS Fargate gateway service; Amazon ElastiCache Redis for token budgets and semantic cache embeddings; Amazon DynamoDB for tenant config, model registry, and durable usage ledger; AWS Secrets Manager for provider API keys; Amazon Bedrock + SageMaker endpoints as inference backends; Amazon OpenSearch for audit log search; Amazon Kinesis for usage event stream; CloudWatch + X-Ray for TTFT/latency SLOs; AWS WAF for abuse protection.

Step-by-step flow:

StepActionExplanation
1POST /v1/chat/completionsClient sends chat request with stream=true.
2Validate API keyLookup tenant config: budget, allowed models, residency rules.
3PII scrubRedact SSN, email, credit card before any provider call.
4Reserve tokensPre-deduct estimated input+output tokens from tenant budget in Redis.
5Cache missSemantic cache lookup by embedding similarity — skip if hit.
6Select providerRouter picks backend by model alias, health, cost, residency.
7Forward + proxy SSEGateway proxies streaming tokens to client; meters on usage events.
8Meter usageAsync usage events to Kinesis for chargeback and reconciliation.
9Audit logRedacted prompt hash + metadata to OpenSearch for compliance.

3. Step-by-Step Interview Answer​

Step 1 — Clarify requirements​

RequirementTarget
API contractOpenAI-compatible POST /v1/chat/completions with SSE streaming
Throughput10K RPS peak; 100K concurrent SSE connections
Gateway p99< 20ms overhead (excluding model inference time)
Chat p99< 2s TTFT for standard workloads
Tenants500+ apps; per-tenant token budgets and model allowlists
ProvidersOpenAI, Anthropic, Azure OpenAI, Amazon Bedrock, self-hosted vLLM
SecurityPII redaction; audit log; no training on customer data
Non-goalsModel training pipelines; fine-tuning infrastructure

Step 2 — Capacity and cost math​

MetricCalculationResult
Peak RPS10K req/sec~500 gateway ECS tasks (20 RPS/task)
Concurrent SSE100K streamsConnection pooling; 2K streams/task
Token budget checkRedis INCRBY per request< 5ms p99
Monthly inference spend2B tokens/day × $0.01/1K avg~$600K/month — budget enforcement critical
Semantic cache hit rate20–30% for support botsSaves ~$120–180K/month
Small model routing40% queries → cheap modelAdditional ~$200K/month savings

Step 3 — Gateway architecture​

Step-by-step flow:

StepActionExplanation
1AuthValidate API key; load tenant config from DynamoDB (cached).
2PII scrubRegex + NER model redact sensitive fields before provider.
3Budget pre-checkReserve estimated tokens; reject 402 if budget exhausted.
4Semantic cacheEmbedding similarity search — return cached response on hit.
5Model routerSelect provider by alias, health, cost tier, data residency.
6GuardrailsBlock prompt injection patterns; content policy filter.
7Provider adapterUnified interface → OpenAI / Bedrock / vLLM native API.
8SSE stream proxyMultiplex provider token stream to client connection.
9Post-hoc reconcileTrue-up token count from usage event; refund over-reservation.

Step 4 — Chat completion request sequence​

Step-by-step flow:

StepActionExplanation
1POST requestClient sends messages array with stream=true.
2Auth + PII scrubValidate tenant; redact sensitive content.
3Reserve tokensPre-deduct estimated tokens (input length + max_output).
4aBudget exhaustedReturn 402 with Retry-After when daily cap hit.
4bRouteRouter resolves gpt-enterprise → Bedrock Claude 3.5.
5ForwardProvider adapter translates to Bedrock Converse API.
6SSE chunksProvider streams data: {"choices":[{"delta":{"content":"Hi"}}]}
7Proxy streamGateway forwards chunks; client sees low TTFT.
8Usage eventProvider returns final usage with actual token counts.
9ReconcileAdjust Redis budget: refund over-reservation delta.
10Usage eventAsync to Kinesis for chargeback warehouse.

Step 5 — Model routing and fallback​

Step-by-step flow:

StepActionExplanation
1Resolve aliasgpt-enterprise → {provider: bedrock, model: claude-3-5-sonnet}
2Check healthCircuit breaker state per provider — error rate / latency.
3Residency ruleEU tenant → EU-only endpoints (Bedrock eu-west-1).
4Primary healthy?If yes, route to primary; if no, enter fallback chain.
5aRoute primaryNormal path — lowest latency, preferred model.
5bFallback chaingpt-4 → gpt-4-turbo → gpt-3.5-turbo ordered list.
6Circuit breakerOpen after 5 consecutive 5xx or p99 > 10s.
7Queue or 503If all providers down: queue with SLA or return 503.

Step 6 — Semantic cache​

Step-by-step flow:

StepActionExplanation
1Embed promptGenerate embedding via small model (e.g., text-embedding-3-small).
2Vector searchRedis vector index (RedisSearch) — tenant-scoped keys.
3Similarity thresholdCosine similarity > 0.95 → cache hit.
4aCache HITReturn cached response — skip provider call; meter as cache hit.
4bCache MISSForward to provider; stream response to client.
5Store responseCache response + embedding with TTL (e.g., 24h).

Step 7 — Streaming and tail latency​

Step-by-step flow:

StepActionExplanation
1Stream requestClient expects SSE with data: prefixed JSON chunks.
2Priority tierPremium tenants get higher queue priority on vLLM.
3Continuous batchvLLM dynamically batches prefill + decode requests.
4Prefill completeTTFT dominated by prompt length and GPU queue depth.
5–6First tokenGateway proxies first chunk — client sees responsive UI.
7–9Decode loopInter-token latency (TPOT) — typically 20–50ms/token.
10Usage eventFinal token count for budget reconciliation.
11Idle timeoutClose SSE if no token for 30s — prevent zombie connections.

4. Whiteboard Guide​

Draw three layers: Gateway (policy + budget + routing) → Provider Adapters → Inference Backends. Emphasize gateway overhead is separate from model latency.

Step-by-step flow:

StepComponentRole
1WAFRate limit abusive IPs; block known attack patterns.
2Auth + PolicyAPI key validation; PII scrub; tenant isolation.
3BudgetRedis token counters; pre-reserve + reconcile pattern.
4Semantic CacheEmbedding similarity — 20–30% cost reduction.
5RouterHealth-aware provider selection with fallback chains.
6Inference tierHeterogeneous backends behind unified adapter interface.
7Kinesis + OpenSearchUsage metering and compliance audit trail.

5. Principal-Level Signals​

SignalWhat strong candidates say
Token budget first-class"Tokens are the currency — pre-reserve, reconcile, hard-stop on exhaustion."
Gateway vs model latency"Our p99 < 2s SLO is TTFT; gateway overhead target is < 20ms."
Provider abstraction"OpenAI-compatible facade; model aliases hide provider/version churn."
Fallback with degradation"GPT-4 down → GPT-3.5 with model_degraded: true header."
Tenant-scoped cache"Semantic cache keys include tenant_id — no cross-tenant leakage."
Streaming metering"Meter tokens on final usage event; mid-stream budget exhaustion is a policy choice."

6. Red Flags​

Red flagWhy it fails
Direct OpenAI calls from every appNo cost control, no audit, no unified fallback.
Rate limit by request count onlyLLM cost is token-based — 1 request can be 100K tokens.
No pre-reservationRace conditions cause budget overruns across concurrent requests.
Shared semantic cacheTenant A's prompt returns Tenant B's cached response — data leak.
Ignoring streamingBlocking on full response kills UX; SSE is default for chat.
No circuit breakerProvider 503 cascades into gateway thread exhaustion.
Synchronous audit loggingBlocks hot path; audit must be async to Kinesis/OpenSearch.

7. Follow-Up Questions​

QuestionStrong answer
GPT-4 down, GPT-3.5 up?Fallback chain auto-routes; return X-Model-Degraded: true header; notify tenant via webhook.
Agent loop burning tokens?Per-session budget cap; max tool-call iterations; circuit breaker on loop detection.
EU data residency?Route EU tenants to Bedrock eu-west-1 only; block external API calls for EU data.
Underestimated token count?Reserve with buffer (1.2× estimate); reconcile post-response; async overage billing.
Cache poisoning?Tenant-scoped keys; TTL; admin cache purge API; no cache for user-specific data.
Multi-modal (images)?Separate routing tier; vision models cost more — different budget pool.
Eval-gated model promotion?Canary 5% traffic to new model; promote only if eval score ≥ baseline.

8. Practice Drill (10 min)​

  1. 2 min — State token budget pre-reserve + reconcile pattern.
  2. 3 min — Draw request flow: auth → budget → cache → router → provider → SSE proxy.
  3. 3 min — Design fallback when primary provider circuit breaker opens.
  4. 2 min — Explain why semantic cache keys must be tenant-scoped.

9. Key Takeaways​

  1. Token budgets are first-class — pre-reserve in Redis, reconcile on usage event.
  2. Gateway overhead ≠ model latency — measure TTFT and gateway p99 separately.
  3. OpenAI-compatible facade — model aliases + provider adapters enable multi-vendor routing.
  4. Semantic cache — 20–30% cost savings for repetitive prompts; tenant-scoped keys mandatory.
  5. Streaming is default — SSE proxy with idle timeout; meter tokens asynchronously.

10. Production HLD​

10.1 C4 Context​

Step-by-step flow:

StepInteractionExplanation
1Apps ↔ GatewayOpenAI-compatible chat completion API.
2ProvidersBedrock, SageMaker, OpenAI, self-hosted vLLM.
3Budget + configRedis counters; DynamoDB tenant/model registry.
4AuditRedacted logs to OpenSearch; usage to Kinesis.
5AdminRegister models, set budgets, configure policies.

10.2 Full production stack​

LayerAWS ServicePurpose
EdgeWAF + ALBAbuse protection; TLS termination
GatewayECS FargateAuth, policy, budget, router, SSE proxy
Token budgetsElastiCache RedisPre-reserve + reconcile counters
Semantic cacheElastiCache Redis (vector)Embedding similarity search
Tenant configDynamoDBAPI keys, budgets, model allowlists, residency
Provider secretsSecrets ManagerOpenAI/Anthropic API keys; auto-rotate
Managed inferenceAmazon BedrockClaude, Llama, Titan models
Self-hosted inferenceEKS + vLLMCustom models; GPU autoscaling
Usage meteringKinesis → S3 → AthenaChargeback warehouse
AuditOpenSearchCompliance search; prompt hash index
ObservabilityCloudWatch + X-RayTTFT, token usage, error rate per model

10.3 Architecture index​

#DiagramSection
1AWS deployment context§2
2Request pipeline§3 Step 3
3Chat completion sequence§3 Step 4
4Model routing + fallback§3 Step 5
5Semantic cache flow§3 Step 6
6Streaming + tail latency§3 Step 7
7Whiteboard AWS layout§4
8C4 context§10.1
9Budget service LLD§11.2
10Fallback state machine§11.4

11. Production LLD​

11.1 Data schemas​

Tenant config (DynamoDB)

AttributeTypeKeyDescription
tenant_idStringPKAPI key owner
daily_token_budgetNumber—Max tokens per day (default 100K)
burst_rpsNumber—Max requests per second (default 50)
allowed_modelsList—Model aliases permitted
residencyString—us, eu, global
tierString—free, standard, premium

Model registry (DynamoDB)

AttributeTypeDescription
aliasString PKLogical name: gpt-enterprise
providerStringbedrock, openai, vllm
model_idStringProvider-specific model ID
fallback_chainListOrdered fallback aliases
cost_per_1k_inputNumberFor chargeback
cost_per_1k_outputNumberFor chargeback

Usage ledger (Kinesis → S3)

FieldTypeDescription
tenant_idStringConsumer
model_aliasStringLogical model used
providerStringActual backend
input_tokensNumberFrom usage event
output_tokensNumberFrom usage event
latency_msNumberTTFT + total
cache_hitBooleanSemantic cache hit
timestampISO8601Event time

11.2 Budget service pseudocode​

def reserve_tokens(tenant_id: str, estimated: int) -> Reservation:
key = f"budget:{tenant_id}:{today()}"
pipe = redis.pipeline()
pipe.get(key)
pipe.incrby(key, estimated)
current, new_total = pipe.execute()
current = int(current or 0)
budget = get_tenant_budget(tenant_id)

if new_total > budget:
redis.decrby(key, estimated) # rollback
raise BudgetExhausted(tenant_id, budget, current)

return Reservation(tenant_id, estimated, reservation_id=uuid4())

def reconcile(reservation: Reservation, actual_tokens: int):
delta = reservation.estimated - actual_tokens
if delta > 0:
redis.decrby(f"budget:{reservation.tenant_id}:{today()}", delta)
emit_usage_event(reservation, actual_tokens)

11.3 API contract​

POST /v1/chat/completions

// Request
{
"model": "gpt-enterprise",
"messages": [{"role": "user", "content": "Summarize this document"}],
"stream": true,
"max_tokens": 500
}

// Response headers
// X-Request-Id: req_abc123
// X-Model-Used: claude-3-5-sonnet (via gpt-enterprise)
// X-Tokens-Reserved: 2000
// X-Cache: MISS

// SSE stream
data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":"The"}}]}
data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":" document"}}]}
data: [DONE]

Error responses

CodeConditionBody
401Invalid API key{"error": "invalid_api_key"}
402Budget exhausted{"error": "budget_exhausted", "retry_after": 3600}
429Rate limit{"error": "rate_limit", "retry_after": 60}
503All providers down{"error": "service_unavailable", "fallback_attempted": true}

11.4 Fallback state machine​

Step-by-step flow:

StepStateExplanation
1PrimaryRouter selects primary provider for model alias.
2SuccessNormal path — stream response to client.
3FallbackCircuit breaker open or 5xx — try next in chain.
4SuccessFallback provider responds — add degradation header.
5QueueAll providers unhealthy — enqueue with timeout.
6SuccessRequest dequeued when provider recovers.
7RejectSLA exceeded — return 503 with retry guidance.

11.5 Provider adapter interface​

class ProviderAdapter(Protocol):
async def chat_completion(
self,
model_id: str,
messages: list[dict],
stream: bool,
max_tokens: int,
) -> AsyncIterator[StreamChunk] | ChatCompletion:
...

class BedrockAdapter(ProviderAdapter):
async def chat_completion(self, model_id, messages, stream, max_tokens):
client = boto3.client("bedrock-runtime", region_name=self.region)
response = client.converse_stream(
modelId=model_id,
messages=translate_messages(messages),
inferenceConfig={"maxTokens": max_tokens},
)
async for event in response["stream"]:
yield translate_chunk(event)

class OpenAIAdapter(ProviderAdapter):
async def chat_completion(self, model_id, messages, stream, max_tokens):
async with httpx.AsyncClient() as client:
async with client.stream(
"POST", "https://api.openai.com/v1/chat/completions",
json={"model": model_id, "messages": messages, "stream": stream},
headers={"Authorization": f"Bearer {self.api_key}"},
) as response:
async for line in response.aiter_lines():
yield parse_sse_line(line)

12. HA, DR, and Multi-Region​

ConcernStrategy
Gateway HAECS across 3 AZs; ALB health checks; auto-scale on RPS
Redis HAElastiCache cluster mode; replica per shard
Provider outageCircuit breaker + fallback chain; cross-provider routing
EU residencyEU tenants pinned to eu-west-1; no cross-border inference
SSE connection drainALB connection draining on deploy; 30s idle timeout
Budget consistencyRedis atomic INCRBY; eventual reconciliation via Kinesis

13. Observability​

MetricTargetAlarm
gateway.overhead.p99< 20ms> 50ms
ttft.p99< 2s> 5s
budget.check.p99< 5ms> 20ms
semantic_cache.hit_rate> 20%< 10%
provider.error_rate< 1%> 5%
circuit_breaker.open0Any open > 5 min

Dashboards: Token usage per tenant; cost per model; TTFT by provider; fallback rate; cache hit ratio.

14. Evolution Roadmap​

PhaseCapabilityTrigger
V1Single provider (OpenAI) + rate limitInitial launch
V2Multi-provider routing + fallbackProvider outage incident
V3Token budgets + semantic cacheCost overrun
V4Self-hosted vLLM on EKSData residency / cost at scale
V5Eval-gated canary routingModel quality regression

15. Testing Strategy​

Test typeScenarioPass criteria
UnitBudget reserve + reconcileNo overruns under concurrent load
IntegrationEnd-to-end streamingSSE chunks arrive; usage metered
FallbackPrimary provider 503Fallback responds within 500ms
CacheIdentical prompt twiceSecond request cache hit; no provider call
IsolationTenant A cacheTenant B does not see Tenant A cached response
Load10K RPS sustainedGateway p99 < 20ms; no connection leaks
ChaosKill Redis shardBudget check degrades gracefully (fail-closed)

16. Production Checklist​

  • OpenAI-compatible API contract (/v1/chat/completions)
  • Token budget pre-reserve + reconcile in Redis
  • Model aliases with fallback chains in DynamoDB
  • Provider adapters for Bedrock, OpenAI, vLLM
  • Circuit breaker per provider with health metrics
  • Semantic cache with tenant-scoped keys
  • PII scrub before any provider call
  • SSE stream proxy with idle timeout
  • Async audit log to OpenSearch (no raw PII)
  • Usage events to Kinesis for chargeback
  • EU residency routing enforced for EU tenants
  • X-Model-Degraded header on fallback responses