Protects APIs against overload and abuse.
Token Bucket¶
The bucket fills with tokens at a constant rate. Request = consumes a token. Empty = rejected. Allows bursts.
Leaky Bucket¶
Requests fall into the bucket and are processed at a constant rate. Smooths out bursts.
Fixed Window¶
Counts requests in fixed windows. Problem: double rate at window boundaries.
Sliding Window¶
Combines the precision of sliding with the efficiency of fixed.
Redis Implementation¶
– Sliding Window Counter local key = KEYS[1] local window = tonumber(ARGV[1]) local limit = tonumber(ARGV[2]) local now = tonumber(ARGV[3]) redis.call(‘ZREMRANGEBYSCORE’, key, 0, now - window) if redis.call(‘ZCARD’, key) < limit then redis.call(‘ZADD’, key, now, now .. math.random()) return 1 end return 0
HTTP Headers¶
X-RateLimit-Limit: 100 X-RateLimit-Remaining: 42 Retry-After: 30
Token Bucket for Most Use Cases¶
Most flexible — allows bursts, constant memory. Redis for distributed environments.