Single Flight Dedupe For Concurrent Calls

A single-flight map that collapses concurrent identical calls into one in-flight request and shares its result with every caller.

TypescriptResilience

Code

export class SingleFlight {
  private readonly inFlight = new Map<string, Promise<unknown>>();

  async run<T>(key: string, loader: () => Promise<T>): Promise<T> {
    if (!key) throw new TypeError("key must be a non-empty string");
    const existing = this.inFlight.get(key);
    if (existing) return existing as Promise<T>;
    const started = (async () => {
      try {
        return await loader();
      } finally {
        this.inFlight.delete(key);
      }
    })();
    this.inFlight.set(key, started);
    return started;
  }

  pending(key: string): boolean {
    return this.inFlight.has(key);
  }
}