Build a throttled query batcher: send the first key at once, then batch the rest per window

mediumAbout 35 minutesUpdated CodingProbatchingthrottlepromisestimersapi-design
Not solved

Share this question

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=200

Ref. UR-1419 · © UIRound · uiround.com/questions/build-a-throttled-query-batcher-send-the-first-key-at-once-then-batch-the-rest-per-window

Stuck? Take a hint

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.

Every question and answer7 days, one payment