Building a High-Throughput Distributed Rate Limiter
System DesignModel answerLast updated
Design a multi-region rate limiting system that handles millions of requests per second with low latency while managing hot keys and partition failures.
You need to architect a distributed system that enforces rate limits on API traffic across a global infrastructure. The system evaluates incoming requests against configurable policies and decides whether to accept or reject them based on sliding time windows.
Context
Your organization runs high-traffic APIs serving millions of users. You need protection against abuse, resource exhaustion, and uneven load. The rate limiter must operate as part of the request path, making allow/deny decisions based on rules like "maximum 1,000 requests per minute per user" or "50 requests per second per IP address."
What You Need to Design
Your system should support:
Core Capabilities:
- Evaluate requests against multiple rule types simultaneously (by user ID, tenant, IP, endpoint)
- Return allow/deny decisions along with metadata (remaining quota, reset time)
- Apply updates to rate limit rules without restarting services
Performance & Reliability Targets:
- Handle 10 million decisions per second across all regions
- Keep decision latency under 5 milliseconds at p99
- Maintain 99.999% uptime
- Continue operating through node crashes, network splits, and sudden traffic surges
- Handle scenarios where a single identifier (hot key) receives disproportionate traffic
Key Design Areas to Address
Explain your choices for:
- Algorithm selection: Which rate limiting algorithm works best given memory and accuracy requirements?
- Distribution strategy: How do you partition state across machines and prevent load imbalance?
- Hot key handling: What happens when one user or IP generates extreme traffic that would overwhelm a single node?
- Latency vs accuracy: How do you achieve sub-5ms decisions while maintaining reasonably accurate counts across distributed nodes?
- Failure behavior: When components fail, should the system allow all traffic (fail open) or block it (fail closed)?
Discuss trade-offs explicitly and quantify your design where possible.
Hints
Hint 1
Making a remote call to check every request will consume your entire latency budget—consider where decisions actually happen
Hint 2
Perfect accuracy across distributed nodes requires synchronization that is too slow; small overshoot is usually acceptable
Hint 3
The hottest keys are often the ones already over their limit—caching denial decisions eliminates most hot key traffic
Hint 4
Consistent hashing distributes keys uniformly but not load uniformly; you need additional techniques when one key dominates
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Building a High-Throughput Distributed Rate Limiter
The central challenge is achieving both high throughput and low latency. A naive approach that synchronously queries a central database on every request immediately fails: at 10M QPS with even 1ms database latency, you would need enormous resources and still risk hot key bottlenecks.
A strong solution recognizes that decisions should happen locally with asynchronous state coordination.
Step 1: Establish Scale and Constraints
Start by clarifying the parameters:
- Accuracy tolerance: Can limits be approximate? For most use cases, 5-10% overshoot is acceptable. Critical flows like authentication might need stricter enforcement.
- Deployment model: The limiter should run embedded in API gateways or as a co-located sidecar. An external service would waste the entire latency budget on network hops.
- Scale breakdown:
- 10M global QPS across 5 regions = ~2M QPS per region
- Approximately 100M distinct rate limit keys (users, IPs, tenants)
- Each key stores ~100 bytes (counters, timestamps, metadata) = 10GB total per region
- Each request might trigger 2-4 rule checks (per-user, per-IP, per-tenant, per-route), so ~25-30M effective checks per second per region
- Durability: Counter state is ephemeral. If lost, the system temporarily over-admits until it rebuilds, which is acceptable.
Step 2: Choose the Right Algorithm
Different algorithms have different memory and accuracy characteristics:
| Approach | Memory per Key | Accuracy | Assessment |
|---|---|---|---|
| Fixed window | Single counter | Allows 2× burst at boundaries | Too imprecise |
| Sliding log | Store all timestamps | Perfect | 1,000+ timestamps per key = prohibitive memory |
| Sliding window counter | Two counters | 1-5% typical error | Best for time-windowed limits |
| Token bucket | Token count + refill timestamp | Exact for rate+burst | Best for per-second burst scenarios |
Sliding window counter works by maintaining current and previous window counts:
weighted_count = prev_window_count × (time_remaining_ratio) + current_window_count
decision = weighted_count + request_cost <= limit
This approximates a true sliding window with O(1) memory and the error stays bounded. Crucially, counters are additive, meaning you can merge partial counts from different sources—essential for distributed aggregation.
Per-key data structure:
{
window_start_ms: timestamp,
current_count: integer,
previous_count: integer,
ttl: 2 × window_duration
}
Step 3: Architecture Overview
Request → API Gateway
├─ Local rule cache
├─ Local counter aggregator
├─ Verdict cache (especially denials)
└─ Decision logic (microsecond latency)
↓ (async batch sync every 50-100ms)
Regional counter store (Redis-like, in-memory)
↓ (async CRDT replication every 500ms-1s)
Other regional counter stores
Partitioning approach:
- Use consistent hashing with ~150 virtual nodes per physical machine
- This smooths out variance and limits remapping when nodes join/leave to approximately 1/N of keys
- Each partition maintains one replica for failover
- Capacity planning: a single node handling atomic counter updates via scripting can process ~150K ops/sec. Without optimization, 30M checks would require 200+ nodes—but batching reduces this dramatically.
Step 4: Solving the Latency Problem
Three strategies exist on a spectrum:
Option A: Synchronous per-request check Every request executes an atomic increment against the counter store. Provides exact counting but adds 1-2ms per request plus tail latency variance. Suitable only for low-volume critical rules (fraud prevention, authentication attempts).
Option B: Local counting with periodic synchronization Each gateway maintains local counters and flushes deltas every 50-100ms. It pulls back global state and makes local decisions.
- Latency: sub-millisecond
- Worst-case overshoot:
number_of_gateways × per_gateway_rate × sync_interval - Example: 100 gateways × 1000 req/s × 0.1s = 10,000 extra requests possible
Option C: Token leasing (recommended default)
Each gateway requests quota chunks from the store: min(estimated_share, 10% of limit). It consumes quota locally and renews at ~50% depletion. Unused tokens expire with the window.
- Overshoot bounded by lease size
- Store write load proportional to lease renewals, not request volume
- Provides good balance of accuracy and performance
Recommendation: Use token leasing (C) as the default with synchronous checks (A) for strict enforcement rules.
Step 5: Hot Key Mitigation
Consistent hashing distributes keys evenly but not load evenly. A single viral event or DDoS target still maps to one shard. Layered defenses:
Layer 1: Cache denial decisions
Once a key exceeds its limit, cache {key: DENY, until: reset_timestamp} at the gateway. Rejected traffic never reaches the backend store. This single technique eliminates most hot key problems since the hottest keys are typically those already over quota.
Layer 2: Larger lease sizes For high-volume allowed traffic, gateways request proportionally larger quota chunks, reducing write frequency to the backend.
Layer 3: Hot key detection and splitting
- Run streaming top-K tracking (count-min sketch) on each shard with 1-second windows
- Flag keys consuming >5% of a shard's operations
- Split hot keys into sub-keys:
{original_key}#0through{original_key}#N-1 - Each sub-key holds
limit/Nquota and hashes to different nodes - Pin each gateway to one sub-key via
hash(gateway_id) mod N - Background process rebalances quota between sub-keys and merges them when traffic normalizes
Layer 4: Upstream defenses Deploy rate limiting at edge layers (CDN, L4 load balancers) to handle volumetric attacks before they reach application logic.
Step 6: Multi-Region Coordination
For globally enforced limits:
- Each region maintains its portion as a slot in a CRDT G-counter
- Regional counters replicate asynchronously (500ms-1s intervals)
- Each region receives a budget share proportional to its recent traffic patterns
- A coordinator rebalances unused quota between regions each sync cycle
- Overshoot bounded by:
cross_region_lag × request_rate
For a 1-second sync lag at 10K req/s, expect ~10K potential overshoot globally—usually acceptable for large limits.
Step 7: Failure Modes and Degradation
Node failure: Replica takes over immediately via health checks. Keys on the failed node are temporarily unavailable (~1s until remap) but gateways can operate on cached state or leased quota.
Network partition: Configure per-rule failure behavior:
- Fail open (default): Allow requests when the counter store is unreachable. Prevents rate limiter from becoming a single point of failure.
- Fail closed: Deny requests. Use for security-critical rules.
Store capacity exceeded: Implement load shedding by priority. Protect authentication and payment limits first, then tenant limits, then IP-based limits.
Configuration updates: Store rules in a coordination service (etcd, Consul). Gateways watch for changes and apply updates atomically in memory, achieving updates in seconds without restarts.
Common Mistakes
- Synchronous remote calls on hot path: Consumes entire latency budget
- No hot key strategy: Single popular key overwhelms one node
- Ignoring cache denial: Rejected traffic shouldn't touch the backend
- Perfect accuracy assumption: Distributed systems require trading some precision for latency
- Ignoring failure modes: Rate limiters should never be the reason APIs go down
Complexity Analysis
- Latency: O(1) local decision with microsecond timescale
- Storage: O(K) where K is number of active keys, approximately 10GB per region
- Network: O(G) writes per sync interval where G is number of gateways, typically 10-100KB/s per gateway
- CPU: Negligible—dominated by gateway's primary request processing
This architecture achieves the required 10M QPS at sub-5ms latency while gracefully handling hot keys, failures, and distributed enforcement.