Scalable Multi-Dimensional Throttling for an Inference API
System DesignModel answerLast updated
Architect a distributed throttle service for an LLM API that enforces per-org request and token limits with sub-5ms latency at 200k RPS.
Context
You run the platform layer for a large-language-model API. Millions of developers call your inference endpoints, and each call consumes both a "slot" (a request) and a variable amount of compute (tokens). You need a centralized throttling service that sits in the request path of every gateway and decides, in milliseconds, whether a call should proceed or be rejected.
The tricky part is that you don't know the real cost of a request until the model finishes generating. So the limiter must reserve an estimate up front and adjust afterward.
What to Build
A distributed rate-limiting service with the following properties:
- Two limit dimensions per caller: requests per minute (RPM) and tokens per minute (TPM), enforced per organization. API keys inherit their org's limits.
- Tiered and per-model configuration: quotas differ by customer tier (free, paid tiers) and by model family (e.g. a flagship chat model vs. a lightweight embedding model). Rules must be changeable without redeploying gateways.
- Standard client-facing behavior: when a limit is hit, return HTTP 429 with
Retry-After,X-RateLimit-Remaining, andX-RateLimit-Resetheaders. On success, return remaining quota headers. - Two-phase token accounting: reserve an estimated token count before the model runs, then reconcile the difference once the actual count is known. Handle refunds and overages.
Non-Functional Targets
- Limiter overhead on the hot path: p99 under 5 ms.
- Peak load: 200,000 requests/sec across globally distributed gateway nodes.
- 10 million active API keys, ~1,500 tokens per request on average.
- The system should favor availability over strict precision: slight over-allowance during failures is acceptable, but blocking legitimate traffic is not.
What Your Answer Should Cover
- Choice of rate-limiting algorithm and why it fits variable-cost, refundable workloads.
- High-level architecture: how gateways, the limiter, a shared counter store, and a config store interact.
- Data model and how atomic multi-dimensional checks happen without distributed locks.
- The reserve-and-reconcile flow for tokens, including what happens if a gateway crashes mid-request.
- Failure handling: cache outages, network partitions, clock drift, and cold starts.
Hints
Hint 1
Start by translating the scale numbers into concrete throughput and memory requirements for the counter store before drawing any boxes.
Hint 2
Think about which algorithm natively supports subtracting a variable cost and adding a refund back later.
Hint 3
If one Redis shard is a single-threaded bottleneck for a hot org, what can the gateway do locally to avoid hitting that shard on every request?
Hint 4
Clock drift between gateways and the counter store can corrupt refill math—where should the authoritative timestamp come from?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Quantify the Problem First
Before designing anything, put numbers on the table:
- Limiter operations: 200k requests/sec means roughly 400k limiter ops/sec (one reserve, one reconcile). Every op must be sub-millisecond, which means at most one in-region network hop on the critical path.
- Token volume: 200k × 1,500 = ~300M tokens/sec. TPM is the binding constraint, not RPM, because token counts vary by orders of magnitude across requests.
- State footprint: 10M orgs × ~3 model groups × 2 dimensions × ~64 bytes per bucket ≈ 4 GB. That fits comfortably in a sharded Redis cluster with replicas.
- Latency budget: p99 < 5 ms leaves room for one in-region call (0.5–1 ms). Cross-region calls and distributed locks are out of scope.
- Consistency model: this is an AP system. Brief over-allowance during partitions is fine; blocking valid traffic is not.
Confirm scope with the interviewer: limits apply per org (keys inherit), scoped per model group, and billing accuracy is a separate downstream pipeline.
2. Algorithm Choice
Compare the three common options:
- Token bucket: O(1) state (token count + last refill timestamp). Handles variable-cost reservations natively (subtract N tokens). Refunds are trivial (add tokens back, capped at capacity). Burst size is an explicit knob. This is the natural fit.
- Sliding window counter: works for RPM but makes token reconciliation messy. Adjusting a past window when actual tokens differ from the estimate is error-prone.
- Leaky bucket: smooths traffic by queuing, which adds latency to an interactive API. Reconciliation and variable costs are awkward.
Choose token bucket for both dimensions. Use a weighted bucket for TPM (subtract est_tokens) and a simple request bucket for RPM (subtract 1). Each bucket is a two-field structure: current tokens and last-refill timestamp.
3. Architecture
Client → Edge/WAF → API Gateway [auth | local leases | rules cache]
│ in-region (~1ms)
▼
Redis Cluster (sharded by org_id, primary + replica)
▲
Config Store (Postgres) → Config Service → pub/sub push to gateways
Gateway → Kafka (usage events) → billing / analytics / async reconciliation
Key design points:
- Config store (Postgres) holds tier definitions and per-model limits. A config service pushes updates to gateways via pub/sub. No config reads happen on the hot path; gateways keep rules in memory.
- Redis cluster is the shared source of truth for bucket state. Shard by
org_idusing hash tags (e.g.{org_id}) so RPM and TPM buckets for the same org land on the same shard. This lets one Lua script touch both buckets atomically. - Local leases for hot keys: the gateway borrows a small chunk of quota (e.g.
min(5% of capacity, 1 second of refill)) from Redis and serves requests from memory. Heavy orgs then cost zero network calls for most requests. Unused lease quota is returned on expiry (~1s TTL). Low-traffic keys skip the lease and go straight to Redis for precision. Over-allowance is bounded byoutstanding leases ≈ #gateways × lease_size, which is the explicit latency/precision trade-off.
4. Data Model and Atomicity
rl:{org}:{model}:tpm → HASH {tokens, ts} TTL = 2 × refill window
rl:{org}:{model}:rpm → HASH {tokens, ts}
rsv:{request_id} → est_tokens TTL = max request duration + slack
A single Lua script handles the reserve check:
- Read both buckets for the org+model.
- Refill each:
tokens = min(capacity, tokens + (now - ts) × rate). Useredis.call('TIME')for the timestamp so gateway clock drift doesn't matter. - Check
rpm_tokens ≥ 1 AND tpm_tokens ≥ est_tokens. - Deduct from both or from neither—no partial state.
- Write the reservation record and return remaining values plus a retry hint.
Redis executes Lua scripts single-threaded per shard, so the multi-dimensional check is atomic without any distributed locks. Locks would blow the latency budget anyway. Idle buckets expire via TTL; a missing key means a full bucket.
5. Two-Phase Token Accounting
- Estimate. The gateway tokenizes the prompt (it already does this) and computes
est = prompt_tokens + min(max_tokens, model_default_cap). Reserving the fullmax_tokensis safe but starves users who set it high. A refinement: reserve a p90 of historical completion length per key+model. - Reserve the estimate atomically via the Lua script.
- Reconcile on completion with
delta = actual - est:- Negative delta (overestimate): add tokens back, capped at capacity.
- Positive delta (underestimate): charge the difference. The bucket can go negative, creating a "debt" that blocks future requests until refilled. This keeps long-run TPM accurate.
- Streaming: for long generations, send interim reconciles every N tokens so concurrent requests see realistic remaining quota.
- Crash safety: reconcile is idempotent on
request_id. If the gateway dies, the reservation TTL expires and the estimate stays charged—conservative and self-healing. Exact billing comes from Kafka usage events, not the limiter.
6. Failure Modes
- Redis shard down: use a 2 ms timeout plus a circuit breaker. Fail open to a degraded local limiter where each gateway enforces
limit / N_gatewaysfrom cached rules. Gateway count comes from service discovery. Replica promotion restores the shard; lost counters reset to full, which is acceptable over-allowance. - Network partition: gateways keep serving on leases and local limits. Over-allowance is bounded by outstanding leases.
- Clock drift: all refill math uses Redis server time. Lease expiry uses gateway monotonic clocks. No cross-node time dependency on the hot path.
- Cold start: new gateways load rules before passing health checks. Leases start small and grow with observed traffic. A full Redis restart resets buckets to full; pair this with a global per-model capacity bucket to protect clusters from thundering herds.
- Hot key (one org at 20k RPS): leases absorb the load. Without leases, one Redis shard's single thread becomes the bottleneck.
7. Common Mistakes
- Choosing sliding window for TPM and then struggling with post-hoc window adjustments.
- Reserving full
max_tokenseverywhere, which unnecessarily throttles conservative users. - Using distributed locks for atomicity instead of single-shard Lua scripts, blowing the latency budget.
- Forgetting to bound over-allowance when failing open: a local fallback without dividing by gateway count can let 10x the limit through.
- Assuming Redis is always available; the fail-open path must be designed and tested, not an afterthought.