How-To Guide

How to Implement Request Coalescing

Deduplicate identical concurrent calls into a single upstream request so a burst of readers does not fan out into a burst of fetches.

On this page

  1. Introduction
  2. The Burst of Identical Calls
  3. A Map of In-Flight Requests
  4. Keying the Request Correctly
  5. Handling Failures
  6. Combining with Caching and Batching
  7. Observing Coalescing
  8. Conclusion

Introduction

When a popular item expires from a cache or a page opens with many widgets that each request the same resource, a burst of identical calls arrives at once. Without coordination each call fetches the same data, and the upstream sees ten, a hundred, or a thousand identical requests. Request coalescing collapses concurrent identical calls into one in-flight request and fans the single result out to every caller. The callers all get the answer they asked for, the upstream sees one request, and the burst disappears. This article shows how to implement coalescing with a map of in-flight promises, how to key it correctly, and how it interacts with caching and batching.

The Burst of Identical Calls

Identical calls arrive together whenever something synchronizes them: a shared cache entry expires and every request misses at the same instant, a dashboard renders a dozen components that each fetch the same slow resource, or a retry storm sends the same request repeatedly. Each caller is independent and each is correct in isolation, but together they multiply the load on a service that could have answered once.

Coalescing is not caching. A cache answers from stored data after a fetch has completed; coalescing deduplicates calls that are in flight at the same time. They complement each other: coalescing prevents the thundering herd at the moment of a miss, caching prevents the fetch entirely on later calls.

A Map of In-Flight Requests

The mechanism is a map from a request key to the promise of the in-flight operation. On a call, if the key is present, return the existing promise; otherwise start the operation, store its promise, and remove it when the operation settles, regardless of success or failure. Every concurrent caller for the same key awaits the same promise and receives the same result or the same error.

const inflight = new Map();   // key -> Promise

function coalesce(key, fn) {
  if (inflight.has(key)) return inflight.get(key);
  const promise = fn().finally(() => inflight.delete(key));
  inflight.set(key, promise);
  return promise;
}

// Many concurrent callers, one upstream request:
const [a, b, c] = await Promise.all([
  coalesce('user:42', () => fetch('/users/42').then((r) => r.json())),
  coalesce('user:42', () => fetch('/users/42').then((r) => r.json())),
  coalesce('user:42', () => fetch('/users/42').then((r) => r.json())),
]);
// a, b and c are the same object result from a single fetch.

Keying the Request Correctly

The key must capture everything that makes two calls equivalent. For a lookup it is the resource identity, such as user:42. If the call can return different results based on parameters, locale, authorization or version, those must be in the key, or two genuinely different requests will be merged and one caller gets the wrong data. Canonicalize the key: sort query parameters, normalize case where the backend is case-insensitive, and exclude parameters that do not affect the result.

Be careful with keys that include the user. If a key omits the tenant or user and the response is personalized, coalescing leaks one user’s data to another. When in doubt, include more in the key; a missed coalesce costs one extra request, a wrong merge costs a data leak.

Handling Failures

The shared promise carries the failure to every caller, which is usually the right behaviour: they all asked the same question and the upstream failed once. But it also means one transient failure becomes a fan-out of errors to all callers. Decide deliberately whether to let the error propagate to all, or to let each caller retry independently after the shared promise rejects.

Do not cache a rejected promise, which is why the finally block deletes the key when the operation settles. If a rejected promise stayed in the map, every subsequent call would receive the same stale error without retrying. The map must reflect only currently in-flight work.

Combining with Caching and Batching

Coalescing and caching stack naturally: check the cache first, and if it misses, coalesce the fetch and write the result to the cache when it completes. The cache also gives you a place to store a short negative result so a burst of lookups for a missing key does not hammer the upstream with misses. Keep the negative TTL short, because the key may appear at any moment.

Batching is a further step: instead of one upstream call per key, collect keys for a few milliseconds and issue a single call that fetches many. Batching reduces request count; coalescing reduces duplicate identical requests within the batch window. They can be combined, with coalescing ensuring no key is fetched twice and batching ensuring many keys go out together.

const cache = new Map();       // key -> { value, expiresAt }
const negative = new Map();    // key -> expiresAt for known misses

async function getUser(id) {
  const key = 'user:' + id;
  const hit = cache.get(key);
  if (hit && hit.expiresAt > Date.now()) return hit.value;
  if ((negative.get(key) ?? 0) > Date.now()) throw new Error('not found (cached)');

  try {
    const user = await coalesce(key, () => fetch('/users/' + id).then((r) => {
      if (r.status === 404) throw new NotFound();
      if (!r.ok) throw new Error('upstream: ' + r.status);
      return r.json();
    }));
    cache.set(key, { value: user, expiresAt: Date.now() + 30_000 });
    return user;
  } catch (err) {
    if (err instanceof NotFound) negative.set(key, Date.now() + 5_000);
    throw err;
  }
}

Observing Coalescing

Instrument the ratio of coalesced calls to upstream calls. A counter of callers and a counter of actual upstream requests tells you how much the deduplication saves; a ratio near one means few duplicates are arriving and coalescing is overhead, while a high ratio means it is doing real work. Alert when the upstream request rate spikes, which usually means keys are not matching and coalescing has stopped working.

Track the map size as a gauge. A map that keeps growing suggests entries are not being removed, which happens if a promise never settles or the cleanup is missing. A bounded map with a short-lived key set is healthy; an unbounded one is a leak waiting to happen.

Conclusion

Request coalescing collapses identical concurrent calls into one in-flight request, so a burst of readers does not fan out into a burst of fetches. Keep a map from a canonicalized key to the in-flight promise, delete the entry when the operation settles so failures are not cached, and include everything that affects the result in the key so distinct requests are never merged. Stack it with a cache and a short negative cache, consider batching for many keys, and measure the coalescing ratio so a broken key shows up as an upstream spike rather than a mystery.

Sources: Go singleflight package, Thundering herd problem, DataLoader (batching and caching).

FAQ

How is coalescing different from caching?
Coalescing merges calls that are in flight at the same instant so the upstream sees one request; caching answers from stored data after a fetch completed. They complement each other: coalescing handles the moment of a miss, caching handles later calls.
What should go into the coalescing key?
Everything that makes two calls equivalent: the resource identity plus any parameter, locale, tenant or version that changes the result. Include more when unsure, because a missed coalesce costs one request while a wrong merge can leak one user data to another.

Related Examples