Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Request deduplication for a data loader in JavaScript

86 A de-duplicator that hands back the request already in flight

hard

Three components mount at once and all three ask for the same vendor list. Wrap the loader so that the second and third callers receive the same promise as the first rather than starting their own request. Forget the key once it settles, so this stays a de-duplicator and not a cache, and make sure a failure is shared and then cleared too.

Stuck? Three hints, smallest first
  1. 1. A Map from key to the promise currently in flight is the whole data structure.
  2. 2. Return the stored promise if there is one. Only create a new one when there is not.
  3. 3. .finally() is where the key gets deleted, because it runs for a rejection as well as a resolution.

The answer

function deduplicate(loader) {
  const inFlight = new Map();
  return {
    load(key) {
      const running = inFlight.get(key);
      if (running) return running;                     // the same promise object, not a copy
      // The async wrapper calls loader synchronously and still turns a
      // synchronous throw into a rejection.
      const started = (async () => loader(key))().finally(() => inFlight.delete(key));
      inFlight.set(key, started);
      return started;
    },
    get size() { return inFlight.size; },
  };
}

// A loader we can settle by hand, so nothing depends on timing.
const gates = new Map();
const asked = [];
const loader = (key) => {
  asked.push(key);
  return new Promise((resolve, reject) => gates.set(key, { resolve, reject }));
};

const api = deduplicate(loader);

const a = api.load('vendors?city=lagos');
const b = api.load('vendors?city=lagos');
const c = api.load('vendors?city=abuja');
const sharedPromise = a === b;
const inFlightNow = api.size;
const requestsSoFar = asked.length;

gates.get('vendors?city=lagos').resolve(['Adaeze Fabrics']);
gates.get('vendors?city=abuja').resolve(['Chidi Electronics']);
const [fromA, fromB, fromC] = await Promise.all([a, b, c]);
const clearedAfterSettling = api.size;

// Settled means forgotten, so this really does go out again.
const again = api.load('vendors?city=lagos');
gates.get('vendors?city=lagos').resolve(['Adaeze Fabrics', 'Balogun Textiles']);
const secondAnswer = await again;

// A failure is shared by every waiter, and evicted just the same.
const failing = api.load('vendors?city=kano');
const alsoFailing = api.load('vendors?city=kano');
gates.get('vendors?city=kano').reject(new Error('504 from upstream'));
const bothErrors = await Promise.all([failing.catch((e) => e.message), alsoFailing.catch((e) => e.message)]);
const clearedAfterFailing = api.size;

const retried = api.load('vendors?city=kano');
gates.get('vendors?city=kano').resolve(['Kano Traders']);
const afterRetry = await retried;

console.log('same promise?   :', sharedPromise);
console.log('requests made   :', asked);
console.log('shared failure  :', bothErrors);

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.

8 checks

test('two callers for one key hold the very same promise object', sharedPromise, true);
test('so three callers across two keys made two requests, both in flight', [requestsSoFar, inFlightNow], [2, 2]);
test('and the duplicate caller gets the identical value, not a second copy', [fromA === fromB, fromA, fromC], [true, ['Adaeze Fabrics'], ['Chidi Electronics']]);
test('a settled key is forgotten, so the map empties itself', clearedAfterSettling, 0);
test('which makes this a de-duplicator, not a cache: the next call really refetches', secondAnswer, ['Adaeze Fabrics', 'Balogun Textiles']);
test('a rejection reaches every waiter with the same message', bothErrors, ['504 from upstream', '504 from upstream']);
test('and finally() clears the key for a failure too, so a retry is possible', [clearedAfterFailing, afterRetry], [0, ['Kano Traders']]);
test('every request the loader was actually asked for, in order', asked, ['vendors?city=lagos', 'vendors?city=abuja', 'vendors?city=lagos', 'vendors?city=kano', 'vendors?city=kano']);

This is the smallest fix for the "three components, three identical requests" problem, and the second assertion is the measure of it: three load calls, two requests. It works because a promise is a value you can hand round — the second caller does not need its own request, it needs a reference to the one already running.

.finally() rather than .then() for the eviction is deliberate, and the seventh assertion is why. Clearing the key only on success leaves a rejected promise wedged in the map for ever, so every later caller instantly re-receives the same old error and the failure becomes permanent. A shared failure is correct; a cached one is not.

Note what this is not. There is no caching here at all: once the request settles, the key is gone, and the fifth assertion proves the next call reaches the loader. That separation is worth keeping — de-duplication is about concurrency, caching is about time, and the two have completely different invalidation rules. Exercise 90 does the caching half. The (async () => loader(key))() wrapper earns its keep on one edge: a loader that validates its arguments and throws synchronously. Called bare, that throw escapes load as an exception rather than a rejection, and the key is left in the map because .finally was never attached.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.