Global Rate Limiter with Regional Distribution
System DesignModel answerLast updated
Design a rate limiting service that enforces API key quotas consistently across multiple geographic regions with low latency and partition tolerance.
You need to build a rate limiting service that operates across several data centers in different geographic locations (for example, Virginia, Frankfurt, and Singapore).
Your system must:
- Apply rate limits tied to API keys (such as 1,000 requests per minute per key), and support additional constraints like per-IP or per-endpoint limits
- Handle requests landing in any region while keeping the limit enforced globally—not separately per region
- Add minimal latency to the critical request path
- Continue operating when a region becomes unavailable
After presenting your design, consider this extension:
You're building a task scheduler that executes background jobs under rate limiting constraints. Compare two scheduling approaches:
A) Execute the highest-value tasks first (sorted by priority or business value)
B) Execute the maximum number of tasks (optimize for throughput)
Discuss the trade-offs and when each approach makes sense.
Hints
Hint 1
The fundamental constraint is that cross-region communication takes 70-250ms, but you need to decide in under 2ms whether to allow a request.
Hint 2
Think about how to distribute quota across regions dynamically based on where traffic actually arrives, rather than splitting it statically.
Hint 3
Consider what happens when regions can't communicate: should the system fail open (allow requests) or fail closed (reject them)?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Challenge
The central problem is that synchronous cross-region coordination is too slow. Round-trip time between regions is 70-250ms, but the rate limit check must complete in 1-2ms. Any viable design must make decisions locally while maintaining approximate global consistency.
State this constraint upfront—it shapes every choice that follows.
Clarifying Questions
Before designing, establish:
- Accuracy requirements: Is 5-10% temporary overshoot acceptable during traffic shifts? For abuse prevention, usually yes. For billing quotas, you'd need a separate accounting system.
- Scale: Assume 3-5 regions, 500K requests/second globally, 1M active API keys, with individual key rates from 10 to 10,000 req/s.
- Failure mode: Should the system fail open (allow traffic when unhealthy) or fail closed (reject everything)? For most API use cases, fail open is correct—blocking all traffic is worse than temporary overshoot.
- Cost model: Can requests have variable cost (e.g., expensive endpoints count as 10 units)?
API Design
The gateway calls the rate limiter with:
allow(
limits: [
{type: "api_key", value: "key_abc123"},
{type: "ip", value: "203.0.113.42"},
{type: "key_endpoint", value: "key_abc123:/v1/transactions"}
],
cost: 1
) -> {allowed: boolean, remaining: int, retry_after_ms: int}
Return 429 status with Retry-After and X-RateLimit-Remaining headers when denied.
Architecture Overview
Client → DNS/Anycast → Regional Gateway (in-process cache)
↓
Regional Redis Cluster
↓
Regional Aggregator ←→ Other Regions (gossip)
Approach comparison:
| Design | Accuracy | Latency | Partition Handling |
|---|---|---|---|
| Central Redis | Perfect | +150ms | Single point of failure |
| Static split (limit/N) | Conservative | <1ms | Works but wastes quota with uneven traffic |
| Local count + gossip | Bounded overshoot | <1ms | Degrades gracefully |
Recommended: Dynamic Quota Allocation
Each region maintains its own quota share and enforces locally. Here's how it works:
1. Regional enforcement: Each region has a Redis cluster holding token buckets for active keys: {tokens_available, last_refill_timestamp}. Token bucket allows bursts while maintaining average rate.
2. Quota distribution: Every 1-2 seconds, regional aggregators exchange observed demand for each active key. If a key has limit L and region Virginia sees 600 req/s while Frankfurt sees 400 req/s:
- Virginia gets 60% of L
- Frankfurt gets 40% of L
3. Lease-based safety: These allocations are leases with 5-second TTL. If a region stops responding, others reclaim its share after expiry.
4. Smoothing: Don't react instantly to demand changes—smooth over 10-30 seconds. Give each active region a minimum floor (5-10% of L) so sudden traffic shifts don't completely starve a region.
Error bound: Overshoot occurs only during traffic shifts and is bounded by (rate of shift × sync interval) / limit. With steady traffic, error approaches zero.
Optimization: Hot Path Performance
Most requests should never hit the network. Use local token batching:
- Gateway processes maintain in-memory token buckets for frequently used keys
- Pre-fetch tokens in batches from Redis (e.g., withdraw 50 tokens at once)
- 90%+ of checks stay in-process, reducing Redis load by 10× and latency to microseconds
Trade-off: slight unfairness across gateway instances, bounded by batch_size × num_instances.
Multi-Constraint Handling
To check both API key and IP limits atomically, use a Redis Lua script that:
- Refills all relevant token buckets
- Checks if all constraints allow the request
- Only decrements tokens if all pass
This prevents a request rejected for IP limit from consuming the API key quota.
Failure Modes
Redis unavailable in one region: Gateways fall back to in-process limiting at (quota_share / num_gateways). This is fail-open but still provides protection.
Region partitioned: Continues enforcing last known quota share, then gradually decays to safe minimum (L/N regions) which guarantees no global overshoot.
Entire region down: Traffic shifts via DNS. Other regions detect demand change within one sync cycle and redistribute quota.
Clock skew: Use Redis server time inside Lua scripts, not client timestamps.
Alternative: Hot Key Optimization
For keys well below their limit (most keys), skip coordination entirely. Only start quota negotiation when a key reaches 50% of its limit in any region. This reduces cross-region traffic by orders of magnitude while maintaining accuracy where it matters.
Storage and Configuration
- Limit configuration: Postgres replicated globally, cached in gateways. Schema:
(dimension, matcher, limit_per_window, burst, window_seconds)with tier defaults and customer overrides. - Counter state: Regional Redis, sharded by key hash, with TTL of 2× window duration to auto-clean inactive keys.
Scheduling Follow-Up
First clarify: does "weight" mean business priority or resource cost (tokens consumed)?
Strategy A: Highest Value First
Advantages:
- Maximizes business value when capacity is constrained
- Ensures premium or SLA-bound work completes first
- Large important jobs never starve
Disadvantages:
- Low-priority tasks may never execute if high-priority work keeps arriving
- Total throughput (number of tasks) may be lower
- Head-of-line blocking if big tasks take a long time
When to use: Customer-facing work with SLAs, real-time notifications, or revenue-generating tasks.
Strategy B: Maximum Throughput
Advantages:
- Completes the most tasks, good for batch processing and clearing backlogs
- Better cache efficiency if small tasks have locality
- Predictable completion metrics
Disadvantages:
- Important large tasks may sit in queue while trivial work executes
- Total business value may be low
- Can violate SLAs or customer expectations
When to use: Background cleanup, analytics jobs, or systems where all tasks have roughly equal importance.
Hybrid Approach
Real production systems often use weighted fair queuing: partition rate limit quota across priority bands (40% for high, 35% for medium, 25% for low), then apply throughput-maximizing within each band. This bounds starvation while preserving priority.
Another option: earliest deadline first for latency-sensitive workloads where each task has a deadline.
The right choice depends on whether you're optimizing for business value, user experience, or operational metrics like queue depth.