Building a Distributed Rate Limiting System at Scale
System DesignModel answerLast updated
Design a multi-region rate limiting system handling millions of requests per second with multiple limit dimensions and low latency.
You need to design a distributed rate limiting system that operates across multiple geographic regions and can handle approximately 10 million requests per second during peak traffic. The system must enforce rate limits across several dimensions simultaneously and maintain low latency on the hot path.
Functional Requirements
Your rate limiter must support:
- Multiple limit dimensions: individual user limits, per-endpoint limits, combined user-and-endpoint limits, and system-wide capacity limits
- Burst handling: allow short bursts of traffic above the steady-state rate
- Window semantics: approximate a continuous sliding window rather than fixed time buckets
- Retry signaling: provide accurate retry-after timing when requests are rejected
Non-Functional Requirements
- Throughput: sustain 10M requests/second across all regions
- Latency: add less than 1ms overhead (p99) to request processing
- Accuracy: bounded overshoot is acceptable for most use cases; a small subset of limits requires strict enforcement
- Availability: handle node failures, network partitions, and regional outages gracefully
What to Cover
Design and justify your approach for:
- Algorithm selection — choose the enforcement mechanism and explain how it provides burst tolerance and smooth rate limiting
- System architecture — describe component responsibilities and how decisions are made with minimal latency
- Data distribution — explain how you partition state across nodes and handle skewed access patterns
- Storage technology — select appropriate storage for different data types and justify throughput feasibility
- Consistency model — define what guarantees you provide and how you bound inaccuracy
- Failure handling — specify behavior during partial failures and how you prevent both over-blocking and under-limiting
- Fair allocation — ensure equitable resource distribution across users and regions
- Capacity planning — calculate resource requirements and explain how the system scales with traffic growth
- Monitoring — identify the key signals needed to operate the system
Provide concrete numbers, discuss trade-offs, and explain reasoning behind major decisions.
Hints
Hint 1
At 10M requests/second, making a network call for every rate limit check is not feasible—consider how to make decisions locally.
Hint 2
Leasing budgets for time periods allows local decision-making while maintaining coordination for shared limits.
Hint 3
Hot keys like global limits need special handling since they cannot be trivially sharded across nodes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Distributed Rate Limiting Architecture
Core Insight
The fundamental constraint is throughput: at 10 million requests per second, we cannot afford a remote call per request. The answer is to make rate limit decisions locally using in-process state, while coordinating budget allocation off the critical path through a leasing mechanism.
1. Algorithm Selection: Token Bucket (GCRA)
I'll use the Generic Cell Rate Algorithm (GCRA), which is mathematically equivalent to a token bucket but requires only a single timestamp per key.
Why token bucket over alternatives:
- Leaky bucket queues requests, adding latency with no burst tolerance
- Fixed windows cause boundary effects (double traffic at window edges)
- Token bucket allows controlled bursts while enforcing long-term rate
GCRA mechanics:
- Store one value: TAT (theoretical arrival time)
- Emission interval:
T = 1/rate - Burst capacity:
τ = (burst - 1) × T - On request at time
now:- New TAT =
max(current_TAT, now) + T - Allow if
new_TAT - now ≤ τ + T - Deny with
Retry-After = new_TAT - τ - T - now
- New TAT =
This provides continuous sliding-window behavior: any time interval of length t admits at most burst + rate × t requests.
2. System Architecture
Three-tier design:
Tier 1: Edge Decision Layer
- API gateways run an in-process rate limiter library
- Hold local GCRA buckets for recently accessed keys (LRU cache, ~100k entries per host)
- Most checks are pure in-memory: hash lookup + arithmetic (~200ns)
- For cache misses on low-traffic keys: synchronous coordinator call (~1ms acceptable)
Tier 2: Regional Coordination Layer
- Sharded services that own authoritative token budgets
- Grant time-bound leases to edge nodes requesting budget
- Track active leases and refresh grants based on consumption patterns
- Typical lease duration: 500ms to 2s
Tier 3: Global Allocation Layer
- Used only for cross-region and global limits
- Periodically (every 2-5 seconds) redistributes total budget across regions
- Uses demand signals to allocate capacity where needed
Request flow:
- Gateway checks local bucket → most requests complete here
- When local tokens run low, async lease renewal starts
- Renewal never blocks requests (renew at 50% consumed)
- For strict keys, synchronous coordinator check
This reduces coordination to ~1-2% of request volume.
3. Data Model
Policy configuration:
{
policy_id, version,
dimensions: [user|endpoint|user_endpoint|global],
rate_per_second, burst_size,
consistency: eventual|strict,
failure_mode: open|closed|conservative
}
Runtime bucket state (64 bytes):
{
key_hash,
tat_nanoseconds,
configured_rate,
configured_burst,
leased_tokens_remaining,
lease_expiry,
epoch_number,
owner_shard
}
4. Sharding and Hot Key Handling
Partitioning: Consistent hashing with 256 virtual nodes per coordinator plus bounded-load balancing (cap any node at 1.25× average load).
Hot key strategies:
Key splitting: Divide hot keys into sub-keys (e.g., global_limit#0 through global_limit#15), each with rate/N. Edge nodes hash themselves to a sub-key for locality.
Dynamic detection: Coordinators track lease request frequency; when a key exceeds ~10k leases/second, automatically increase split factor.
Batched leasing: For truly global limits, batch lease requests from multiple edge nodes into single coordinator operations.
5. Storage Choices
| Component | Technology | Reasoning |
|---|---|---|
| Active buckets | In-process memory at edges | Nanosecond access, 3GB per region |
| Coordinator state | Custom in-memory service with optional WAL | 100K+ ops/sec per shard needed |
| Policy config | etcd or similar, pushed via watch | Small, versioned, strongly consistent |
| Metrics | Stream to Kafka → analytical DB | High write volume, query infrequently |
Why not Redis for hot path:
- At 4 dimensions per request: 40M ops/second needed
- Redis Lua scripts: ~100K ops/sec per shard = 400+ shards
- Network RTT adds 0.5-1ms to every request
- Single-threaded shards cannot handle hot keys
Redis is viable for the small subset of strict-consistency keys.
6. Consistency Model
Regional eventual consistency:
- Admitted requests ≤
regional_budget + outstanding_leases - Overshoot bounded by lease sizing: typically 5-10% of rate
- Achieved by setting lease sizes to
rate × lease_duration / sqrt(active_leaseholders)
Global soft limits:
- Overshoot bounded by:
(1 + ε) × global_limit + Σ stale_regional_shares - Reallocation lag typically 2-5 seconds
- Practical overshoot under 20% during rapid traffic shifts
Strict enforcement (minority of keys):
- Use single-writer Raft group in home region
- Synchronous check-and-consume with linearizability
- Accept 50-150ms cross-region latency for this tier
7. Failure Modes
Coordinator unavailable:
- Edge nodes continue with current lease until expiry
- After expiry, fall back based on policy:
- Conservative: use last-known rate × 0.8
- Open: allow with no limit (availability-critical endpoints)
- Closed: deny all (abuse prevention)
Edge node crash:
- Unreturned tokens expire naturally at lease boundary
- Bounded waste: at most
leased_tokensper crashed node
Network partition:
- Regional split: continue operating within region
- Cross-region split: each region operates independently with its allocated share
Idempotency: Accept optional request_id to deduplicate retries within a time window.
8. Fairness
Cross-user fairness: Natural from per-user buckets; no single user can starve others.
Cross-region fairness for global limits: Use demand-proportional allocation with min-max fairness:
- Collect demand signals (denied_requests, lease_exhaustion_rate)
- Allocate using water-filling: give each region
min(demand, fair_share), distribute surplus to regions with remaining demand - Update every reallocation cycle (2-5s)
9. Capacity Planning
Single edge host capacity:
- 200ns per check × 4 dimensions = 800ns
- Single core: ~1M checks/second
- 16-core host: ~10M checks/second (with contention factor ~0.7)
Baseline deployment (10M RPS):
- Edge: 10 hosts (N+2 redundancy)
- Coordinators: 100M keys / 10M per shard = 10 shards × 3 replicas = 30 hosts
2× traffic spike:
- Edge: double to 20 hosts (autoscale on CPU >60%)
- Coordinators: same host count, lease size adjusts dynamically
- Watch: lease grant latency, token exhaustion rate
Backpressure: When coordinators are overloaded, extend existing leases with smaller grants rather than denying renewals.
10. Observability
Key metrics:
requests_checked,requests_allowed,requests_deniedby policy, dimension, regioncheck_latency_p50/p99/p999lease_renewal_latency,lease_grant_rate,lease_exhaustion_rateovershoot_ratio= actual_admitted / configured_limitcoordinator_cpu,edge_cache_hit_rate
Critical alerts:
- Check latency p99 > 5ms
- Lease renewal failures > 1%
- Overshoot > 30% for strict policies
- Coordinator unavailable
Distributed tracing: Sample 0.1% of requests with full dimension evaluation path.
Trade-offs Summary
- Eventual consistency for throughput and latency vs. strict accuracy
- Lease-based coordination for local decisions vs. coordination overhead
- Memory footprint (~5GB per region) vs. per-request network calls
- Regional autonomy vs. tight global enforcement
- Hot key splitting for scale vs. individual bucket accuracy
This design achieves the required 10M RPS with sub-millisecond latency while providing practical rate limiting with bounded inaccuracy.