53Implement request deduplication for identical in-flight API calls
Problem
Three components mount at the same time and each calls getUser(42). Without care, that is three identical network requests.
Implement dedupe(fn, getKey). It returns a function with the same signature as the async fn. While a call for a given key is in flight, further calls with the same key get the same promise instead of calling fn again. Once that promise settles, the entry is removed, so the next call makes a fresh request.
getKey(...args) defaults to JSON.stringify(args).
const getUser = dedupe((id) => fetch(`/api/users/${id}`).then((r) => r.json()));
const [a, b, c] = await Promise.all([getUser(42), getUser(42), getUser(42)]); // one requestRequirements
- Concurrent calls with the same key share one call to
fnand one promise. - Different keys run independently.
- After the shared promise settles (fulfilled or rejected), the next call calls
fnagain. This is deduplication, not caching. - A failure is delivered to every waiting caller.
- If
fnthrows synchronously, the call rejects and nothing stays stuck in flight.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Press Run or ⌘ Enter to execute your code.
Step-by-step
Keep const inFlight = new Map(). The value is the promise of the call currently running for that key.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.