Databases & System Design•Part 4: In-Memory Caching & Fast Data Stores (Redis) (41 - 50)
Redis Sliding Window Rate Limiter:
In Simple Words:
Uses a Sorted Set (ZSET) where score is the current timestamp: ZREMRANGEBYSCORE clears expired timestamps; ZCARD counts active requests in the window.
javascript
async function rateLimit(userId, limit = 100, windowSec = 60) {
const now = Date.now();
const clearBefore = now - (windowSec * 1000);
const key = `rate:${userId}`;
const multi = redis.multi();
multi.zremrangebyscore(key, 0, clearBefore); // Remove old requests
multi.zadd(key, now, `${now}-${Math.random()}`); // Add current request
multi.zcard(key); // Count requests in window
multi.expire(key, windowSec);
const results = await multi.exec();
const currentCount = results[2][1];
return currentCount <= limit;
}