Redis & Caching (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
How do you implement a simple Rate Limiter using Redis Sorted Sets (Sliding Window)?
junior LevelMost AskedCode ExampleredisBasic
In Simple Words: Sliding window rate limiters prevent boundary spikes:
- Use a Sorted Set where both the member and score are the current Unix epoch timestamp in milliseconds:
typescript
async function isRateLimited(userId: string, limit = 5, windowMs = 60000): Promise<boolean> {
const now = Date.now();
const key = `ratelimit:${userId}`;
const clearBefore = now - windowMs;
const multi = redis.multi();
multi.zremrangebyscore(key, 0, clearBefore); // Remove expired requests
multi.zadd(key, now, `${now}-${Math.random()}`); // Add current request
multi.zcard(key); // Count active requests in window
multi.expire(key, Math.ceil(windowMs / 1000));
const results = await multi.exec();
const currentCount = results[2][1] as number;
return currentCount > limit;
}