Building a Global Rate Limiting System
System DesignModel answerLast updated
Design a low-latency rate limiting system that enforces usage quotas across distributed API gateways while maintaining availability and handling failures gracefully.
Problem Context
You're building a rate limiting system for a globally distributed API platform serving machine learning inference requests. The system must protect backend resources while enforcing per-customer usage policies across multiple regions without introducing significant latency.
Your Task
Design a rate limiting solution that operates within these parameters:
What the System Must Do
- Limit requests based on different identifiers: API keys, user IDs, and source IP addresses
- Support multiple time windows (per-second, per-minute quotas)
- Provide standard feedback through HTTP headers (
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset) - Return HTTP 429 status with retry information when thresholds are exceeded
- Allow configurable behaviors: reject immediately, queue briefly, or fail open/closed during outages
Performance & Scale Targets
- Latency: Add less than 5ms overhead at p99
- Availability: System failures must not block API traffic
- Throughput: Support 100,000 requests/second globally
- Scale: Manage 5 million active rate limit policies
- Geography: Three regions (US East, US West, Europe)
Expected Design Elements
Your design should address:
- Algorithm choice: Evaluate different rate limiting algorithms for memory efficiency and precision
- Storage architecture: Select appropriate datastores and explain how atomic updates work
- Cross-region coordination: Show how global limits work without cross-region latency on each request
- Fault tolerance: Describe behavior during datastore outages, network splits, and traffic surges
Hints
Hint 1
Consider algorithms that work with constant memory per limit rule rather than storing individual request timestamps
Hint 2
Think about how to partition quota allocation across regions so local checks remain fast
Hint 3
Design for the common case where the datastore is healthy, but have a fallback that maintains some protection when it's not
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Understanding the Scale
Let me translate requirements into concrete numbers that will drive design decisions.
Request volume: 100k requests/second globally means roughly 33k RPS per region. Since each request gets checked against multiple policies (API key + user + IP), we're looking at approximately 300k rate limit checks per second across all regions.
Memory footprint: With 5 million active policies, storing minimal state (token count and timestamp) at ~100 bytes per policy including overhead gives us ~500 MB to 1 GB — easily fits in memory-based storage.
Latency constraints: Our 5ms budget is tight. In-region cache access takes 0.5-1ms, but cross-region calls take 60-150ms. This means every request must be decided locally — we cannot afford synchronous cross-region coordination.
Availability priority: The API must stay up even if rate limiting infrastructure fails. Approximate enforcement is acceptable; perfect accuracy is not required.
2. Algorithm Selection
Let me compare the main options:
Fixed window counters are simplest but allow double the limit at window boundaries (one burst at the end of window N, another at the start of N+1).
Sliding window logs store every request timestamp for exact counting. For a 1000 RPM limit across 5M keys, this means storing billions of timestamps — prohibitively expensive.
Sliding window counters use two buckets and interpolate between them. Memory-efficient and accurate, good when contracts specify "per calendar minute."
Token bucket is my recommended choice:
- Constant memory: just tokens remaining and last refill time
- Handles bursts naturally (important for interactive AI workloads)
- Supports variable costs (critical for token-based pricing)
- Lazy refill eliminates background timers
3. Core Architecture
Request → API Gateway (in-process limiter)
↓ batched, <1ms
Regional Redis Cluster (6-10 shards)
↓ async, every 100ms-1s
Cross-Region Coordinator
↓ config push
PostgreSQL (durable rule storage)
Storage choice: Redis cluster provides:
- Sub-millisecond latency for in-region access
- Atomic operations via Lua scripting
- Built-in replication and persistence
- Simple operational model
Atomic operations: A Lua script handles the entire check-refill-decrement cycle atomically:
-- Inputs: rate, capacity, current_time, request_cost
local state = redis.call('HMGET', KEYS[1], 'tokens', 'last_refill')
local tokens = tonumber(state[1]) or capacity
local last_refill = tonumber(state[2]) or current_time
-- Refill based on elapsed time
local elapsed = current_time - last_refill
tokens = math.min(capacity, tokens + (elapsed * rate / 1000))
-- Check and consume
local allowed = (tokens >= request_cost)
if allowed then
tokens = tokens - request_cost
end
-- Persist and set expiry
redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_refill', current_time)
redis.call('PEXPIRE', KEYS[1], ttl_ms)
return {allowed, math.floor(tokens)}
Redis executes Lua scripts atomically per shard, preventing race conditions between concurrent gateways.
4. Multi-Region Coordination Strategy
The core challenge: enforcing global quotas without cross-region synchronization on every request.
Approach: Regional quota allocation with local leasing
-
Quota distribution: A coordinator divides each key's global quota across regions based on recent traffic patterns. If 70% of a customer's traffic comes from US East, that region gets 70% of their quota allocation. Rebalancing happens every 5-10 seconds.
-
Local token leasing: For high-volume keys, gateways lease token batches from Redis and serve them from local memory with zero network overhead. A lease might be 10% of the per-second rate, expiring after 1 second. Unused tokens return to the pool at expiry.
-
Cold path for low-volume keys: Keys with infrequent requests skip leasing and check Redis directly — one in-region round trip still meets our latency budget.
-
Async reconciliation: Regions report consumption every 100ms. Regions running low can request redistribution of unused quota from others.
Accuracy trade-off: Maximum overshoot equals (lease size × number of gateways) + (one sync interval of traffic). We tune lease sizes per tier — enterprise customers get tighter limits with smaller leases; free tier gets looser enforcement.
5. Handling Clock Skew
Use Redis TIME command to get timestamps from the datastore rather than trusting gateway clocks. This provides a consistent time source per shard. When gateway timestamps are unavoidable, clamp elapsed time to prevent negative values.
6. Failure Modes and Degradation
Redis unavailable or slow:
- Implement circuit breaker with 2ms timeout
- Fall back to local in-memory buckets with quota divided by gateway count
- API continues serving with degraded accuracy rather than failing completely
Fail-open vs fail-closed policy:
- Fail open for authenticated paying customers — their service availability matters more than brief quota violations
- Fail closed for anonymous traffic, IP-based limits, and abuse-prone endpoints
- Independent backend protection (queue depth limits, load shedding) provides a second line of defense
Traffic spikes:
- Hot keys automatically trigger local leasing
- Cached denials for abusive IPs avoid touching Redis
- Hash tagging ensures related keys stay on same shard, but we monitor for hot shards and promote problem keys to aggressive local caching
Regional failure:
- Surviving regions retain their last quota allocations
- Coordinator redistributes the failed region's share after a timeout (30-60s)
- Local fallback buckets continue providing protection
7. Capacity Planning
Each Redis shard handles ~50-100k token bucket operations per second. For 100k checks/region, provision 8-10 shards per region (primaries plus replicas) giving 2-3× headroom.
8. Common Pitfalls to Avoid
- Synchronous cross-region calls: Destroys latency budget
- Thundering herd on cache miss: Use lease-based caching to prevent stampedes
- Ignoring clock skew: Causes undercounting or overcounting
- No fallback strategy: Single point of failure brings down the entire API
- Fixed equal quota splits: Wastes quota in low-traffic regions
9. Extensions for Complex Scenarios
Token-based metering (when cost known only after response):
- Reserve estimated tokens up front (prompt tokens + output estimate)
- Reconcile actual usage asynchronously
- Allow small overdraft buffer for estimation error
- Periodically settle accounts
Hierarchical limits (org + team + user):
- Check all levels in one Redis transaction using hash tags
- Short-circuit on first denial
- Track which limit was hit for observability
This design balances strict consistency requirements against operational reality: perfect global coordination is too slow, but pure local enforcement is too inaccurate. The leasing strategy hits the sweet spot for production systems.