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);
  }
}

Fifty concurrent requests for the same missing key fire fifty identical expensive calls, multiplying load exactly when the system is weakest.

Use case: engineers whose cache misses stampede under concurrency

Inputs / outputs

  • Input: a key string and a loader function returning a promise
  • Output: the shared promise result for every caller of the same key while in flight

Error conditions

  • loader rejects (all waiters receive the same rejection)
  • key is empty

Approach

keep a Map of in-flight promises keyed by the call key; on miss start the loader and delete the entry in a finally block so the next call starts fresh.

Implementation

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);
  }
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { SingleFlight } from "./example.ts";

test("collapses concurrent identical calls into one loader run", async () => {
  const flight = new SingleFlight();
  let calls = 0;
  const loader = async () => {
    calls += 1;
    await new Promise((r) => setTimeout(r, 20));
    return "value";
  };
  const results = await Promise.all([
    flight.run("k", loader),
    flight.run("k", loader),
    flight.run("k", loader),
  ]);
  assert.deepEqual(results, ["value", "value", "value"]);
  assert.equal(calls, 1);
});

test("shares the loader rejection with every waiter", async () => {
  const flight = new SingleFlight();
  const loader = async () => {
    await new Promise((r) => setTimeout(r, 10));
    throw new Error("boom");
  };
  const settled = await Promise.allSettled([
    flight.run("k", loader),
    flight.run("k", loader),
  ]);
  assert.deepEqual(settled.map((s) => s.status), ["rejected", "rejected"]);
  assert.equal(flight.pending("k"), false);
});

test("a later call after settle starts a fresh run", async () => {
  const flight = new SingleFlight();
  let calls = 0;
  const loader = async () => {
    calls += 1;
    return calls;
  };
  const first = await flight.run("k", loader);
  const second = await flight.run("k", loader);
  assert.equal(first, 1);
  assert.equal(second, 2);
});

test("rejects an empty key", async () => {
  const flight = new SingleFlight();
  await assert.rejects(flight.run("", async () => 1), TypeError);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts

Limitations and error handling

in-process only; no cross-instance dedupe; no request coalescing window beyond in-flight time.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic