Keep the current batch and one timer. push adds the item, and then either the batch is full, so flush now, or it makes sure a timer is running that will flush after wait ms. flush cancels the timer, detaches the batch, and sends it if it isn't empty. Cancelling the timer in flush is what "restart the timer" means: the next item pushed starts a fresh one. Start the timer on the first item of a batch and don't restart it on later pushes, or a steady trickle of items never gets sent. Then make it real: send is async, so return a promise from push, and add retry with backoff, flush() for page hide and clear().
Build a utility in JS that sends data in batches with a timeout: as soon as the batch size is reached, send immediately and restart the timer; if the timer fires before the batch is filled, send what's there and restart.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Two triggers share one flush. push adds the item; if the batch is now full it flushes at once, otherwise it makes sure a timer is running. The timer is started by the first item of a batch and isn't restarted by later items, so no item waits longer than wait. flush always cancels the timer, which is the "restart": the next item starts a fresh one. An empty batch is never sent. The timing checks pin this down: with a size of 3 and a wait of 100 ms, items pushed at 0, 50 and 50 ms go out at 50 ms, and an item pushed at 60 ms goes out at 160 ms.
// Collect items; send them when the batch is full or when `wait` ms have passed since the// first item of the batch, whichever comes first. Sending restarts the timer.function createBatcher(send, { size, wait }) {let batch = [];let timer = null;function flush() {clearTimeout(timer);timer = null;if (batch.length === 0) return; // nothing to send: no empty requestsconst items = batch;batch = [];send(items);}return {push(item) {batch.push(item);if (batch.length >= size) flush();else if (timer === null) timer = setTimeout(flush, wait);},flush,};}
passes 7 checks run on every build, against the native method where there is one
- a full batch is sent at once, with no timer left behind
- the timer sends a batch that isn't full
- the timer runs from the first item of the batch; later items don't restart it
- sending restarts the timer for the next batch
- more items than one batch: full batches go now, the rest waits
- nothing pushed, nothing sent
- flush sends now and cancels the timer
Real sends are requests that can fail. Each batch gets one promise, and every push returns the promise of the batch its item joined, so the caller can await the result or handle the failure. The batch is detached before sending, so items pushed while a request is in flight start a new batch and a failure affects only its own batch. Whoever calls push owns that promise: await it or add a catch.
// `send` is async: push() returns a promise that settles with the outcome of the batch that// carried the item, so a caller knows whether its data went out.function createBatcher(send, { size, wait }) {let batch = null; // { items, promise, resolve, reject }let timer = null;function open() {const b = { items: [] };b.promise = new Promise((resolve, reject) => {b.resolve = resolve;b.reject = reject;});return b;}function flush() {clearTimeout(timer);timer = null;if (!batch) return Promise.resolve();const current = batch;batch = null; // items pushed while this batch is in flight start a new one// The executor runs now, so the send starts at once, and a throw becomes a rejection.new Promise((resolve) => resolve(send(current.items))).then(current.resolve, current.reject);return current.promise;}return {push(item) {batch ??= open();batch.items.push(item);const { promise } = batch;if (batch.items.length >= size) flush();else if (timer === null) timer = setTimeout(flush, wait);return promise;},flush,get pending() {return batch ? batch.items.length : 0;},};}
passes 13 checks run on every build, against the native method where there is one
- a full batch is sent at once, with no timer left behind
- the timer sends a batch that isn't full
- the timer runs from the first item of the batch; later items don't restart it
- sending restarts the timer for the next batch
- more items than one batch: full batches go now, the rest waits
- nothing pushed, nothing sent
- flush sends now and cancels the timer
- push resolves with the result of its batch
- a failed send rejects that batch's pushes only
- a send that throws synchronously is a rejection
- pending counts the items waiting
- flush returns the batch's promise; with nothing waiting it resolves
- the send starts in the same tick as the push that fills the batch
A failed send is tried again after 100, 200, 400 ms… (exponential backoff), up to retries more times; send receives the attempt number. Sends are chained, so batches go out one at a time in the order they were filled, and a retrying batch isn't overtaken by the next one. flush() sends what's waiting now and resolves when it's out. clear() drops what's waiting, rejects those pushes and returns the count; a batch already being sent is left alone.
// Retries with exponential backoff, batches sent one at a time in order, and clear().function createBatcher(send, { size, wait, retries = 0, backoff = 100 }) {let batch = null; // { items, promise, resolve, reject }let timer = null;let chain = Promise.resolve(); // every send so far; never rejectsconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));function open() {const b = { items: [] };b.promise = new Promise((resolve, reject) => {b.resolve = resolve;b.reject = reject;});return b;}async function sendWithRetry(items) {for (let attempt = 0; ; attempt++) {try {return await send(items, attempt);} catch (error) {if (attempt >= retries) throw error;await sleep(backoff * 2 ** attempt); // 100, 200, 400 ms…}}}function stopTimer() {clearTimeout(timer);timer = null;}// Sends what's waiting. Resolves when it (and every batch before it) has gone out.function flush() {stopTimer();if (!batch) return chain;const current = batch;batch = null;// Chained, so a batch waits for the one before it, retries included: order is kept.chain = chain.then(() => sendWithRetry(current.items)).then(current.resolve, current.reject);return current.promise;}// Drops what's waiting (not what is already being sent). Returns how many items were dropped.function clear() {stopTimer();if (!batch) return 0;const dropped = batch;batch = null;dropped.reject(new Error('batch cleared'));return dropped.items.length;}return {push(item) {batch ??= open();batch.items.push(item);const { promise } = batch;if (batch.items.length >= size) flush();else if (timer === null) timer = setTimeout(flush, wait);return promise;},flush,clear,get pending() {return batch ? batch.items.length : 0;},};}
passes 18 checks run on every build, against the native method where there is one
- a full batch is sent at once, with no timer left behind
- the timer sends a batch that isn't full
- the timer runs from the first item of the batch; later items don't restart it
- sending restarts the timer for the next batch
- more items than one batch: full batches go now, the rest waits
- nothing pushed, nothing sent
- flush sends now and cancels the timer
- push resolves with the result of its batch
- a failed send rejects that batch's pushes only
- a send that throws synchronously is a rejection
- pending counts the items waiting
- flush returns the batch's promise; with nothing waiting it resolves
- retries with a doubling delay, then succeeds
- gives up after `retries` more tries and rejects with the last error
- batches go out one at a time, in order, even while one retries
- clear drops what's waiting, rejects those pushes and cancels the timer
- clear doesn't touch a batch that is already being sent
- flush with nothing waiting resolves when the batch in flight is out
Analytics and logging
Sending one request per click or log line wastes requests. Clients collect events and send a batch every few seconds or every N events, and flush when the page is hidden, since that's the last moment a page can rely on.
Sending the last batch on the way out
navigator.sendBeacon() queues a small POST that the browser delivers even as the page unloads, which is what a batcher's final flush should use.
DataLoader
GraphQL's DataLoader is a batcher for reads: every load(key) in one tick joins a single batch request and each caller gets its own promise back, the pattern of the intermediate stage.
Restarting the timer on every push: that's a debounce, and a steady trickle of items is never sent until the batch fills.
Leaving the timer running after a size-triggered send, so the next batch goes out early.
Sending empty batches when the timer fires with nothing collected.
Sending the live array and then clearing it, so the request sees an empty or changing batch. Detach it first.
Losing items when a send fails, with no retry and no way for the caller to know.
Never flushing on page hide or unmount, which drops the last batch.
Should the timer be per batch or a fixed interval?
Ask. Per batch (started by the first item) bounds how long any item waits and does no work while idle. A fixed setInterval is simpler but wakes up even when there's nothing to send, and the first item of a batch may wait anywhere from 0 to wait.
What happens to items pushed during a send?
They go into a new batch, because the current one was detached before sending. Whether that next batch may be sent while the first is in flight, or must wait for it, is a design choice; the advanced stage keeps them in order.
What should be retried?
Failures that can succeed later: network errors, timeouts, 429 and 5xx responses. A 400 will fail the same way every time. Space retries out with exponential backoff and some randomness, and give up after a limit.
How do you avoid sending a batch twice?
A retry after a timeout can repeat a request the server did process. Give each batch an id and have the server ignore an id it has already seen.
- developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
- developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
- developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise
- en.wikipedia.org/wiki/Exponential_backoff
- github.com/graphql/dataloader