Library

Volume 1 · Additional Advanced System Design Scenarios

Notebook
Sign in

Section 68

Global Rate Limiter / API Gateway for a Multi-Region AI API Platform

3,026 words · about 14 min

Problem Statement

Design a rate limiter/API gateway enforcing per-customer quotas and rate limits (e.g., requests/minute, tokens/minute for an LLM API) consistently across multiple geographic regions, with minimal cross-region coordination latency — the core “distributed counting” problem: how do you accurately enforce a single global limit when traffic for one customer arrives simultaneously in multiple regions, without a synchronous cross-region call on every request (which would destroy latency).

Requirements Clarification

  • Assume a global AI API platform (e.g., LLM completions API) deployed across 4 regions (US, EU, APAC, and a secondary US region for DR).
  • Rate limit dimensions: per-customer requests/minute (RPM) and tokens/minute (TPM) — TPM is trickier because token count for a request is only known after the response is generated (for output tokens), not purely at request time.
  • Assume tiered customers: free tier (e.g., 60 RPM / 40K TPM), paid tier (e.g., 3,500 RPM / 350K TPM), enterprise tier (custom negotiated limits, sometimes with dedicated capacity).
  • Requirement: limits must be enforced globally per customer (a customer hitting your US and EU endpoints simultaneously should not effectively get 2x their quota by splitting traffic across regions), but the enforcement mechanism must not add meaningful latency to the hot request path (target: rate-limit check adds <5ms to p99 request latency) and must not introduce a single global point of failure (a coordination service outage should not take down the entire platform’s request handling).
  • Assume peak aggregate platform traffic: 200,000 requests/minute across all customers/regions combined, highly skewed by customer size.
  • Tolerance: clarify with interviewer — perfectly exact global enforcement (zero possibility of ever exceeding the limit, even briefly) vs. “soft” enforcement that allows small, bounded overshoot in exchange for avoiding synchronous cross-region coordination. Assume the business accepts bounded overshoot (e.g., up to ~10-20% burst tolerance) as the practical trade-off, which is standard industry practice for this exact reason.

Architecture Diagram

                     ┌───────────────┐   ┌───────────────┐   ┌───────────────┐   ┌───────────────┐
   Customer traffic  │   Region: US-E  │   │  Region: EU     │   │  Region: APAC   │   │ Region: US-W (DR)│
   (geo-routed by     └───────┬────────┘   └───────┬────────┘   └───────┬────────┘   └───────┬────────┘
    DNS/anycast)                │                     │                     │                     │
                                 ▼                     ▼                     ▼                     ▼
                      ┌───────────────────────────────────────────────────────────────────────────────┐
                      │                    Regional API Gateway (per region, identical stack)             │
                      │                                                                                    │
                      │  ┌────────────────────────────────────────────────────────────────────────────┐ │
                      │  │  Local Rate Limiter (in-memory / local Redis, <1ms)                            │ │
                      │  │  - token bucket per customer, LOCAL allocation = (global_limit / N_regions)    │ │
                      │  │    + dynamic borrowing from a shared regional-share pool                        │ │
                      │  │  - fast local decision: ALLOW / REJECT (429) made without cross-region call     │ │
                      │  └───────────────────────────┬────────────────────────────────────────────────┘ │
                      └────────────────────────────────┼──────────────────────────────────────────────────┘
                                                          │  async usage events (batched, ~100-500ms interval)
                                                          ▼
                      ┌───────────────────────────────────────────────────────────────────────────────┐
                      │              Global Usage Aggregation Layer (async, eventually consistent)        │
                      │  - each region streams its local usage counters                                    │
                      │  - central aggregator (or gossip/CRDT-based peer sync between regions) computes    │
                      │    true global usage per customer                                                   │
                      │  - redistributes updated per-region allocation shares back to each region           │
                      │    based on observed regional traffic proportion (adaptive rebalancing)              │
                      └───────────────────────────────────────────────────────────────────────────────┘

   Enforcement model:
   - Each region gets a LOCAL SHARE of the customer's global limit (not the full limit), sized initially
     by even split or historical traffic proportion, then continuously rebalanced based on observed
     regional demand (a customer whose traffic is 90% in US-East gets 90% of their global budget
     allocated to the US-East region's local bucket).
   - Regions enforce hard local limits with zero cross-region synchronous calls -> bounded worst-case
     global overshoot = sum of all regions' "slack" (the gap between allocated share and instant
     redistribution lag), tunable via aggregation interval and reserved headroom.
   - TPM (token-based) limiting: request-time check uses an ESTIMATED token cost (based on prompt
     length + a max_tokens request parameter) reserved against the bucket optimistically; actual
     output token count reconciles the bucket after generation completes (refund the delta if actual
     < estimated, or count the overage if actual > estimated, feeding into the next window).

