14.8. A rate limiter (n calls per second)
Topics
This question is in
14. Timeouts, retries and concurrencyMany APIs set a rate limit: "at most 10 requests per second", and every request over it gets a 429 Too Many Requests. A page that loads a dashboard, autocompletes and polls can easily go over. Instead of letting requests fail, the client can queue them and start each one as soon as the limit allows.
Write createRateLimiter(limit, interval) in rate-limiter.js. It returns schedule(fn, ...args), which runs fn(...args) when the limit allows and returns a promise of its result. At most limit calls may start in any window of interval ms; the others wait in a queue, in order.
Signature
function createRateLimiter(limit, interval) // returns schedule(fn, ...args)limit: how many calls may start in any window (a whole number of 1 or more).interval: the window length in ms (1000 for "per second").schedule(fn, ...args): queues the call and returns a promise offn(...args)'s result.fnmay return a promise or a value, or throw.
Requirements
- While the window has room, a call starts during
schedule, at once. - In any
intervalms, at mostlimitcalls start. A call over the limit starts exactly when the oldest start in the window becomesintervalms old, not earlier. - The window slides: each start leaves it on its own,
intervalms after it happened (not a counter reset every second). - Waiting calls start in the order they were scheduled; a new call never jumps ahead of the queue.
- Only starts count: a slow call that is still running does not block the next start.
- The promise settles like
fn: same value, or same error. A failed or throwing call still counts against the limit, and the queue keeps going after it.schedulenever throws. - At most one timer is waiting at a time, and none is left once the queue is empty.
- Each limiter has its own window and queue.
Examples
const schedule = createRateLimiter(2, 1000);
for (const id of [1, 2, 3, 4, 5]) schedule(fetchUser, id);
// fetchUser starts at 0, 0, 1000, 1000 and 2000 msconst schedule = createRateLimiter(2, 1000);
schedule(a); // starts at 0
// 500 ms later
schedule(b); // starts at 500
// 100 ms later
schedule(c); // waits: starts at 1000, when a's start leaves the window
schedule(d); // starts at 1500, when b's doesconst user = await schedule((id) => fetch(`/api/users/${id}`), 7);
// the response, whenever the limit let it startEnvironment
- Plain JavaScript in a browser page; the tests call the global
createRateLimiterfromrate-limiter.js. - The tests run on a virtual clock that replaces
setTimeout,clearTimeoutandDate.now. Read the time withDate.now(). - Limiting how many calls run at once is a different problem: problem 14.7.
Hints
- To know when the next call may start, which past start do you need to look at?
- Does each queued call need its own timer, or can one timer start a call and then set the next timer?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it