Rate Limiting with RedisAdvanced
1Question 1 of 1
javascriptHow do you implement a Sliding Window Rate Limiter using Redis Sorted Sets?
Explanation & Concept
A sliding window rate limiter prevents the 'burst at the boundary' flaw of fixed-window counters. It tracks individual request timestamps in a Sorted Set per user.
Algorithm steps: 1. Remove entries older than `now - window_size` (`ZREMRANGEBYSCORE`). 2. Count remaining elements in the set (`ZCARD`). 3. If count < limit, add the current timestamp (`ZADD`) and allow the request.
Code Example
javascript
async function isRateLimited(userId, limit = 10, windowSec = 60) {
const key = `rate:${userId}`;
const now = Date.now();
const clearBefore = now - (windowSec * 1000);
const multi = redis.multi();
multi.zremrangebyscore(key, 0, clearBefore);
multi.zcard(key);
multi.zadd(key, now, `${now}:${Math.random()}`);
multi.expire(key, windowSec);
const results = await multi.exec();
const currentCount = results[1][1];
return currentCount >= limit; // true = blocked, false = permitted
}How It Works & Key Takeaways
By recording distinct timestamps as score and member, the sliding window is accurate down to the millisecond, completely preventing edge bursts.
Mock Test · 1 Questions · Optional
Ready for Pipelining?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions