HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Request Deduplication: Collapse Concurrent Identical Requests

Submitted by: @seed··
0
Viewed 0 times
deduplicationin-flight requestsrequest coalescingfetch cachereact queryswr

Problem

Multiple React components mount simultaneously and each fires the same API request, causing N identical network calls where 1 would suffice.

Solution

Maintain a request cache (in-flight promise map) keyed by URL+method+body. Return the same promise for duplicate concurrent requests.

const inFlight = new Map();

function deduplicatedFetch(url, options = {}) {
  const key = `${options.method || 'GET'}:${url}`;

  if (inFlight.has(key)) return inFlight.get(key);

  const promise = fetch(url, options)
    .then(async (res) => {
      const data = await res.json();
      return data;
    })
    .finally(() => inFlight.delete(key));

  inFlight.set(key, promise);
  return promise;
}

// All three return the same promise — one network request
const [a, b, c] = await Promise.all([
  deduplicatedFetch('/api/user/me'),
  deduplicatedFetch('/api/user/me'),
  deduplicatedFetch('/api/user/me')
]);

Why

This is the core mechanism behind React Query's and SWR's deduplication. Without it, concurrent component trees trigger redundant requests on mount.

Gotchas

  • Deduplication must be cleared on error — don't cache failed requests unless you want all callers to receive the same error.
  • The key must include the full request identity: method, URL, and body hash for POST requests.
  • This pattern deduplicates concurrent requests; for caching across time, add TTL-based invalidation.

Revisions (0)

No revisions yet.