Design an LLM gateway for a company
Once a company has more than a handful of teams using LLMs, the same problems show up everywhere: API keys pasted into repos, no idea who spent 40,000 dollars last month, customer data flowing to providers nobody approved, and every team writing its own retry logic. The fix is an LLM gateway: one internal endpoint that every application calls, which handles routing, keys, quotas, redaction and audit. Open-source projects like LiteLLM and Envoy AI Gateway, and cloud offerings from most API gateway vendors, all implement versions of this. Here is how I would design one.
Requirements
Functional
- One OpenAI-compatible API (chat, embeddings, images, audio) in front of many providers and self-hosted models.
- Virtual keys per team, app or user, mapped to allowed models.
- Quotas and budgets: requests per minute, tokens per minute, and monthly spend per key or team.
- PII detection and redaction (or blocking) on prompts, configurable per route.
- Routing: by model alias, cost, latency or region; automatic fallback on errors.
- Audit log of every call: who, what model, tokens, cost, policy decisions.
Non-functional
- Low added latency (target: under 20 ms p50 overhead before the provider call, excluding redaction models).
- High availability: the gateway must not be a bigger outage risk than the providers.
- Streaming passthrough with no buffering of the full response.
- Data residency: some routes must only reach providers in a given region.
Scale estimates (assumptions)
| Quantity | Assumption | Result |
|---|---|---|
| Internal apps | 300 | across 60 teams |
| Requests per day | 20M | about 230/s average, 1,000/s peak |
| Average tokens per request | 2,500 in, 400 out | about 58B tokens/day |
| Audit log size | 5 KB metadata per request | 100 GB/day of metadata |
| Full prompt logging | 15 KB per request if enabled | 300 GB/day, which is why it is opt-in |
The QPS is modest. The challenges are correctness of budgets across replicas, keeping overhead low, and storing logs that are useful without becoming a data leak themselves.
High-level architecture
Rendering diagram…
Request flow
Rendering diagram…
Components
| Component | Responsibility | Notes |
|---|---|---|
| Gateway replicas | Stateless proxy, OpenAI-compatible API, streaming | Written for low overhead; scale horizontally |
| Config store | Keys (hashed), teams, model aliases, routes, budgets, policies | Postgres plus in-memory cache with short TTL |
| Limit counters | Shared RPM, TPM and spend counters | Redis; without a shared store each replica enforces its own copy of the limit |
| PII service | Detect and redact or block sensitive data | Presidio-style recognizers plus custom ones for internal IDs |
| Cache | Exact match cache; optional semantic cache | Keyed by tenant to avoid cross-team leaks |
| Router | Model alias to concrete deployments, health tracking, fallback chains | Circuit breakers per provider deployment |
| Audit pipeline | Async events to a warehouse | Metadata always; prompts and outputs only where policy allows |
| Admin portal | Self-service keys, budgets, usage dashboards | Teams see their own spend without filing tickets |
Data model
CREATE TABLE teams (
id UUID PRIMARY KEY,
name TEXT,
monthly_budget NUMERIC(12,2),
cost_center TEXT
);
CREATE TABLE virtual_keys (
key_hash TEXT PRIMARY KEY, -- never store the raw key
team_id UUID,
app_name TEXT,
allowed_models TEXT[], -- aliases like "chat-default", "embed-default"
rpm_limit INT,
tpm_limit INT,
budget_usd NUMERIC(12,2),
pii_policy TEXT, -- off | redact | block
log_payloads BOOLEAN,
region TEXT,
expires_at TIMESTAMPTZ
);
CREATE TABLE model_routes (
alias TEXT,
priority INT,
provider TEXT,
model TEXT,
region TEXT,
input_price NUMERIC(10,6), -- per 1K tokens, from provider price sheets
output_price NUMERIC(10,6),
PRIMARY KEY (alias, priority)
);
Model aliases are the most useful abstraction here. Apps ask for chat-default; the platform team decides which concrete model that means and can switch it without any app deploying.
Deep dives
Budgets and rate limits across replicas
Token limits are tricky because you only know output tokens after the response. The usual approach is to reserve: estimate prompt tokens before the call (tokenize or approximate), reserve prompt + max_tokens against the TPM and budget counters, then settle with actual usage when the stream ends. Use atomic Redis operations (a Lua script or INCRBY with TTL windows) so concurrent replicas cannot overspend. For monthly budgets, a small overshoot from in-flight requests is acceptable; document it rather than serializing every request.
Routing and fallback
Each alias maps to an ordered list of deployments. The router tracks health per deployment (error rate, latency, recent 429s) and opens a circuit breaker when one is unhealthy. Fallback rules should be explicit: falling back from one provider's model to another changes behavior, so some teams will want "same model in another region only." Retries must never happen after streaming has started sending tokens to the client.
PII redaction
PII handling is a policy per key: off, redact, or block. Detection layers:
- Regex and checksum recognizers for structured data (emails, card numbers, national IDs). Fast and precise.
- An NER model for names and addresses. Slower and less precise.
- Custom recognizers for internal identifiers (employee IDs, customer numbers).
Redaction can be reversible: replace "alice@corp.com" with <EMAIL_1>, keep the mapping in request memory, and restore it in the response so the app still gets a useful answer. Microsoft's Presidio is a common open-source base. Its own docs warn that ML-based detection will not catch everything, so treat redaction as risk reduction, and pair it with provider contracts (zero retention, regional processing).
Audit logging without creating a new leak
The audit log is gold for security and FinOps, and a liability if it stores every prompt forever. Log metadata for every call (key, team, model, tokens, cost, latency, policy actions, request id). Log payloads only for keys that opt in, with redaction applied, short retention, and access controls stricter than the apps themselves. Write events asynchronously to a queue so logging never adds latency or takes the gateway down.
Caching
Exact-match caching (hash of model plus full request) is safe and helps for repeated evaluation runs and deterministic tasks. Semantic caching (embedding similarity on prompts) can return wrong answers for prompts that look similar but differ in a crucial detail; enable it only for narrow, known use cases. Always scope cache keys by team.
Availability
The gateway sits in the path of every AI feature, so treat it like core infrastructure: multiple replicas across zones, config cached in memory so a database blip does not stop traffic, and a documented fail-open vs fail-closed choice for each dependency. My default: if the PII service is down, fail closed for keys with block, fail open with an alert for redact. If Redis is down, fall back to local per-replica limits.
Trade-offs and pitfalls
- Gateway as bottleneck. Heavy synchronous work (NER models, logging) inflates latency. Keep the hot path lean and async everything else.
- Lowest-common-denominator API. Normalizing to one API hides provider-specific features (prompt caching controls, reasoning settings, tool formats). Allow passthrough fields.
- Price tables drift. Costs are computed from a price table that someone must update when providers change prices. Automate or own it.
- Shadow usage. Teams calling providers directly bypass everything. Block egress to provider endpoints from production networks except via the gateway.
- Key sprawl. Expire keys, tie them to owners, and alert on unused or leaked keys.
- Retries multiplying cost. Retries plus fallbacks plus agent loops can multiply spend. Count every attempt against the budget.
Checklist
- OpenAI-compatible API with model aliases, so apps never hardcode providers.
- Virtual keys hashed at rest, scoped to models, budgets and policies.
- Shared atomic counters for RPM, TPM and spend, with reserve-then-settle.
- Per-deployment health tracking, circuit breakers and explicit fallback chains.
- PII policy per key (off, redact, block) with reversible redaction.
- Metadata audit for every call; payload logging opt-in, redacted, short retention.
- Egress controls so the gateway is the only path to providers.