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 { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler,
Refreshing tokens with an Angular HttpInterceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
go
package ratelimit import ( "context"
A token bucket rate limiter in Go
rate-limiting
concurrency
goroutines
Intermediate
7 steps
python
from django.core.cache import cache from django.db.models import Count, Sum, Q from django.utils import timezone
Caching a Django dashboard aggregate query
caching
aggregation
conditional-queries
Intermediate
7 steps
ruby
class BulkImporter BATCH_SIZE = 500 def initialize(records)
Batching bulk inserts in Rails
batching
bulk-insert
deduplication
Intermediate
5 steps
typescript
type StorageSchema = Record<string, unknown>; interface StorageOptions { namespace?: string;
A type-safe wrapper around localStorage
generics
type-safety
serialization
Intermediate
9 steps
go
package cache import ( "context"
Cache-aside reads with singleflight in Go
caching
singleflight
concurrency
Advanced
8 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.