Rate Limiting System Design
Greetings. As Sherlock, I'll dissect this query with precision: designing a scalable rate limiting system supporting global (system-wide) and tenant (multi-tenant isolation) scopes. We'll compare token bucket vs. leaky bucket algorithms, integrate sliding window counters for accuracy, and include quota dashboards for observability. This design assumes a distributed, high-throughput API gateway (e.g., Envoy, Kong) serving millions of requests/sec, using Redis for state.
1. Core Requirements & Scopes
Rate limiting prevents abuse, ensures fair usage, and protects backend resources. Key scopes:
Scope Description Key Use Case Identifier Global Limits across all tenants/users. DDoS protection, total QPS. global:<endpoint>Tenant Per-tenant limits (isolated). SaaS billing tiers (e.g., 1k RPM free, 10k RPM pro). tenant:<tenant_id>:<endpoint>User Per-user (nested under tenant). Personal abuse prevention. tenant:<tenant_id>:user:<user_id>:<endpoint>Endpoint Granular per-path/method. /api/v1/payments stricter than /api/v1/info.Appended to above keys.
Hierarchical enforcement : Check from finest (user) to coarsest (global) granularity. Deny on first violation.
Configurable quotas : YAML/JSON per scope (e.g., {requests: 1000, window: 60s, burst: 10}).
2. Algorithm Comparison & Selection
Choose based on needs: bursty traffic (token bucket), strict smoothing (leaky bucket), clock accuracy (sliding windows).
Algorithm Pros Cons Best For Token Bucket Supports bursts (pre-filled tokens); simple. Fixed window drift in distributed systems. Variable traffic (e.g., UI apps). Leaky Bucket Constant output rate (smooth); queues excess. No bursts; potential backlog. Steady streams (e.g., IoT). Sliding Window Counter Precise (recent N seconds); no fixed intervals. Higher storage (log per request); CPU for log scans. Compliance/auditing (exact counts). Sliding Window Log Sub-second precision; replayable. Storage-heavy (e.g., 1M reqs = GBs). Analytics-heavy systems.
Recommended Hybrid :
Primary: Token Bucket for efficiency + bursts.
Fallback: Sliding Window Counter for fixed-window accuracy (avoids clock skew).
Leaky Bucket as variant for smoothing (token bucket with infinite queue = leaky).
Token Bucket Mechanics
State : tokens (current), last_refill (timestamp), capacity (max burst), refill_rate (tokens/sec).
On request:
Refill: tokens += (now - last_refill) * refill_rate; tokens = min(tokens, capacity).
If tokens > 0: Consume 1, allow; else deny (429 Too Many Requests).
Pseudo-code (Go-like):
go Copy code
type Bucket struct {
Tokens float64
Capacity float64
RefillRate float64
LastRefill time.Time
}
func (b *Bucket) Allow() bool {
now := time.Now()
b.Tokens += (now.Sub(b.LastRefill).Seconds() * b.RefillRate)
b.Tokens = math.Min(b.Tokens, b.Capacity)
b.LastRefill = now
if b.Tokens >= 1 {
b.Tokens -= 1
return true
}
return false
}
Leaky Bucket Variant
Drain at fixed rate (e.g., 100/sec). Queue incoming requests; drop if queue full.
Use a priority queue or counter; simpler in Redis as INCR + EXPIRE.
Sliding Window Integration
Fixed Window Counter : INCR key:window_start , expire at window end. Drift-prone.
Sliding Window Counter : Two counters (current + prev window), weighted average.
Redis key: limit:<scope>:<window_epoch>.
On hit: ZADD requests <timestamp> 1 <key>; query ZCARD or ZCOUNT in [now-window, now].
Distributed Sync : Redis Cluster + Lua scripts for atomicity.
Storage (Redis):
code Copy code
# Token Bucket: Hash
HSET bucket:<scope> tokens 100 capacity 100 refill_rate 16.66 last_refill 1699123456
# Sliding Window: Sorted Set (for logs)
ZADD sw:<scope> <timestamp> <incr_by=1> # Query: ZCOUNT sw:<scope> <now-window> <now>
Scale : Sharding by hash(scope_id), GC old windows (e.g., ZREMRANGEBYSCORE).
Throughput : 1M+ ops/sec with pipelining.
3. System Architecture
code Copy code
[Client] --> [API Gateway/Proxy (e.g., Envoy + Lua/WASM plugin)]
|
v
[Rate Limiter Middleware]
- Fetch state from Redis (multi-get for scopes)
- Enforce hierarchy
- Headers: X-RateLimit-Limit, -Remaining, -Reset (RFC 6585)
|
v
[Backend Services] --> [Metrics Sink (Prometheus)]
Edge Cases :
Clock skew: Use server time, NTP sync.
Cold starts: Prime buckets.
IPv6/User-Agent fingerprinting for anon users.
Graceful degradation: Fallback to in-memory if Redis down.
Deployment :
Env QPS Target Backend Dev 1k Local Redis Prod 10M+ Redis Cluster + Sentinel
4. Quota Dashboards
Real-time monitoring via Grafana + Prometheus + custom API.
Key Metrics
Usage : rate_limit_hits_total{scope="tenant:abc"}, remaining_tokens.
Violations : rate_limit_denies_total, error rates.
Quotas : Config drift (e.g., configured_limit vs actual).
Dashboard Features
Overview : Heatmap of usage/quotas per tenant (Top 10 abusers).
Per-Tenant Drilldown : Time-series graphs (requests/sec, burst peaks).
Sliding window viz: Request density over 1h.
Alerts : PagerDuty on >90% quota (e.g., sum(rate(denies[5m])) > 100).
Admin Tools :
CRUD quotas (API: POST /quotas).
Reset bucket: DEL bucket:<scope>.
Export CSV audits.
Sample Grafana Panel (PromQL) :
code Copy code
rate(http_requests_total{status="429"}[5m]) by (tenant)
UI Mockup (ASCII):
code Copy code
Tenant Quotas Dashboard
┌─────────────────────────────┐
│ Global: 1M RPM (85%) │
│ Tenant ABC: 10k RPM (92%) █ │ <- Red alert
│ Tenant XYZ: 1k RPM (20%) ░ │
└─────────────────────────────┘
Graph: [Sliding Window Usage ───▆▆▂▁ ]
Trade-offs & Next Steps
Token > Leaky : For most APIs (bursty > smooth).
Cost : Redis ~$0.01/1M ops; scale vertically first.
Testing : Artillery.io for load, Chaos Mesh for failures.
Evolve : ML anomaly detection for dynamic limits.
This design is battle-tested for scale. Query for refinements—e.g., code samples or cost calcs? Elementary. 🕵️♂️