Key Design Decisions

  1. Regional local enforcement with async global rebalancing vs. synchronous cross-region coordination on every request.

    • Chosen: each region enforces against a locally-held share of the customer’s global limit, using a fast local counter (in-memory or regional Redis, sub-millisecond); actual global usage is aggregated and rebalanced asynchronously across regions on a short interval (e.g., every 100-500ms), adjusting each region’s local allocation share going forward.
    • Alternative: every request synchronously checks/decrements a single global counter (e.g., a strongly consistent distributed counter service) before being allowed through.
    • Trade-off: synchronous global coordination gives exact enforcement (never overshoot) but adds a cross-region network round trip to every single request’s critical path — for a customer whose traffic originates far from wherever that global counter service lives, this could add 100ms+ of pure network latency, unacceptable against the <5ms rate-limit-overhead target, and creates a single global dependency whose outage or slowdown affects request handling everywhere. The async local-share model sacrifices perfect exactness (bounded overshoot possible during the rebalancing lag window) for near-zero added latency and no single point of failure — this is the standard, deliberate trade-off virtually all large-scale global rate limiters make, and should be explicitly named as an eventual-consistency choice in the interview.
  2. Adaptive/dynamic regional share rebalancing vs. static even-split allocation.

    • Chosen: each region’s local share of a customer’s global limit is continuously adjusted based on observed real traffic distribution for that customer (a customer sending 90% of traffic to one region gets ~90% of their budget allocated there), rather than a fixed even split across all regions.
    • Alternative: statically split the global limit evenly (or by a fixed configured ratio) across regions, never adjusted.
    • Trade-off: static even-split is simple but badly wastes quota for customers with geographically concentrated traffic (a customer only ever calling the US region would have their EU/APAC shares permanently idle while potentially getting throttled in US despite having “room” in their global limit sitting unused elsewhere) — effectively under-serving customers relative to their contracted limit. Adaptive rebalancing fixes this at the cost of needing a continuously running aggregation/redistribution process and careful tuning of the rebalancing interval and smoothing (too-fast rebalancing can oscillate under bursty traffic; too-slow rebalancing under-reacts to genuine regional traffic shifts).
  3. Token bucket (or sliding-window) algorithm per region vs. fixed-window counters.

    • Chosen: token bucket (or a sliding-window-log/sliding-window-counter hybrid) algorithm for local rate limiting, allowing smooth, burst-tolerant enforcement.
    • Alternative: simple fixed-window counters (e.g., reset a counter every 60 seconds).
    • Trade-off: fixed windows are trivial to implement but suffer the well-known boundary-burst problem — a customer can send their full limit right at the end of one window and their full limit again right at the start of the next, achieving effectively 2x their intended rate in a short span around the window boundary. Token bucket / sliding window avoids this at modest additional implementation complexity (need to track more than a single integer counter — either a timestamp-weighted bucket or a rolling log), which is well worth it given rate limiting’s entire purpose is protecting against abuse/overload that boundary-gaming would directly undermine.
  4. Optimistic reservation + post-hoc reconciliation for token-based (TPM) limits, since true cost is only known after generation completes.

    • Chosen: at request time, reserve an estimated token cost against the customer’s bucket (based on prompt token count plus the requested max_tokens parameter, typically using max_tokens as a conservative upper-bound estimate, or a statistically-informed estimate if max_tokens isn’t set); once generation completes and actual output token count is known, reconcile — refund the difference if actual usage was lower than reserved, or apply the true cost if using a more relaxed estimate that undershot.
    • Alternative: only count tokens after the fact (post-paid), doing no request-time reservation at all.
    • Trade-off: pure post-hoc counting with no reservation allows a burst of concurrent long-running requests to all be admitted simultaneously (each individually under the limit at admission time) and collectively blow far past the TPM budget once they all complete around the same time, since nothing was reserved to prevent over-admission — a real risk given LLM generation latency can be seconds long, plenty of time for many requests to stack up. Optimistic reservation with max_tokens as the conservative estimate prevents this over-admission risk but can under-utilize quota when max_tokens is set conservatively high relative to typical actual usage (reserving more than usually needed) — mitigated by the reconciliation refund step and by encouraging/defaulting reasonable max_tokens values.
  5. Bounded overshoot tolerance as an explicit, monitored SLA vs. attempting zero-overshoot.

    • Chosen: the platform explicitly defines and monitors a maximum acceptable overshoot bound (e.g., no customer should exceed 120% of their contracted global limit even during worst-case rebalancing lag across all regions simultaneously bursting), derived mathematically from the rebalancing interval and number of regions, and treats this as a tested, documented property of the system rather than an accepted unknown risk.
    • Trade-off: chasing zero overshoot would require the synchronous global coordination rejected in decision #1; accepting and tightly bounding overshoot is the practical alternative, but it must be an intentional, quantified engineering decision (with real math backing the bound, and monitoring that verifies the bound holds in production) rather than a vague “eventually consistent, should be fine” hand-wave — this distinction matters a great deal in an architect-level interview.
  6. Enterprise/custom-tier customers get dedicated capacity and potentially region-pinned enforcement vs. the same shared multi-region pooling for all tiers.

    • Chosen: for the largest enterprise customers with heavily negotiated custom limits (and often dedicated infrastructure elsewhere in the platform, echoing the multi-tenant serving scenario), rate limiting may be simplified to per-region hard limits matching their contracted per-region capacity, rather than running them through the adaptive global-rebalancing machinery designed for the broader self-serve customer base.
    • Trade-off: this avoids applying complex, general-purpose adaptive logic to customers whose traffic patterns and contractual terms are already well-understood/negotiated (often literally with per-region capacity commitments in the contract), simplifying both their enforcement logic and their capacity planning, at the cost of maintaining two enforcement code paths (general adaptive pooling for the broad base, simpler static per-region for top enterprise accounts) — justified because the largest accounts’ behavior and blast radius warrant bespoke handling anyway.

