Build a Rate Limiter
Rate limiting is one of the most important patterns in production systems. It prevents:
- API abuse
- DDoS attacks
- Runaway scripts hammering your database
Every major API (Twitter, GitHub, OpenAI) uses rate limiting.
The Sliding Window Algorithm
Fixed window (naive): 100 requests per minute, reset at :00. Problem: A user could send 100 at :59 and 100 more at :01 — 200 in 2 seconds.
Sliding window (better): Track timestamps of recent requests. Only allow requests where the count in the last N milliseconds < limit.
timestamps = [t1, t2, t3, ...]
windowStart = now - windowMs
validRequests = timestamps.filter(t => t > windowStart)
if (validRequests.length < limit) → allow
else → deny
The Spec
const limiter = new RateLimiter(5, 1000); // limit=5, windowMs=1000
limiter.isAllowed("user123"); // true (1st request)
// ... after 5 requests in 1 second:
limiter.isAllowed("user123"); // false (rate limited)
- Each key (user id, IP) has its own window
- Multiple keys are independent
⚡ 60 XP
solution.jsRuns in your browser
Loading editor…
Tests3 to pass
allows requests under limit
blocks requests over limit
different keys are independent
Run your code to check these.