Architecture
Request Coalescing: Serve Many Identical Requests With One Backend Call
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيA popular product page expires from cache at 12:00:00. In the next 200 milliseconds, 500 visitors ask for it. Without any protection, your reverse proxy forwards all 500 requests to the application, which runs the same five database queries 500 times and renders the same HTML 500 times. Every one of those requests wants the exact same answer. Request coalescing is the simple idea of noticing that, sending one request to the backend, and handing its result to everyone who was waiting.
What request coalescing means
Request coalescing (also called request collapsing or deduplication of in-flight requests) works like this:
- The first request for a key, such as a URL or a cache key, goes to the backend.
- Any identical request that arrives while the first is still in flight does not go to the backend. It waits.
- When the first response returns, it is delivered to every waiting caller, and usually stored in cache too.
The key difference from plain caching is timing. A cache helps once a response exists. Coalescing helps in the gap before it exists, which is exactly when cold caches and expiring keys cause load spikes. It is one of the main defences against the thundering herd problem.
Where coalescing happens
You can apply it at several layers, and they combine well.
| Layer | Tool or technique | Coalesces |
|---|---|---|
| Reverse proxy | Nginx proxy_cache_lock, Varnish (default) | Identical cacheable HTTP requests |
| CDN | Origin shield or request collapsing features | Edge misses heading to your origin |
| Application | singleflight pattern, shared promises | Expensive function calls per key |
| Data loader | DataLoader-style batching | Many lookups within one request |
Nginx: proxy_cache_lock
Nginx has coalescing built into its proxy cache. Enable it per location:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app:50m max_size=2g inactive=60m;
server {
location / {
proxy_pass http://127.0.0.1:8080;
proxy_cache app;
proxy_cache_valid 200 60s;
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
proxy_cache_lock_age 5s;
proxy_cache_use_stale updating error timeout;
proxy_cache_background_update on;
}
}What each directive does:
proxy_cache_lock onlets only one request per cache key populate a new entry; others wait for it.proxy_cache_lock_timeoutsets how long the waiters wait. After that they are passed to the backend, but their responses are not cached.proxy_cache_use_stale updatingserves the old copy while a fresh one is fetched, so nobody waits at all once an entry exists.proxy_cache_background_update onrefreshes expired entries in the background.
Together, a cache miss produces one backend call and an expired entry produces one background refresh. Reload with nginx -t && systemctl reload nginx.
Varnish coalesces identical requests by default through its waiting list. Be careful with responses marked uncacheable, though: if you mark them as hit-for-miss or hit-for-pass objects with a short TTL, Varnish will not serialise later requests behind them.
Application-level coalescing
Proxy caches only help with cacheable HTTP responses. For internal calls, such as an expensive report, a token refresh or a call to a slow third-party API, coalesce in code.
In Go, the golang.org/x/sync/singleflight package does it directly:
var g singleflight.Group
func getProduct(id string) (*Product, error) {
v, err, _ := g.Do("product:"+id, func() (any, error) {
return loadProductFromDB(id)
})
if err != nil {
return nil, err
}
return v.(*Product), nil
}In Node.js, keep a map of pending promises:
const inflight = new Map();
function getProduct(id) {
if (inflight.has(id)) return inflight.get(id);
const p = loadProductFromDB(id).finally(() => inflight.delete(id));
inflight.set(id, p);
return p;
}These protect a single process. If you run several app processes or servers, each will still make one call per key, which is usually fine. If it is not, add a short distributed lock in Redis using SET key value NX PX 5000 so only one process recomputes the value while the others read the cached result.
Pitfalls to avoid
- Personalised responses. Never coalesce requests whose responses differ by user. Make sure the cache key includes anything that changes the output, or bypass the cache for authenticated pages.
- Shared failures. If the single backend call fails or hangs, every waiter fails with it. Use timeouts and decide whether waiters retry on their own.
- Long lock waits. A slow backend plus a long lock timeout means users stare at spinners. Serving stale content is often better.
- Mutations. Coalesce reads only. Two
POSTrequests that look identical may be two real orders; use idempotency keys for those instead.
Checklist
- Identify hot, expensive, cacheable endpoints from your access logs.
- Enable
proxy_cache_lockandproxy_cache_use_stale updatingon them. - Wrap expensive internal calls in singleflight or a shared-promise map.
- Verify cache keys exclude no output-changing inputs.
- Load-test a cold cache with a tool like
wrkork6and compare backend request counts before and after.
FAQ
Is request coalescing the same as caching?
No. Caching stores a finished response for reuse later. Coalescing merges requests that arrive while the first response is still being produced. They work best together: coalescing protects the moment of a miss, and caching serves everything afterwards.
Does coalescing add latency for users?
Waiting requests take about as long as the original request, since they receive its result. That is usually faster than what they would get if hundreds of duplicate requests competed for the same database at once. Serving stale content during refreshes removes the wait entirely.
Can I use it for API calls that need authentication?
Yes, but only if the response is identical for every caller sharing the key. Include the user or tenant in the key when output differs, or coalesce only the shared underlying data fetch and apply per-user logic afterwards.