52Implement a sliding-window rate limiter
mediumAbout 35 minutesCodingrate-limitingalgorithmsqueues
Problem
Implement createSlidingWindowLimiter({ limit, windowMs, now = Date.now }). It allows at most limit requests per key in any window of windowMs milliseconds, not just per fixed minute.
It returns:
tryAcquire(key = "default"): record a request and returntrueif allowed; otherwise returnfalseand record nothing.retryAfter(key = "default"): milliseconds until the next request forkeywould be allowed (0 if now).
const limiter = createSlidingWindowLimiter({ limit: 5, windowMs: 60_000 });
if (!limiter.tryAcquire(userId)) {
showToast(`Too many attempts. Try again in ${Math.ceil(limiter.retryAfter(userId) / 1000)} s`);
}Requirements
- A request made at time
tstops counting att + windowMs. - Keys are independent.
- Forget timestamps that left the window, so memory stays bounded by
limitper key, and drop keys that have no recent requests. nowis injectable so tests can control time.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Step-by-step
A counter that resets every minute allows limit requests at 0:59 and limit more at 1:00, which is twice the limit within two seconds. A sliding window looks at the last windowMs from now.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.