Scale Math

  • 200,000 requests/minute aggregate peak across 4 regions ≈ 3,333 requests/sec average, higher instantaneous burst.
  • Local rate-limit check: in-memory/local-Redis token bucket read+decrement, sub-millisecond typically (well under the <5ms budget), leaving ample margin even after gateway overhead.
  • Rebalancing interval trade-off math: assume rebalancing every 200ms and 4 regions; worst-case overshoot bound ≈ (number of regions - 1) × (per-region burst allowed within one rebalancing interval) — e.g., if a customer’s global limit is 3,500 RPM (~58 RPS) and rebalancing lag is 200ms, the maximum “unaccounted” burst per region during one lag window is roughly limit × (lag/60s) ≈ 58 × 0.2 ≈ 12 requests per region; across 3 “other” regions simultaneously bursting undetected ≈ 36 extra requests, which is about 1% of the 3,500 RPM global limit for that interval — demonstrating the bound is small and tunable by shortening the rebalancing interval (at the cost of more aggregation traffic/overhead) or by reserving explicit headroom in each region’s allocation.
  • Aggregation traffic: each region streaming usage deltas every 100-500ms for, say, 10,000 active customers with non-trivial traffic — a few KB per batch per region, well within normal inter-region bandwidth budgets (this is control-plane traffic, not data-plane, so it tolerates being run over a less latency-sensitive path than customer requests).
  • Free-tier customers (60 RPM) at the low end: with only 1 request/sec average, the “local share per region” model needs a floor/minimum allocation per region (can’t meaningfully split 60 RPM into fractional per-region shares across 4 regions and still allow reasonable burst) — handled by giving low-volume customers a full local limit in every region initially (since their absolute overshoot risk in dollar/abuse terms is small) and reserving the adaptive-share machinery’s complexity for higher-volume customers where it actually matters.

