AniUI Academy
hard+350 XPPractice

Rate limit with a sliding window

Public APIs publish limits like 'ten requests per second' and answer with 429 when you exceed them. A client-side limiter keeps you under the line without you having to think about it at every call site.

Implement createRateLimiter(limit, windowMs), returning a schedule(task) function. task takes no arguments and returns a promise; schedule returns a promise that settles with that task's own result. At most limit tasks may be **started** within any windowMs window. A task that cannot start yet waits, and waiting tasks start in the order they were scheduled. Once a start falls further than windowMs in the past it no longer counts against the limit, so a slot frees up. A task that rejects only rejects its own promise and does not hold up the ones behind it.

What it has to do

  • Start at most limit tasks within any windowMs window.
  • Start the first limit tasks without any delay.
  • Start queued tasks in the order they were scheduled.
  • Settle each returned promise with its own task's result.
  • Let a rejecting task fail alone, without stalling the queue.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.