Implementing Rate Limiting

1. Using Token Bucket Algorithm

ElementDetail
Bucket capacityBurst size
Refill rateTokens added per second
BehaviorAllow if token available; else 429
UseSmooth burst tolerance (most common)

Example: Token bucket (Redis Lua)

// Pseudo: capacity=100, refill=10/s
long now = clock.millis();
long tokens = redis.evalsha(luaTokenBucket, key, capacity, refill, now);
if (tokens < 1) throw new RateLimitedException();

2. Using Leaky Bucket Algorithm

ElementDetail
QueueFixed-size buffer of requests
Leak rateConstant outflow
BehaviorSmooth output; reject when full
UseTraffic shaping; constant downstream rate

3. Using Fixed Window Counter

AspectDetail
Windowe.g. per minute
CounterIncrement per request; reset at boundary
ProsSimple, low memory
ConsEdge bursts at window boundary (2× limit)

4. Using Sliding Window Log

AspectDetail
StorageSorted set of timestamps
CheckCount entries in last N seconds
ProsMost accurate
ConsO(N) memory per key

5. Using Sliding Window Counter

AspectDetail
ApproximationWeighted blend of current + previous window
MemoryTwo counters per key
ProsSmooth, low memory
UseDefault for HTTP rate limiters

6. Implementing Per-User Limits

KeyDetail
AuthenticatedJWT subject ID
AnonymousHashed IP
API tierFree / Pro / Enterprise quotas
Quota windowPer second / minute / day

7. Implementing Per-Service Limits

ScopeDetail
Per upstreamProtect dependency from overload
Per routeDifferent limits per endpoint
TenantMulti-tenant fairness
Concurrency limitCap in-flight requests (semaphore)

8. Handling Rate Limit Responses

ElementDetail
Status429 Too Many Requests
Retry-AfterSeconds or HTTP date
Error bodyJSON with code & doc link
ClientBackoff with jitter

9. Using Distributed Rate Limiting

BackendDetail
RedisINCR + EXPIRE; Lua for atomicity
Envoy global RL servicegRPC (Lyft Ratelimit)
Cell-basedHash key → shard for scale
Local + globalCheap local cap; global precise

10. Implementing Rate Limit Headers

HeaderMeaning
X-RateLimit-LimitQuota in window
X-RateLimit-RemainingCalls left
X-RateLimit-ResetReset time (epoch / seconds)
RateLimit (RFC draft)RateLimit: limit=100, remaining=42, reset=30
Retry-AfterOn 429

11. Managing Rate Limit Tiers

TierQuota
Free60 req/min, 10k/day
Pro600 req/min, 1M/day
EnterpriseCustom; SLAs
BurstAllow short overage with token refill

12. Implementing Adaptive Rate Limiting

SignalAction
Latency riseReduce concurrency
Error spikeTighten quotas
HealthyRelax limits
AlgorithmsAIMD, concurrency limits (Netflix Limit lib)