Design a Scalable API Rate Limiter
System DesignModel answerLast updated
Architect a high-performance, distributed rate limiting system for an API gateway handling high-throughput, bursty traffic.
Design a distributed rate limiting system integrated into an API gateway layer.
System Requirements & Constraints
- Multi-dimensional Limiting: Support rate limits based on arbitrary keys (e.g., API key, user ID, client IP, or composite routes like
user_id + endpoint). - Flexible Rules: Support multiple concurrent limits per key (e.g., short-term burst limits like 50 requests/second alongside long-term quotas like 100,000 requests/day), with configuration varying by customer tier and endpoint.
- High Performance & Low Latency: Add no more than 1–2 ms of $p99$ latency overhead at a scale of 1M requests per second across a cluster of API gateways.
- Distributed Concurrency: Maintain strict correctness and thread safety across multiple stateless gateway instances without race conditions or over-admission during traffic spikes.
- Fault Tolerance & Reliability: Fail gracefully if the underlying storage tier (e.g., memory cache) suffers high latency or outages.
- Client Feedback: Provide informative HTTP headers and status codes on limit enforcement according to standard specifications.
Walk through your architecture, data structures, algorithms, concurrency management strategy, operational trade-offs, and failure handling mechanisms.
Hints
Hint 1
Consider how algorithm selection affects state memory footprint at scale (e.g., Token Bucket vs. Sliding Window Log).
Hint 2
Think about atomic operations in distributed caching systems to avoid read-modify-write race conditions.
Hint 3
How would you handle global enterprise keys handling 50k+ requests/sec hitting a single database shard (hot key problem)?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirement Clarifications & Scale Estimation
Functional Requirements
- Key Identification: Support arbitrary identifiers (
IP,User_ID,API_Token,(Token + Endpoint)). - Multi-Rule Evaluation: Single incoming requests can trigger multiple rule evaluations (e.g., 20 req/sec burst limit AND 10,000 req/day quota limit).
- Dynamic Configuration: Rules vary by endpoint and customer tier (Free, Tier 1, Enterprise) and update with minimal latency.
- Standardized Protocol: Return proper HTTP standard headers (
RateLimit-Limit,RateLimit-Remaining,RateLimit-Reset,Retry-After) and429 Too Many Requestson violation.
Non-Functional Requirements & Capacity Planning
- Throughput: Peak $1,000,000$ requests/second spread across 50–100 API Gateway instances.
- Active Keys: $\approx 10,000,000$ active keys per day.
- Latency Budget: $p99 \le 1\text{ ms}$ evaluation overhead.
- Availability: $99.999%$ availability. The rate limiter must not degrade gateway uptime.
Storage Estimation
Using a Token Bucket model stored in Redis:
- Data per key:
tokens(float, 8 B),last_updated_timestamp(64-bit int, 8 B), key metadata (~64 B). - Total memory per key $\approx 100\text{ bytes}$ including Redis key overhead.
- $10,000,000 \text{ keys} \times 100\text{ bytes} \approx 1\text{ GB}$ total RAM.
- Single Redis node capacity easily holds memory, but throughput requires sharding: at ~100k ops/sec per Redis primary shard, a 10–15 shard cluster provides ample headroom.
2. API Interface & Data Contracts
Internal Evaluation Interface
def check_rate_limit(request_context: RequestContext) -> RateLimitResult
class RequestContext:
user_id: str
client_ip: str
api_token: str
endpoint: str
method: str
cost: int = 1 # Standard request = 1, heavy operation > 1
class RateLimitResult:
allowed: bool
limit: int
remaining: int
reset_after_ms: int
retry_after_sec: int
matched_rule_id: str
3. Algorithm Evaluation
| Algorithm | Memory per Key | Accuracy / Window Boundary Behavior | Suitable For |
|---|---|---|---|
| Fixed Window Counter | $O(1)$ (1 integer) | Poor; allows up to $2\times$ burst at window boundaries. | Long-term daily/monthly quotas. |
| Sliding Window Log | $O(N)$ (stores every request timestamp) | Perfectly accurate. High memory overhead at scale. | Low-throughput, high-security endpoints. |
| Sliding Window Counter | $O(1)$ (2 integers) | Approximated via weighted overlapping windows. Low memory. | High-throughput steady rates. |
| Token Bucket / GCRA | $O(1)$ (1 float, 1 timestamp) | Exact burst limit control; smooth continuous refill. | Recommended core rate limit algorithm. |
Recommendation: Token Bucket via Generic Cell Rate Algorithm (GCRA)
We use Token Bucket for short-term per-second rate limits because it naturally handles legitimate burst traffic while capping long-term consumption.
For longer time horizons (such as a 24-hour quota of 100k requests), a Sliding Window Counter or Fixed Window Counter minimizes tracking overhead.
4. High-Level Architecture
+-----------------------+
| Dynamic Config Sync |
+-----------+-----------+
|
v
[ Client ] ---> [ Load Balancer ] ---> [ API Gateway Node ]
| - Local LRU Cache
| - Evaluation Engine
+-----------+-----------+
| (Lua Script / Async batch)
v
+-----------------------+
| Sharded Redis Cluster|
+-----------------------+
- Rule Engine & In-Memory Config: Gateway nodes pull configurations asynchronously from a central Dynamic Config Store (e.g., via ETCD or Redis Pub/Sub).
- Key Synthesis: Upon request, the Gateway matches endpoint/tier rules and synthesizes key signatures (e.g.,
rl:{tenant_id}:{endpoint_hash}:1s). - Atomic Store Check: Gateway executes an atomic Redis operation against the key.
- Decision Enforcement:
- If Allowed: Attach headers (
RateLimit-Remaining, etc.) and route downstream. - If Exceeded: Immediately return HTTP
429with JSON body andRetry-Afterheader.
- If Allowed: Attach headers (
5. Concurrency Control & Atomic Execution
To prevent race conditions (two instances reading tokens=1 concurrently and both executing the request), rate updates must execute atomically inside Redis using a Lua script.
Atomic Token Bucket Lua Script
-- KEYS[1]: Rate limit key (e.g., 'rl:usr_123:search:1s')
-- ARGV[1]: Refill rate (tokens per millisecond)
-- ARGV[2]: Bucket capacity (max tokens / burst size)
-- ARGV[3]: Requested tokens (cost)
-- ARGV[4]: Current server timestamp (milliseconds)
local key = KEYS[1]
local refill_rate = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local requested = tonumber(ARGV[3])
local now = tonumber(ARGV[4])
-- Retrieve existing state
local data = redis.call('HMGET', key, 'tokens', 'last_updated')
local tokens = tonumber(data[1])
local last_updated = tonumber(data[2])
if not tokens then
-- Initial state: bucket is full
tokens = capacity
last_updated = now
else
-- Compute refilled tokens based on elapsed time
local delta = math.max(0, now - last_updated)
tokens = math.min(capacity, tokens + delta * refill_rate)
last_updated = now
end
local allowed = tokens >= requested
if allowed then
tokens = tokens - requested
end
-- Update key state and refresh expiration (TTL set to time required to fully refill)
local ttl_seconds = math.ceil((capacity / refill_rate) / 1000) * 2
redis.call('HMSET', key, 'tokens', tokens, 'last_updated', last_updated)
redis.call('EXPIRE', key, ttl_seconds)
-- Return: allowed flag (1/0), remaining tokens, reset delay in ms
local reset_delay_ms = math.ceil((capacity - tokens) / refill_rate)
return { allowed and 1 or 0, math.floor(tokens), reset_delay_ms }
Synchronized Time Source
The gateway passes the current time from the application or Redis's own TIME command to prevent host clock skew between stateless nodes from distorting token calculation.
6. Distributed Scalability Solutions
1. Redis Hash Tags for Multi-Limit Single Round-Trips
When evaluating multiple rules for a single incoming request (e.g., 1-second burst AND 1-day quota), pass all rules to Redis in a single Lua call. Use Redis Hash Tags (e.g., {user_123}:1s and {user_123}:1d) to ensure keys hash to the same cluster slot and evaluate in one network trip.
2. High-Throughput Hot Key Mitigation (Token Batching)
If a high-traffic tenant produces 50,000 req/sec, targeting a single Redis node causes a hotspot.
- Local Lease/Batching: The local Gateway instance reserves a batch of tokens (e.g., 50 tokens) at once from Redis.
- Requests consume from the gateway node's local memory.
- When local tokens drop below a threshold, the instance requests another batch.
- Trade-off: Reduces Redis network IO by 50×, with slight risk of under-utilizing overall capacity if gateway instances are unevenly balanced.
3. Multi-Region Deployment Model
For multi-region API deployments:
- Option A (Local Redis + Asynchronous Sync): Each region runs its own Redis cluster enforcing local sub-limits (e.g., total limit $N$ divided among $R$ regions). Best for sub-millisecond local performance.
- Option B (Global Key Local Cache): Enforce short-term rates locally in each region, and aggregate long-term daily quotas asynchronously via message queues (Kafka) to a global counter.
7. Resiliency & Failure Modes
When Redis experiences network partitions, slow operations, or failovers:
Circuit Breakers & Fallback Strategies
- Fail-Open Policy (Default): If Redis latency exceeds 5 ms or times out, bypass enforcement, log a metric, and let requests pass to preserve backend availability.
- Fail-Closed Policy: Use selectively for high-cost or security-sensitive routes (e.g.,
/api/v1/payments/charge,/api/v1/auth/login). - Local In-Memory Emergency Limiting: When the circuit breaker trips open, fallback to a local in-memory sliding counter per gateway node (e.g., bounded LRU cache using Guava/Caffeine).
8. Client Interface & HTTP Response Format
Successful Response Headers
HTTP/1.1 200 OK
Content-Type: application/json
RateLimit-Limit: 100
RateLimit-Remaining: 42
RateLimit-Reset: 1672531199
Exceeded Limit Response
HTTP/1.1 429 Too Many Requests
Retry-After: 3
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 1672531202
Content-Type: application/json
{
"error": "rate_limit_exceeded",
"message": "API rate limit exceeded for tier 'free'.",
"rule_triggered": "per-second-burst",
"retry_after_seconds": 3
}
9. Common Pitfalls & Key Takeaways
- Deducting Tokens on Denied Requests: Ensure failed checks do not decrease token balances. Clients should not be penalized or locked out indefinitely for hitting a limit.
- Double-Deduction across Multi-Rule Checks: If checking multiple rules, verify all pass before deducting tokens from any of them. Lua scripts allow atomic rolling back of intermediate deductions if a later rule fails.
- Memory Leaks: Always assign a TTL to keys in Redis so inactive clients clean up automatically.