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).
| System | Switch | Default | What the docs say |
|---|---|---|---|
| Go singleflight | Group.Do, DoChan, Forget | Opt in | One execution in flight per key |
| nginx | proxy_cache_lock | off | One request at a time fills a new cache element; others wait |
| nginx | proxy_cache_lock_timeout | 5s | After it, the request goes to the origin uncached (since 1.7.8) |
| nginx | proxy_cache_lock_age | 5s | If the lock holder is still running, one more request may go to the origin |
| Varnish | built in (waiting list) | on for cacheable requests | Duplicates wait on a waiting list; hit-for-miss (TTL two minutes by default) bypasses it |
| Squid | collapsed_forwarding | off | Forwards only the first request for a URL; off because it can needlessly delay requests |
| Fastly | req.hash_ignore_busy to opt out | on for cache misses | Pass and hit-for-pass are not collapsed; hit-for-pass default TTL is 2 minutes |
| Cloudflare | cache lock | automatic | One 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 second | Backend latency | Calls without | Calls with | Mean wait of the burst |
|---|---|---|---|---|
| 100 | 200 ms | 20 | 1 | 105 ms |
| 1,000 | 200 ms | 200 | 1 | 100.5 ms |
| 1,000 | 50 ms | 50 | 1 | 25.5 ms |
| 5,000 | 200 ms | 1,000 | 1 | 100.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.
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,
Resultholds oneValand oneErr, 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 afterproxy_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 treatsprivateas 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.
| Technique | What it merges or avoids | Waiting? | Typical tool |
|---|---|---|---|
| Caching | Repeats after the answer exists | No | Redis, CDN, proxy_cache |
| Request coalescing | Identical requests during the first fetch | Yes, on the leader | singleflight, proxy_cache_lock, Varnish |
| Batching (DataLoader) | Different keys in one tick, one call | Yes, until the batch fires | GraphQL DataLoader |
| Stale-while-revalidate / grace | Serves the old value while one request refreshes it | No | proxy_cache_use_stale updating, Varnish grace |
| Probabilistic early expiration | Refreshes before the expiry time | No | XFetch (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.shielddoes 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
- What are different cache invalidation strategies?
- What is caching and why is it important in system design?
- What is the Circuit Breaker pattern?
- How do you handle content updates with a CDN?
- Design a distributed caching system
- All system design interview questions
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.
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.