Failure Modes & How They’re Handled

  • Aggregation/rebalancing service outage: regions stop receiving updated share allocations. Mitigated by regions continuing to enforce against their last-known allocation (fail static, not fail open or fail closed) — this is exactly why the design doesn’t require the aggregator for the request-path decision at all, only for keeping allocations optimally tuned; a stale allocation is a minor efficiency problem (a customer’s traffic shift not being reflected promptly), not a correctness or availability problem.
  • Region isolated/network-partitioned from others: Mitigated the same way — isolated regions keep enforcing against their last-synced local share; the bounded-overshoot math (decision #5) already accounts for a rebalancing gap, and an extended partition just means that gap grows, which should trigger alerting (rebalancing staleness monitor) even though it doesn’t break request handling.
  • Thundering herd at billing-cycle/quota reset boundary: many customers’ windows reset simultaneously, causing a traffic spike. Mitigated by jittering window boundaries per customer (based on customer ID hash) rather than a globally synchronized reset instant, spreading the reset-triggered traffic surge over time.
  • A single customer’s traffic pattern defeats the adaptive rebalancing (rapidly oscillating between regions, e.g., a mobile client roaming, or deliberate gaming attempts to exploit rebalancing lag): Mitigated with smoothing/hysteresis in the rebalancing algorithm (don’t fully react to a single interval’s traffic shift, use an exponentially weighted moving average of regional traffic share) and, if actual abuse is detected (deliberately splitting traffic across regions specifically to exploit the lag window), a fraud/abuse detection layer flags and can apply a stricter, more conservative global-sync fallback for that specific customer.
  • max_tokens-based reservation wildly overestimates true usage for a customer with many small-output requests, causing unwarranted false 429s despite real usage being well under limit: Mitigated by the reconciliation step continuously refunding over-reservations, and by tracking a per-customer historical actual-vs-estimated ratio to inform a smarter estimate (rather than blindly using max_tokens at face value) for customers with a stable, predictable usage pattern.
  • Local Redis/in-memory store failure within a region: rate limiting for that region’s traffic has no counter to check. Mitigated with a documented explicit policy choice (fail-open with a conservative default low limit applied via a fallback in-process counter, vs. fail-closed rejecting all traffic) — for a paid API platform, fail-open with tightened conservative limits is typically preferred over a hard outage, since it degrades gracefully (some risk of brief over-admission) rather than taking down the whole regional gateway.

Interviewer Follow-Up Q&A

Q: A customer complains they’re getting 429s despite being “well under” their global limit on their own dashboard — how do you debug this? A: This is the classic symptom of regional-share imbalance — their dashboard likely shows aggregated global usage (from the async aggregation layer, which is correct/eventually consistent), but their traffic is concentrated in a region whose local share hasn’t yet rebalanced to reflect that concentration (e.g., they just shifted a big batch job from EU to US-East and the US-East local allocation hasn’t caught up). Debugging path: check per-region local usage vs. per-region allocated share for that customer around the incident window; if there’s a clear imbalance correlated with a recent traffic-pattern shift, this confirms it’s a rebalancing-lag artifact, and the fix (beyond it self-correcting shortly) might be shortening the rebalancing interval for high-value customers or pre-provisioning a higher regional floor for known enterprise traffic patterns.

Q: Why not use a single globally-distributed strongly-consistent database (e.g., a Spanner-like system) for the counter, avoiding the whole eventual-consistency complexity? A: That’s a legitimate alternative and worth naming — a globally consistent database can provide exact global counting, but it does so by paying synchronous cross-region consensus latency on writes (which is exactly what decision #1 was designed to avoid on the request hot path), and even then you’d typically still want a local cache/batching layer in front of it for request-path performance, which reintroduces a version of the same lag/staleness trade-off one layer down. It’s a reasonable choice if the organization already operates such infrastructure reliably and the added tens-of-milliseconds write latency is acceptable, but it doesn’t eliminate the fundamental tension between consistency and low-latency local enforcement — it just moves where in the stack you pay for it.

Q: How would you handle a sudden legitimate massive burst from one customer (e.g., a large enterprise customer kicking off a huge batch job) — should the rate limiter treat this the same as abuse? A: Rate limiting and abuse detection should be distinct layers with different remedies — the rate limiter enforces the contracted limit regardless of intent (a burst beyond the limit gets 429’d or queued whether it’s legitimate or malicious, because the limit exists for capacity/fairness reasons independent of intent), but a legitimate large customer with predictable batch needs should be handled at the product/contract layer — e.g., a temporary limit increase requested and provisioned ahead of a known batch job, or a queued/throttled-but-not-rejected mode (202-style backpressure with retry-after guidance) for customers who prefer graceful throttling over hard rejection, which is often a better experience for large legitimate bursts than a wall of 429s.

Q: What happens to in-flight requests if a region needs to fail over to another region mid-outage — does rate-limit state transfer with them? A: Not synchronously — failed-over traffic lands in the surviving region(s) and is enforced against whatever local share that region currently holds, which likely doesn’t yet reflect the sudden traffic increase from the failed region’s former customers. This is an accepted, bounded-duration degradation (same overshoot-bound reasoning as normal rebalancing lag, just triggered by a bigger step change) rather than something requiring synchronous state transfer during an already-stressful failover event; the aggregation layer’s normal rebalancing loop catches up within a few intervals once the new traffic pattern stabilizes, and this behavior should be explicitly tested via failover drills, not assumed to work.

Q: How do you rate-limit fairly when different request types have wildly different costs (a tiny classification call vs. a huge long-context generation call) under the same RPM limit? A: This is precisely why most production LLM API platforms enforce both RPM and TPM simultaneously as separate, independently-tracked limits rather than RPM alone — RPM protects against raw request-count abuse/overhead (connection handling, routing cost per request), while TPM (using the optimistic-reservation-plus-reconciliation approach from decision #4) protects against the actual compute-cost variation between requests, since token count is a much better proxy for true backend cost than request count alone; a customer sending many cheap small requests and a customer sending few expensive large requests are governed by the dimension that actually reflects the resource they’re consuming.