typescript 33 lines · 7 steps

Deduplicating in-flight requests in TypeScript

A small class that collapses concurrent calls for the same key into a single shared promise.

Explained by highlit
1type Fetcher<T> = (key: string) => Promise<T>;
2 
3export class RequestDeduplicator<T> {
4 private inFlight = new Map<string, Promise<T>>();
5 
6 constructor(private readonly fetcher: Fetcher<T>) {}
7 
8 async request(key: string): Promise<T> {
9 const existing = this.inFlight.get(key);
10 if (existing) {
11 return existing;
12 }
13 
14 const promise = this.fetcher(key).finally(() => {
15 this.inFlight.delete(key);
16 });
17 
18 this.inFlight.set(key, promise);
19 return promise;
20 }
21 
22 get pending(): number {
23 return this.inFlight.size;
24 }
25}
26 
27export const userLoader = new RequestDeduplicator(async (id: string) => {
28 const res = await fetch(`/api/users/${id}`);
29 if (!res.ok) {
30 throw new Error(`Failed to load user ${id}: ${res.status}`);
31 }
32 return res.json();
33});
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing the promise, not the result, lets concurrent callers share work that is still in progress.
  2. 2Cleaning up in finally ensures both success and failure clear the entry so future calls can retry.
  3. 3Generics keep the deduplicator reusable across any key-to-value fetching function.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Deduplicating in-flight requests in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code