Build a throttled query batcher: send the first key at once, then batch the rest per window
Problem
A dashboard renders dozens of widgets, and each one asks for a user by id the moment it mounts. One request per widget floods the API. A batcher that waits a little before every request makes the first widget slow. You need both: the first request goes out at once, and the rest are grouped.
const users = createQueryBatcher({
windowMs: 100,
fetchMany: (ids) => fetch(`/users?ids=${ids.join(",")}`).then((r) => r.json()),
});
users.get(1); // t=0: fetchMany([1]) right away
users.get(2); // t=10: queued
users.get(3); // t=40: queued
users.get(2); // t=60: already queued, shares the same request
// t=100: fetchMany([2, 3]), and a new window runs until t=200Ref. UR-1419 · © UIRound · uiround.com/questions/build-a-throttled-query-batcher-send-the-first-key-at-once-then-batch-the-rest-per-window
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1This is throttle with a leading call, applied to requests. When the batcher is idle, a key goes out on its own straight away. While a window is open, keys wait in a queue.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.