Design a Low-Latency Distributed Rate Limiting System
System DesignModel answerLast updated
Architect a high-performance, multi-tenant rate limiter capable of enforcing global traffic quotas across millions of requests per second with sub-5ms response times.
Architect a scalable, distributed rate-limiting infrastructure for a multi-tenant platform. The service must sit inline with request processing and enforce complex rate policies across global regions without introducing significant latency.
Core Requirements
- Multi-Tenancy & Custom Rules: Support customizable rules per client or endpoint (e.g., limits by IP, User ID, or API Key; fixed window or burst controls; soft limits vs. hard blocks).
- Ultra-Low Latency: Process rate-check evaluation in under 5ms at the 99th percentile ($p99$).
- High Throughput: Handle millions of requests per second (RPS) distributed across global data centers.
- Controlled Accuracy vs. Availability: Provide configurable trade-offs between exact quota enforcement (strict consistency) and high availability (eventual consistency/local estimation).
Expected Discussion Points
- Overall System Architecture: How application proxies/sidecars coordinate with local and regional rate-limiting nodes.
- Data Storage & State Management: How state is partitioned, cached, and updated across data centers without global synchronous locks.
- Algorithm Selection: Choosing appropriate algorithms (e.g., Token Bucket, Generic Cell Rate Algorithm, Sliding Window) tailored to local leasing and memory bounds.
- Resilience Strategy: Behavior under network partitions, regional outages, or control plane failures (fail-open vs. fail-closed dynamics).
Hints
Hint 1
Consider how local caching and token leasing reduce cross-datacenter round-trips to achieve sub-5ms latencies.
Hint 2
Think about how the choice of rate-limiting algorithm affects memory requirements and the ability to split quotas across distributed nodes.
Hint 3
Distinguish between security-critical rules (e.g., login attempts) and high-volume data APIs when deciding between fail-open and fail-closed strategies.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture & Core Strategy
Enforcing a global rate limit by making synchronous, cross-datacenter calls on every request is impossible within a sub-5ms latency budget. Cross-region network round-trips take anywhere from 30ms to 150ms. Therefore, the core architectural principle of this system is hierarchical quota delegation (leasing) combined with local execution.
+------------------------+
| Control Plane / Rules |
| (etcd / Spanner DB) |
+-----------+------------+
| Config Sync
v
+----------------------------------+
| Global Coordinator (Background) |
| Re-balances quotas across regions|
+-----------------+----------------+
^
Sync Metrics | Push Quota
(1-5s interval| Allocation
v
+------------------------------------------+
| Regional Tier |
| (Stateless Frontend + In-Memory Shards)|
+---------------------+--------------------+
^
Batch Acquire | Lease Response
(Lease Sync) |
v
+-------------------------------------------------------------------+
| Client Tier |
| +-------------------------------------------------------------+ |
| | Request -> Gateway / Envoy Sidecar (Local Token Bucket) | |
| +-------------------------------------------------------------+ |
+-------------------------------------------------------------------+
The system operates across three tiers:
-
Client Tier (Sidecar / API Gateway):
- Embedded directly alongside application services (e.g., as an Envoy filter or SDK).
- Evaluates rate limits in microseconds using locally held token leases.
- Infrequently contacts the Regional Tier to refill its local lease buffer.
-
Regional Tier (Datacenter Cluster):
- An in-memory, sharded cache cluster (e.g., Redis cluster or custom Go/C++ service using consistent hashing).
- Handles aggregate counts for a single region (latency ~0.5ms–1ms).
- Provides token batches (leases) to edge sidecars.
-
Global Coordinator Tier:
- Runs asynchronously out of the request path.
- Collects usage telemetry from all regions every 1 to 5 seconds.
- Adjusts regional quota allocations based on real-time traffic demand (dynamic quota rebalancing).
Data Model & Rule Configuration
Rule Schema
Rules are defined in a central configuration store (e.g., etcd or transactional DB) and streamed down to edge sidecars and regional nodes.
{
"rule_id": "rule_user_write_v1",
"tenant_id": "payment_service",
"selector": "headers['X-API-KEY']",
"algorithm": "TOKEN_BUCKET",
"capacity": 1000,
"fill_rate_per_sec": 100,
"soft_limit_threshold": 0.80,
"mode": "RELAXED",
"fail_strategy": "FAIL_OPEN"
}
In-Memory State Schema
To keep storage footprint low (~64 bytes per key), state is kept as soft state in memory. For 100 million active keys, the global memory footprint is under 10 GB, easily fitting within modest memory clusters.
State representation for Token Bucket / GCRA:
key:hash(tenant_id, rule_id, target_identifier)tokens:float64(remaining count)last_updated_at:int64(Unix timestamp in nanoseconds)version:uint32(for concurrency control)
Algorithm Selection
| Algorithm | Pros | Cons | Design Fit |
|---|---|---|---|
| Token Bucket / GCRA | $O(1)$ space, lazy updates, supports bursts, highly batchable via token leasing. | Slightly complex local lease math. | Primary Choice |
| Fixed Window | Extremely low memory overhead. | Double-limit burst spikes at boundary turns. | Backup for simple global limits. |
| Sliding Window Counter | Prevents boundary burst issues. | Difficult to partition into distributed batch leases. | Good for long time windows (e.g., daily quotas). |
| Sliding Log | Perfectly accurate. | $O(N)$ memory cost per request; unscalable at millions of RPS. | Rejected. |
Preferred Choice: Generic Cell Rate Algorithm (GCRA) / Token Bucket
Token Bucket is selected because tokens represent discrete units of execution that can easily be fragmented and leased.
With lazy evaluation, token replenishment does not require background timers: $$\text{tokens}{\text{new}} = \min(\text{capacity}, \text{tokens}{\text{old}} + (\text{now} - \text{last_updated}) \times \text{fill_rate})$$
GCRA optimizes this further by representing state using a single variable—Theoretical Arrival Time (TAT)—enabling lock-free atomic compare-and-swap (CAS) updates in memory.
Consistency vs. Throughput: Adaptive Token Leasing
To guarantee sub-5ms response times while handling 5M+ RPS, the system supports two operational modes depending on tenant requirements:
1. RELAXED Mode (High-Throughput / Local Leasing)
Sidecars acquire token leases from the Regional Tier. A lease grants a block of tokens (e.g., 500 tokens or a 100ms supply) to the local instance.
- Request Path: Executed 100% locally against sidecar memory (~50 microseconds).
- Lease Refill: When local tokens drop below a low-water mark (e.g., 20%), the sidecar asynchronously requests another lease block.
- Accuracy Trade-off: Maximum theoretical overshoot is bounded by: $$\text{Max Overshoot} \le \sum (\text{Active Sidecars} \times \text{Lease Size}) + (\text{Sync Delay} \times \text{Global Rate})$$
- Adaptive logic automatically shrinks lease sizes for low-volume keys and expands them for high-volume keys.
2. STRICT Mode (High-Consistency / Direct Check)
For security-critical boundaries (e.g., /api/v1/login or payment authorization):
- Leasing is bypassed.
- The sidecar performs a synchronous, atomic reservation call directly against the Regional Tier cluster.
- The global limit is statically partitioned across regions, ensuring zero over-commit at the cost of slight regional quota rigidity.
Resiliency & Edge Cases
Hot Keys
If a single API key generates 200,000 RPS, a single regional Redis node or sidecar thread could become overloaded.
Mitigation:
- Local Consolidation: High-volume keys naturally amortize load because sidecars request large token leases, resulting in very few network RPCs relative to request volume.
- Key Sharding: Sub-divide the hot key into $K$ virtual keys (
key_1,key_2, ...,key_K) across different storage shards, assigning fractional rates ($\text{rate} / K$) to each shard.
Cache Eviction & Cold Starts
If state for an active key is lost or evicted from memory:
- Initialization Strategy: Initialize the state conservatively at a fraction of maximum capacity (e.g., 50% capacity instead of 100%). This prevents "burst abuse" right after failovers or service restarts.
Network Partitions & Failure Handling
The sidecar enforces failure strategies specified per rule:
-
FAIL_OPEN (Default for General APIs):
- If the regional rate-limiter cluster is unreachable within a 2ms timeout, allow the request.
- Fall back to a localized fallback rate limit: $$\text{Local Fallback Limit} = \frac{\text{Global Limit}}{\text{Estimated Pod Count}} \times \text{Safety Factor}$$
- Prevents an outage in the rate-limiting infrastructure from bringing down downstream applications.
-
FAIL_CLOSED (Default for Security/Financial APIs):
- If the rate limiter is unreachable, deny the request (
HTTP 429orHTTP 503). - Essential for preventing brute-force authentication attacks or financial double-spending.
- If the rate limiter is unreachable, deny the request (
Summary Metrics & Latency Profile
- Decision Latency:
- Local Lease Hit (RELAXED): < 0.1 ms ($p99$)
- Regional Cache Hit (STRICT): ~1.5 ms ($p99$)
- Memory Footprint: ~6.4 GB per 100 million active key states.
- Network Overhead: < 1% of total incoming requests trigger an RPC call to the regional rate-limiting tier when utilizing dynamic leasing.