How to Batch and Coalesce HTTP Requests
Collapse duplicate in-flight requests with singleflight, merge small calls into batch endpoints, and keep failure semantics honest at the merge point.
On this page
Introduction
Two distinct pathologies make outbound HTTP traffic expensive. The first is duplication: one hundred concurrent requests all asking for the same uncached resource, a cache stampede or a page where every widget independently fetches the same session object. The second is granularity: one hundred distinct but tiny requests, each paying its own round trip, headers, and serialization, where one bulk call would do. The fixes are different and often confused. Coalescing, the singleflight pattern, collapses concurrent identical requests into one upstream call and fans the single result back to every waiter. Batching collects distinct requests over a short window and sends them as one request to a bulk endpoint. This tutorial implements both, shows where each pays off, and spends equal time on the part teams skip: what happens when the merged call fails, because failure semantics at the merge point are where both patterns get dangerous.
Measure the duplication first
Before implementing either pattern, establish which pathology dominates, because the wrong one adds latency without removing load. Instrument outbound calls with two dimensions: the request key and the timestamp. Group requests by key within a short sliding window, say five milliseconds. A key with forty concurrent copies is coalescing material: those forty calls can become one. Many distinct keys each called once per page load is batching material if the target supports a bulk API. Many distinct keys with low concurrency is neither: the cost is inherent round trips, and the fix is caching or payload redesign, not merging. This measurement also yields the expected win: forty concurrent copies collapsing to one removes ninety-seven percent of upstream calls for that key, which is worth the complexity, while merging three requests saves two round trips and probably is not.
Coalesce with singleflight
The singleflight pattern keeps a map from key to in-flight promise. The first caller creates the promise and starts the real request; concurrent callers with the same key receive the same promise instead of starting their own. When the request settles, the result fans out to everyone and the key is removed so the next wave starts fresh. Go ships this in the standard extension library, and the implementation is a useful reference in any language.
import "golang.org/x/sync/singleflight"
var group singleflight.Group
func GetUser(ctx context.Context, id string) (*User, error) {
v, err, shared := group.Do("user:"+id, func() (interface{}, error) {
return fetchUserFromAPI(ctx, id)
})
if err != nil {
return nil, err
}
metrics.SingleflightShared(shared)
return v.(*User), nil
}
The shared return value reports whether the call was deduplicated, which is worth exporting as a metric because it directly measures the pattern paying for itself. In TypeScript the same structure is a map of promises guarded so the entry is deleted on settlement, including on rejection, or a failed request poisons the key forever.
const inflight = new Map<string, Promise<unknown>>();
export async function coalesce<T>(key: string, run: () => Promise<T>): Promise<T> {
const existing = inflight.get(key);
if (existing) return existing as Promise<T>;
const p = run().finally(() => inflight.delete(key));
inflight.set(key, p);
return p;
}
Batch distinct requests
Batching trades a small, fixed wait for fewer round trips. The wrapper accumulates requests for a window of a few milliseconds, then issues one bulk call and routes results back by position or by id. The endpoints that benefit are ones with a natural bulk form: fetching twenty products by id list, resolving fifty slugs, checking availability for a set of dates. The window must be tiny because it is latency added to every participant, including the first request that arrives when the batch would otherwise be empty.
type Pending = { id: string; resolve: (v: unknown) => void; reject: (e: Error) => void };
export class BatchCollector {
private pending: Pending[] = [];
private timer: NodeJS.Timeout | null = null;
constructor(private send: (ids: string[]) => Promise<Map<string, unknown>>,
private windowMs = 5) {}
fetch(id: string): Promise<unknown> {
return new Promise((resolve, reject) => {
this.pending.push({ id, resolve, reject });
if (!this.timer) {
this.timer = setTimeout(() => this.flush(), this.windowMs);
}
});
}
private async flush() {
this.timer = null;
const batch = this.pending;
this.pending = [];
try {
const results = await this.send(batch.map(p => p.id));
for (const p of batch) {
const value = results.get(p.id);
if (value === undefined) p.reject(new Error('missing in batch: ' + p.id));
else p.resolve(value);
}
} catch (err) {
for (const p of batch) p.reject(err as Error);
}
}
}
Note the missing-entry path: a bulk endpoint that silently omits failed items turns a partial failure into a hang. Reject explicitly for absent ids so callers see an error rather than a promise that never settles.
Failure semantics at the merge point
Merging requests merges their failure domains, and this is the cost that decides whether the pattern is net positive. With coalescing, one failed upstream call fails every concurrent waiter simultaneously. That is usually acceptable, because those waiters would have issued the same request and received the same failure, but it concentrates retry storms: if all forty waiters retry after backoff, the herd re-forms. Add jittered backoff at the caller, or a single retry inside the singleflight function, so the merged call retries once for everyone rather than forty times in parallel. With batching, the failure question is partial: does one bad id fail the whole batch? Prefer endpoints that return per-item results with individual error fields, and reject only the failed items locally. If the endpoint is all-or-nothing, one invalid id breaks every participant, so validate before adding to the batch. Timeouts compose badly in both patterns: the merged call needs its own budget, and callers waiting on a shared promise cannot be cancelled individually, so document that cancellation propagates to the group.
Compose with caching
Coalescing and caching solve different halves of duplication. The cache removes repeat requests across time; singleflight removes concurrent duplicates during the cold or expired window, which is exactly when the cache cannot help. Composing them is a one-line change with a large effect on thundering herds: check the cache, then enter singleflight for the miss, then populate the cache inside the flight.
async function getUser(id: string): Promise<User> {
const hit = cache.get(userKey(id));
if (hit) return hit;
const user = await coalesce(userKey(id), async () => {
const fetched = await api.getUser(id);
cache.set(userKey(id), fetched, 30_000);
return fetched;
});
return user;
}
Without the singleflight wrapper, an expired hot key triggers one upstream request per concurrent caller the instant it expires, which is the cache stampede. With it, the expiry costs exactly one upstream call, and the remaining callers receive the freshly cached value. This combination is the highest-leverage version of the whole pattern and should be the default shape for any read-through cache in front of an expensive dependency.
Test the merge points
Both patterns fail in ways that only appear under concurrency, so tests must exercise the concurrent path directly. For coalescing: fire one hundred calls with the same key while the upstream responds after a delay, and assert the upstream counter shows exactly one. Then reject the upstream call and assert every waiter receives the rejection and that a subsequent call succeeds, proving the in-flight entry was cleaned up. For batching: submit items with staggered arrival times and assert batch composition follows the window; submit a batch where the endpoint omits one id and assert that item rejects while others resolve; and assert the flush survives the send promise rejecting, by checking the next window still collects. Use deterministic clocks or controllable promises, because timing-sensitive merge logic is untestable with real sleeps and flaky under load.
let upstreamCalls = 0;
const fetcher = async (id: string) => {
upstreamCalls += 1;
await tick(20);
return { id };
};
await Promise.all(Array.from({ length: 100 }, () => coalesce('u:1', () => fetcher('u:1'))));
expect(upstreamCalls).toBe(1);
Common pitfalls
- Leaking in-flight entries on rejection. A singleflight map that is not cleaned in the failure path poisons the key permanently.
- Batch windows measured in tens of milliseconds. Every participant pays the window; keep it single-digit or skip batching.
- Merging non-idempotent calls. Coalescing writes that callers expect to execute once each changes semantics silently; reserve merging for reads.
- Silent partial batch results. An endpoint that omits failed items converts a partial failure into a hung promise for those callers.
- No jitter on merged retries. All waiters retry in lockstep and the herd re-forms at the upstream.
- Batching without measuring. Merging three cheap distinct calls adds a window and saves almost nothing.
Conclusion
Coalescing and batching are precise tools for measured problems. Instrument outbound traffic by key and by time, and let the numbers choose: duplicated keys want singleflight, where one upstream call serves every concurrent waiter and the map must be cleaned on failure as reliably as on success. Many distinct small calls want a short batching window and a bulk endpoint, with per-item errors preserved so a partial failure stays partial. In both cases, design the merge-point failure semantics deliberately, because merged requests share a failure domain, and retry jitter is what keeps a merged failure from becoming a synchronized herd. Compose coalescing with caching as the default read-through shape, and test the concurrent paths with deterministic clocks, because that is the only place these patterns actually live.
Sources: singleflight package docs, Brandur: singleflight caching, MDN: Promise reference.
FAQ
- What is the difference between coalescing and batching?
- Coalescing merges concurrent requests with the same key into one upstream call and fans the result back out. Batching groups different requests over a time window into one call. Coalescing removes duplicates; batching removes round trips.
- How long should a batching window be?
- Single-digit milliseconds, typically two to ten. The window is pure added latency for every participant, so it must stay far below the round trip it saves while still collecting enough requests to matter.
- Does singleflight break caching layers?
- They compose well. Singleflight deduplicates concurrent misses, and the cache deduplicates across time. Fill the cache through the singleflight wrapper so a cold key pays one upstream call even under a thundering herd.
Report a problem with this articleOpens a pre-filled issue on GitHub.