14.10. Batch requests by size or by time
Topics
This question is in
14. Timeouts, retries and concurrencyA list of 40 comments renders 40 avatars, and each one asks for its user: 40 requests for 40 small answers. If the server accepts a list of ids, one request could do the job. A batcher lets every component ask for one key as usual, quietly collects the keys for a moment, and sends them together. It sends a batch when it is full, or when its first key has waited long enough, so no caller waits forever.
Write createBatcher(handler, options) in batcher.js. It returns load(key), which returns a promise of the value for key. Keys are collected into a batch that goes to handler(keys) when it holds maxSize keys, or maxWait ms after its first key, whichever comes first.
Signature
function createBatcher(handler, options) // returns load(key)handler(keys): sends one batch. It gets an array of keys and returns a promise of an array of values: one per key, in the same order. It may also return the array directly, or throw.options(optional):maxSize(default 10), the most keys in a batch, andmaxWait(default 50), the ms from a batch's first key until it is sent.load(key): addskeyto the current batch and returns a promise of its value.
Requirements
- A key is not sent at once: it waits in the current batch.
- A batch is sent exactly
maxWaitms after its first key. Later keys do not push that time back. - When a batch reaches
maxSizekeys, it is sent at once, during theloadcall that filled it, and its timer is cancelled. - After a batch is sent, the next key starts a new, empty batch with its own wait. The handler's array is never changed afterwards.
- The handler gets the keys in call order, the same key as often as it was asked for. Each
loadresolves with the value at its own position. - If the handler rejects or throws, every
loadof that batch rejects with its error; other batches are not affected. - If the handler's answer is not an array with one value per key, every
loadof that batch rejects with anError. - Batches already sent settle on their own, and each batcher has its own batch and timer.
Examples
const loadUser = createBatcher((ids) => fetch(`/api/users?ids=${ids.join(",")}`).then((r) => r.json()));
loadUser(1); // at 0 ms: a new batch, sent at 50 ms
loadUser(7); // at 30 ms: joins it
loadUser(1); // at 40 ms: joins it too
// at 50 ms: one request for ids 1,7,1; each promise gets its own userconst load = createBatcher(handler, { maxSize: 2 });
load("a");
load("b"); // the batch is full: handler(["a", "b"]) runs now
load("c"); // a new batch, sent 50 ms from now// handler(["a", "b"]) resolves with ["only one"]
// both loads reject: a value would otherwise reach the wrong callerEnvironment
- Plain JavaScript in a browser page; the tests call the global
createBatcherfrombatcher.js. - The tests run on a virtual clock that replaces
setTimeoutandclearTimeout. - Sharing one result between identical keys is problem 14.11; here every call keeps its own place in the batch.
Hints
- When should the timer start: on every key, or only on some? What would starting it on every key turn the batcher into?
- Each item in a batch needs a way to hand its caller a value later. What can you store next to the key?
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