Request Coalescing Explained With Code | Skill-Lync Resources
Medium System Design Caching Strategies

What is request coalescing and when should you use it?

By the Skill-Lync engineering team · Last updated

Answer

Request coalescing merges identical concurrent requests into one backend call. The first request becomes the leader and the others wait and share its result. It stops a cache stampede on a cold or expired key. Use it for expensive, shareable reads, never for personalised responses, and always time-box the wait.

What is request coalescing?

Request coalescing merges identical requests that are in flight at the same moment into one backend call. The first request for a key becomes the leader and does the work. Every other request for that key becomes a follower, waits, and receives the leader's result. Also called request collapsing or single-flight.

Why is a cold or expired cache key dangerous?

When a hot key is missing from the cache, every request that arrives before the first refill finishes also sees a miss and calls the backend. That pile-up is a thundering herd or cache stampede. The slower the backend, the longer the window.

Vattani, Chierichetti and Lowenstein (VLDB 2015) call it a cascading failure: the extra concurrent recomputations slow each recomputation down, which pulls even more requests into the stampede.

How does request coalescing work?

Keep a table of in-flight work keyed by what makes two requests identical. A request that finds no entry creates one and runs the backend call. A request that finds an entry waits on it. When the call finishes, the result goes to all waiters and the entry is removed, so the next miss starts a fresh call.

That is the contract of Go's golang.org/x/sync/singleflight: Do(key, fn) makes sure only one execution is in flight for a given key at a time, and shared reports whether the result went to multiple callers. Here is the idea in Python asyncio. Skill-Lync's verify script really runs it.

import asyncio

class SingleFlight:
    def __init__(self):
        self._inflight = {}

    async def do(self, key, fn):
        task = self._inflight.get(key)
        if task is None:  # first caller becomes the leader
            task = asyncio.ensure_future(fn())
            self._inflight[key] = task
            task.add_done_callback(lambda _t: self._inflight.pop(key, None))
        return await asyncio.shield(task)  # everyone awaits the same task

calls = 0

async def load_user():  # stands in for the slow backend
    global calls
    calls += 1
    await asyncio.sleep(0.05)
    return {"id": 42}

async def main():
    sf = SingleFlight()
    results = await asyncio.gather(*(sf.do("user:42", load_user) for _ in range(100)))
    print(calls, len(results))

asyncio.run(main())

It prints 1 100: 100 concurrent callers, 1 backend call. The asyncio.shield matters. Without it, one follower that times out would cancel the shared task and fail everyone else.

Where does coalescing live in a real system?

At three layers. Inside one process, a library such as Go's singleflight collapses duplicate calls from that process only. In a reverse proxy such as nginx, Varnish or Squid, it collapses duplicates across all clients of that proxy. In a CDN, it collapses duplicates per data center or per cache node before the origin sees them.

Each layer sees only its own traffic, so they stack. Defaults below are from vendor docs (checked 23 Nov 2026).

SystemSwitchDefaultWhat the docs say
Go singleflightGroup.Do, DoChan, ForgetOpt inOne execution in flight per key
nginxproxy_cache_lockoffOne request at a time fills a new cache element; others wait
nginxproxy_cache_lock_timeout5sAfter it, the request goes to the origin uncached (since 1.7.8)
nginxproxy_cache_lock_age5sIf the lock holder is still running, one more request may go to the origin
Varnishbuilt in (waiting list)on for cacheable requestsDuplicates wait on a waiting list; hit-for-miss (TTL two minutes by default) bypasses it
Squidcollapsed_forwardingoffForwards only the first request for a URL; off because it can needlessly delay requests
Fastlyreq.hash_ignore_busy to opt outon for cache missesPass and hit-for-pass are not collapsed; hit-for-pass default TTL is 2 minutes
Cloudflarecache lockautomaticOne origin request per asset per data center; the rest wait

In nginx, pair the lock with proxy_cache_use_stale updating (default off), which serves the stale copy of an expired item while one request refreshes it, and proxy_cache_background_update on (default off) to refresh in a background subrequest. Varnish's grace mode does the same.

How many backend calls does it save?

It saves every duplicate that arrives while the first call is still running. In the simulation below, 1,000 requests per second hit a cold key and the backend needs 200 ms, so 200 requests arrive before the first answer lands. Without coalescing that is 200 backend calls. With it, 1.

Simulation, not a measurement. Requests arrive evenly spaced for one second, the backend always takes the stated time, and the key is cached the instant the first answer arrives. Calls without coalescing = arrivals earlier than the latency = ceil(rate x latency / 1000).

Requests per secondBackend latencyCalls withoutCalls withMean wait of the burst
100200 ms201105 ms
1,000200 ms2001100.5 ms
1,00050 ms50125.5 ms
5,000200 ms1,0001100.1 ms

