JavaScriptFundamental (ES6), part 2
Deduplicate in-flight requests (singleFlight) in JavaScript
41 One request in flight, however many callers
hardWrite singleFlight(fn): while a call for a key is still running, every new caller for that key gets the same promise instead of a second request. Count the calls to prove it. Then show what happens after it settles, and what happens when it fails.
Stuck? Three hints, smallest first
- 1. A
Mapfrom key to the in-flight promise. Present means join, absent means start. - 2. Delete the entry when it settles, or you have written a cache rather than a de-duplicator.
- 3. A failure should be shared by everyone currently waiting, and then forgotten so a retry can work.
function singleFlight(fn) {
const inFlight = new Map();
const wrapped = (key) => {
if (inFlight.has(key)) return inFlight.get(key); // join the one in progress
const promise = (async () => fn(key))().finally(() => inFlight.delete(key));
inFlight.set(key, promise);
return promise;
};
wrapped.pending = () => inFlight.size;
return wrapped;
}
let calls = 0;
const tillBalance = singleFlight(async (name) => {
calls++;
await Promise.resolve();
await Promise.resolve();
if (name === 'broken') throw new Error(name + ': 500 from the API');
return name + ' balance ₦24,000';
});
const three = await Promise.all([tillBalance('yaba'), tillBalance('yaba'), tillBalance('yaba')]);
const callsAfterThree = calls;
const started = tillBalance('lekki');
const pendingDuring = tillBalance.pending();
await started;
const pendingAfter = tillBalance.pending();
await tillBalance('yaba'); // long settled, so a fresh call
const callsAfterLater = calls;
const bothFailed = await Promise.all([
tillBalance('broken').catch((err) => err.message),
tillBalance('broken').catch((err) => err.message),
]);
const callsAfterFailure = calls;
const retried = await tillBalance('broken').catch((err) => err.message);
const callsAfterRetry = calls;
const twoKeys = await Promise.all([tillBalance('ikeja'), tillBalance('ajah')]);
const callsAfterTwoKeys = calls;
console.log('three callers, calls made:', callsAfterThree);
console.log('pending during / after :', pendingDuring, '/', pendingAfter);
console.log('shared failure :', bothFailed[0] === bothFailed[1]);
console.log('calls, in order :', [callsAfterThree, callsAfterLater, callsAfterFailure, callsAfterRetry, callsAfterTwoKeys]);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three simultaneous callers cause one request', callsAfterThree, 1);
test('and all three get the same answer', three, ['yaba balance ₦24,000', 'yaba balance ₦24,000', 'yaba balance ₦24,000']);
test('exactly one entry is held while it runs, none afterwards', [pendingDuring, pendingAfter], [1, 0]);
test('a caller arriving after it settled starts a fresh request', callsAfterLater, 3);
test('everyone waiting on a failure gets the same failure, once', [bothFailed, callsAfterFailure], [['broken: 500 from the API', 'broken: 500 from the API'], 4]);
test('and the failure is not cached, so a later attempt really retries', [retried, callsAfterRetry], ['broken: 500 from the API', 5]);
test('different keys never share, so both run', [twoKeys.length, callsAfterTwoKeys], [2, 7]);
test('nothing is left in the map at the end', tillBalance.pending(), 0);
This is the fix for the stampede: a page where eight components each ask for the same balance on mount, and a server that receives eight identical requests. De-duplication happens on the client, in one Map, and the eight components are none the wiser because they all get a promise that resolves with the same value.
The line that decides what you have built is .finally(() => inFlight.delete(key)). With it, this is a de-duplicator: it collapses concurrent calls and nothing more, so data is never stale by more than one request. Take it out and you have an accidental permanent cache, where the first answer is the only answer your application will ever see again. Both are useful; confusing them is not.
Failure needs deciding too. Here the rejection is shared by everyone currently waiting — one request failed, so all eight callers hear about it — and then the entry is dropped, so the next attempt is a real attempt. Caching the rejection would mean a single blip poisoning the key for the lifetime of the page. Retrying per caller would mean the eighth caller starting request number eight, which is what you were trying to avoid.
The wrapper is written as (async () => fn(key))() rather than fn(key) on purpose. If fn is not async and throws synchronously, that would throw at the call site with no entry ever stored; wrapping it turns the throw into a rejection so both paths behave alike.