Skip to main content

Import

import { RequestDeduplicator } from "bytekit/request-deduplicator";

Constructor

const dedup = new RequestDeduplicator(config?);

Config options

PropertyTypeDefaultDescription
keyGenerator(key: string) => stringCustom function to normalize or transform deduplication keys

Methods

MethodReturnsDescription
execute<T>(key, fn, options?)Promise<T>Runs fn once per unique in-flight key. Concurrent calls with the same key receive the same promise.
getStats()DeduplicatorStatsReturns deduplication counters
getInFlightCount()numberNumber of requests currently in progress
clear()voidCancels tracking of all in-flight keys
resetStats()voidResets hit counters to zero

getStats return value

PropertyTypeDescription
deduplicatedCountnumberNumber of calls that reused an existing in-flight promise
totalRequestsnumberTotal number of execute calls

Examples

Deduplicate parallel fetches

When multiple UI components mount at the same time and each requests the current user, only one network call is made.
import { ApiClient } from "bytekit/api-client";
import { RequestDeduplicator } from "bytekit/request-deduplicator";

const api = new ApiClient({ baseUrl: "https://api.example.com" });
const dedup = new RequestDeduplicator();

// Both calls share a single HTTP request
const [sidebar, header] = await Promise.all([
  dedup.execute("/me", () => api.get("/me")),
  dedup.execute("/me", () => api.get("/me")),
]);

Custom key generator

const dedup = new RequestDeduplicator({
  keyGenerator: (key) => key.toLowerCase().replace(/\/+$/, ""),
});

// These resolve to the same in-flight request
dedup.execute("/Users/1", () => api.get("/users/1"));
dedup.execute("/users/1/", () => api.get("/users/1"));

Monitoring deduplication

const stats = dedup.getStats();
console.log(`Saved ${stats.deduplicatedCount} redundant requests`);
console.log(`Total calls: ${stats.totalRequests}`);
console.log(`In-flight right now: ${dedup.getInFlightCount()}`);

Integration with ApiClient interceptors

const dedup = new RequestDeduplicator();

const api = new ApiClient({
  baseUrl: "https://api.example.com",
  interceptors: {
    request: async (url, init) => {
      // Only deduplicate GET requests
      if (init.method === "GET") {
        return dedup.execute(url, () => [url, init]);
      }
      return [url, init];
    },
  },
});
Combine RequestDeduplicator with RequestCache for maximum efficiency: the deduplicator collapses concurrent in-flight calls, while the cache serves repeated reads from memory.
Once the underlying promise settles, the next execute call with the same key will invoke fn again. Deduplication only applies while the original call is still in flight.