The cost is dependence. In the 1,000 per second row the first request waits 200 ms, the 200th waits 1 ms, and the mean is 100.5 ms, so nobody is slower than with their own call. But all 200 now depend on one call: if it is slow or fails, they all are.

Simulated backend calls for a cold key at 200 ms latency, by request rate, with and without coalescing 100 / s20 calls 500 / s100 calls 1,000 / s200 calls 2,000 / s400 calls 5,000 / s1,000 calls With coalescing: 1 call at every rate
Simulated, 200 ms backend latency. Bars: 1 px per 5 calls (minimum 4 px).

Try it: a burst on a cold key

Same model as the table (a simulation): move the sliders and replay.

What can go wrong with request coalescing?

Five things. Followers queue behind a slow leader. A failed leader fails everyone. A wait with no timeout can hang requests. A key that ignores who is asking can leak one user's data. And an unshareable response makes the queue run one request at a time.

  • Head-of-line waiting. Fastly warns that collapsing queues requests and can slow response times. Varnish says request serialization causes extra latency and can become a bottleneck.
  • Leader failure and fan-out of errors. In Go's singleflight, Result holds one Val and one Err, so every caller on that key gets the leader's error. The Python version above does the same: one failed call, 100 failed requests.
  • Timeouts. nginx bounds the wait with proxy_cache_lock_timeout (5s default) and lets a second request start after proxy_cache_lock_age (5s default). Set your own deadline on every follower.
  • Personalised responses. The key must contain everything that changes the response. nginx shares by proxy_cache_key. Fastly treats private as good for only one user and processes the queued requests individually. Coalesce by URL alone and user A's page can reach user B.
  • Uncacheable responses. If the reply cannot be shared, the queue drains serially. Varnish's hit-for-miss and Fastly's hit-for-pass markers (both 2 minutes by default) remember the key is uncacheable so later requests skip the queue.

How is coalescing different from caching, batching and early expiry?

Caching remembers an answer once it exists. Coalescing protects the moment before it exists. Batching merges different keys into one call; coalescing merges the same key. Stale-while-revalidate and early expiration avoid the cold moment, so they pair well with coalescing.

TechniqueWhat it merges or avoidsWaiting?Typical tool
CachingRepeats after the answer existsNoRedis, CDN, proxy_cache
Request coalescingIdentical requests during the first fetchYes, on the leadersingleflight, proxy_cache_lock, Varnish
Batching (DataLoader)Different keys in one tick, one callYes, until the batch firesGraphQL DataLoader
Stale-while-revalidate / graceServes the old value while one request refreshes itNoproxy_cache_use_stale updating, Varnish grace
Probabilistic early expirationRefreshes before the expiry timeNoXFetch (Vattani et al.)

The GraphQL DataLoader README says it will coalesce all individual loads which occur within a single frame of execution into one call to your batch function. That is batching: different keys, one call.

XFetch, the algorithm in the Vattani paper, has each request roll a die before expiry. A request recomputes early when Time() - delta * beta * log(rand()) >= expiry, where delta is how long the last recomputation took, rand() is a uniform random number between 0 and 1 and beta defaults to 1. Slow items are refreshed earlier, so a few requests recompute before expiry instead of the whole crowd after it. No lock, no waiting, but it cannot help a key that was never cached or was just evicted. That is where coalescing still pays.

When should you use request coalescing?

Use it when many callers ask for the same key, the backend call is slow or costly, and the result is safe to share. Skip it for personalised or write requests, for very cheap calls, and when making a duplicate call is better than waiting on someone else's.

A practical order: cache first, add stale serving, add coalescing for cold moments (deploys, restarts, evictions, new keys), and early expiry for the few hot, expensive keys. Put a deadline on every wait, and add a circuit breaker: coalescing cannot fix a backend that is down.

Common interview follow-ups

What if the leader's request is cancelled by its client?
The shared work must not die with it. Run the fetch under its own task, as asyncio.shield does above, so one impatient client cannot fail all the followers.
How do you make coalescing safe for per-user data?
Put the user, tenant or any varying header into the key, or skip coalescing on that route.
Why not just use a distributed lock?
A lock stops duplicate work but followers still need the result. Cloudflare's engineers note that a shared cache lock adds latency and can itself be unavailable.

Keep reading

Build and scale real backend systems

Skill-Lync's Microservices with Java, Spring and Docker course covers service calls and resilience hands-on. Broader paths: full stack web development and cloud computing.

View the course
Master These Concepts with IIT Certification
IIT Certified

Master These Concepts with IIT Certification

175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.

Relevant for Roles

Software Engineer Backend Developer Performance Engineer