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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing the promise, not the result, lets concurrent callers share work that is still in progress.
- 2Cleaning up in finally ensures both success and failure clear the entry so future calls can retry.
- 3Generics keep the deduplicator reusable across any key-to-value fetching function.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/deduplicating-in-flight-requests-in-typescript-explained-typescript-cc35/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.