
API Rate Limiting with Redis: Token Bucket, Sliding Window, and Per-Client Limits
API Rate Limiting with Redis: Token Bucket, Sliding Window, and Per-Client Limits Your API has no rate limiting. A single client sends 10,000 requests per second. Your database melts. Here is how to protect your services. Token Bucket with Redis import Redis from " ioredis " ; const RATE_LIMIT_SCRIPT = ` local key = KEYS[1] local limit = tonumber(ARGV[1]) local window = tonumber(ARGV[2]) local now = tonumber(ARGV[3]) redis.call("ZREMRANGEBYSCORE", key, 0, now - window) local count = redis.call("ZCARD", key) if count >= limit then return 0 end redis.call("ZADD", key, now, now .. math.random()) redis.call("EXPIRE", key, window / 1000) return 1 ` ; async function checkRateLimit ( redis : Redis , clientId : string , limit : number , windowMs : number ): Promise < boolean > { const key = `rate: ${ clientId } ` ; const allowed = await redis . eval ( RATE_LIMIT_SCRIPT , 1 , key , limit , windowMs , Date . now ()); return allowed === 1 ; } Express Middleware function rateLimiter ( limit = 100
Continue reading on Dev.to Webdev
Opens in a new tab



