Notes
Listen
Listen. Teams send chat and embedding requests to one endpoint in one format, whatever the provider behind it. Each team and app gets its own key. We enforce quotas in tokens per minute, track cost per team for a monthly bill, route and fall back between providers, stream answers, cache where safe, redact personal data, enforce which models and regions a team may use, and keep logs and traces.
The qualities. The gateway must add at most about twenty milliseconds at p ninety-nine, small next to a model's first token. It needs four nines, because it now sits in front of every AI feature. No app holds a provider key, no data goes to a model or region a team is not allowed, and one noisy team cannot starve the rest. Out of scope: training, agent logic and serving the models ourselves.
- one endpoint for every model and provider, same format
- a key per team and app
- quotas in tokens per minute
- cost per team, monthly bill
- routing, retries, fallback
- streaming responses
- caching where it is safe
- PII redaction, allow-lists, data residency
- logs and traces for debugging
- adds ≤ 20 ms at p99
- 99.99%: it sits on every AI feature in the company
- no provider keys in apps
- no data to a model or region a team is not allowed
- one team cannot starve others
- internal callers only out of scope: training, agent logic, serving the model
Ask scale
Scale. Say three hundred teams and about a thousand apps make ten million requests a day. That is about a hundred fifteen a second, and with a daytime peak of five times, about six hundred a second. A typical request sends two thousand input tokens and gets three hundred back. That is twenty billion input and three billion output tokens a day, and at peak about eighty-three million tokens a minute.
Turn that into decisions. At an assumed three dollars per million input tokens and fifteen per million output, that is about a hundred five thousand dollars a day, three million a month. That is why chargeback matters. Each answer streams for about seven seconds, so at peak four thousand two hundred streams are open. Providers cap tokens per minute per account, so eighty-three million must be spread over several accounts, regions and providers.
300 teams, ~1,000 apps and jobs 10M requests/day ≈ 115/s avg; daytime peak ×5 ≈ 600 requests/s per request: 2,000 in + 300 out = 2,300 tokens day: 20B in + 3B out tokens peak: 600 × 2,300 ≈ 1.4M tok/s ≈ 83M tokens per minute
cost, at $3 / $15 per M tokens:
20B in × $3 = $60k
3B out × $15 = $45k
≈ $105k/day ≈ $3M/month
streams: 600/s × ~7 s each
≈ 4,200 open at peak
provider cap per account,
e.g. 10M tokens/min per model
→ spread over accounts,
regions and providers
bodies: 10M × 10 KB = 100 GB/day Define API
The API. A chat call carries the team key and an idempotency key. The body names a model alias such as chat default, not a vendor model, so we can change what it points to without touching any app. It has messages, max tokens and a stream flag. The response is server-sent events: deltas, then a final usage event. Shape it like the most common chat API, so existing SDKs just work. Add embeddings, a usage report and admin calls.
POST /v1/chat
Authorization: team key
Idempotency-Key: 7f3a…
{ model: "chat-default",
messages, max_tokens,
stream: true, metadata }
→ SSE: delta … delta … usage
POST /v1/embeddings
GET /v1/usage?team=&month=
admin: keys, policies, routes Data model
Data model. Config is small and read on every request: teams with a cost center, a token limit and a budget; keys, stored only as hashes; policies listing allowed models, region, PII mode, cache mode and log sampling; routes mapping an alias to ordered targets; and a price table with validity dates. That lives in Postgres and is pushed to the gateways. Usage events are big and append-only, so they go to a columnar warehouse.
teams: id, cost_center, tpm_limit, monthly_budget api_keys: key_hash PK, team_id, app, scopes, revoked_at policies: team_id, models[], region, pii_mode, cache, sample routes: alias → ordered targets (provider, model, region) prices: model, from, in/out/$ usage_events (columnar): ts, team, model, tokens, cost
High-level design
Trace a request. The gateway hashes the key and finds the team in its local config. It reserves tokens from the team's quota in Redis, runs policy checks, and the router resolves the alias to a provider, model and region. Policy and routing are modules inside the gateway process, not network hops. The provider streams tokens, and the gateway passes each chunk straight to the caller, converted to our one event format.
Interviewers will ask what the gateway costs in latency, so budget it. Key lookup from local memory is a tenth of a millisecond. The quota script in Redis is about one. Counting prompt tokens takes a millisecond or two, regex PII and secret scanning a few, an exact cache lookup one. Keep warm, pooled connections to providers. That is under ten milliseconds against a first token of up to two seconds. Slower checks are opt-in per route.
Policy runs before any byte leaves. Is this model on the team's allow-list? What data class and region is the team in? An EU team only reaches EU endpoints, and restricted data only goes to the self-hosted model. Personal data is blocked, masked or allowed per policy. Masking swaps an email for a placeholder and restores it in the answer, holding a few tokens so a placeholder split across chunks is caught. Leaked secrets are blocked.
Two side flows. The control plane pushes keys, policies, routes and prices to every node, which keeps them in memory. And every request emits a usage event, about a kilobyte, with tokens, cost, time to first token and status. Full prompts and answers are a hundred gigabytes a day and sensitive, so log one percent plus all errors, redacted and encrypted for thirty days. Carry the caller's trace id, and write everything asynchronously.
target: p50 ≤ 5, p99 ≤ 20 auth: key hash, local cache 0.1 quota: Redis Lua script 1 tokenize the prompt 1-2 PII regex + secrets scan 2-5 exact cache lookup 1 route, pooled connection 0.5 model first token: 300-2,000 → gateway ≈ 1-2% of TTFT semantic cache, ML PII: opt-in
- 1 key → team → policy
- 2 model on allow-list? else 403
- 3 data class + region: EU team → EU endpoints only restricted → self-hosted only 4 PII: block, mask or allow mask: email → [EMAIL_1], restore it in the response
- 5 secrets in a prompt → block
- 6 output: scan every ~50 tokens in a small buffer
- every request → usage event: team, model, tokens in/out, cached, cost, TTFT, status 100%, about 1 KB each bodies: 1% sample + all errors redacted, encrypted, 30 days per-team opt in or out trace id from the caller; spans: policy, cache, provider, first token
- async: local buffer → Kafka
Deep dive: quotas
Deep dive one: quotas. Requests per second is the wrong unit, because one request can be fifty tokens or a hundred thousand. Use a token bucket per team, say two million tokens a minute. Output size is unknown up front, so reserve the counted input plus max tokens, here twenty-eight hundred, then refund the unused four hundred ninety when the usage arrives. Over the limit returns four twenty-nine with Retry-After. The same buckets guard each provider account.
Cost. A consumer prices each usage event with the price row valid at that moment, because prices change, and treats cached input tokens at their cheaper rate. Totals roll up per team per hour into the warehouse and a monthly chargeback per cost center. A subtle case: the client hangs up mid-stream. Cancel the provider call so we stop paying, count the tokens already generated, and still bill them. Alert at eighty percent of budget, block at a hundred.
team bucket: 2M tokens/min problem: output size unknown before: reserve input 2,000 (counted) + max_tokens 800 = 2,800 after: actual 2,000 + 310 refund 490 to the bucket one Redis Lua script, atomic over → 429 + Retry-After tiers: interactive > batch
usage event → Kafka → aggregate per team per hour cost = in × price_in + cached × price_cached + out × price_out (price row valid at ts) client hangs up mid-stream: cancel upstream, count what was generated, still bill budget: alert 80%, block 100% monthly chargeback by cost_center
Deep dive: routing
Deep dive two: routing. An alias maps to ordered targets, provider A, then B, then self-hosted, all in the allowed region. A circuit breaker per provider, model and region watches errors, rate-limit responses and time to first token. Slow counts as down. When A's breaker opens, new requests go to B. Fall back only before the first token is sent; mixing two models mid-answer is wrong. And run your eval set against each fallback model first.
Retries. Retry rate limits, server errors and timeouts, with backoff and jitter, at most twice, and never retry a bad request or a policy block. Cap retries at about ten percent of traffic, so an outage does not triple the load. Callers also retry, so store each idempotency key in Redis for a day. A duplicate of a running call waits; a finished one replays the stored answer. A timeout is not free: the provider may already have billed us.
- route chat-default: 1 provider A, model X, EU 2 provider B, model Y, EU 3 self-hosted, EU
- breaker per provider+model+ region: errors, 429s, TTFT
- fall back only before the first token is sent
- never leave allowed region
- fallback model is evaluated on the same test prompts
retry: 429, 5xx, timeout backoff + jitter, max 2 never retry 400 or a policy block retry budget ≤ 10% of calls (stops retry storms) Idempotency-Key in Redis 24 h: running → wait or 409 done → replay stored answer timeout is not free: the provider may have billed
Deep dive: caching
Deep dive three: caching. An exact cache keys on a hash of team, model version, full messages and parameters. It is safe for deterministic work: temperature zero extraction, classification, embeddings and eval reruns. Never share entries across teams, and skip calls that use tools. Separately, providers cache prompt prefixes and bill those tokens at a big discount. Help them: keep the system prompt stable and first, and route the same prefix to the same provider and region.
A semantic cache embeds the prompt, finds the nearest stored prompt, and above a similarity threshold returns its answer. It sounds great until refund order eleven eighty-two and refund order eleven eighty-three score point nine nine, and one customer gets the other's answer. So make it opt-in per route, only for FAQ-style prompts without user data, never across teams, with short lifetimes, and measure the false-hit rate on sampled traffic. It also adds an embedding call.
exact cache (Redis, per team):
key = hash(team, model,
version, messages, params)
safe: temperature 0,
extraction, classification,
embeddings, eval reruns
TTL hours; skip if tools run
provider prefix caching:
stable system prompt first,
sticky route → cheap tokens - embed the prompt, nearest neighbour, similarity ≥ 0.95 → return the stored answer
- danger: near but different "refund order 1182" "refund order 1183" similarity 0.99, wrong answer
- safe only: opt-in per route, FAQ-like, no user data, never across teams, short TTL
- measure the false-hit rate
Trade-offs
Availability. Gateway nodes are stateless, a dozen across three zones and two regions, sized so a whole zone can fail. If the control plane is down, nodes keep serving from cached config. If Redis is down, each node enforces its share of every quota locally and fails open, because blocking all AI traffic is worse. If Kafka is down, buffer usage to disk. Drain long streams before deploys, and isolate critical teams in their own cell.
The trade-off is one extra hop and one more critical system, in exchange for keys, cost, policy and fallbacks in a single place. Many companies start from an open-source proxy and add their own policy plugins. Monitor the gateway's own overhead, first-token time per provider, rate-limit responses, fallback rate, cache hits and dollars per team. At ten times the scale, add provider accounts and regions, and move simple high-volume tasks to self-hosted models.
- stateless nodes, 3 zones, 2 regions; one zone can die
- config cached in each node: control plane down → serve
- Redis down → local quota share per node, fail open
- Kafka down → disk buffer, drop sampled bodies first
- deploys: drain streams 5 min
- cells: critical teams apart
- SDK: retry the other region
- gateway vs direct calls: + one place for keys, cost, policy; - a hop, a SPOF
- build vs buy: open-source proxy + our policy plugins
- monitor: overhead p99, TTFT per provider, 429s, fallback rate, cache hits, $ per team
- at 10x: more provider accounts, regions, self-hosted share for simple, high-volume tasks
Interview summary
The thirty-second version. Six hundred requests and eighty-three million tokens a minute at peak, about a hundred thousand dollars a day. One chat API with a model alias and a key per team. Token buckets that reserve and refund, and usage events that drive chargeback. Ordered routes with breakers, falling back only before the first token. Retry budgets and idempotency keys. Exact caching freely, semantic caching carefully. Policy before data leaves, all within twenty milliseconds.
- 600 req/s, 83M tokens/min peak
- one chat API, keys per team
- TPM bucket: reserve, refund
- usage events → chargeback
- routes: ordered targets, breakers, fall back pre-token
- retry budget + idempotency key
- exact cache safe; semantic only opt-in policy: PII, allow-list, region
- overhead p99 ≤ 20 ms, stateless