Prevent CDN Cache Stampedes with Origin Shield and Request Collapsing

by Fahim Mahmud Chisti

A CDN cache stampede happens when a popular cache entry expires in the middle of a traffic spike. Every edge server misses at once, hundreds of identical requests hit the backend together, and the origin answers with 504 gateway timeouts. This guide shows how to stop it with request collapsing, stale-while-revalidate and an origin shield, and how to test that the fix holds.

Quick answer: Let only one request refresh an expired item while everyone else gets the cached copy. In Nginx that means proxy_cache_lock on plus proxy_cache_use_stale updating; at the CDN it means stale-while-revalidate headers and an origin shield that funnels all edge misses through one cache.

  1. Add proxy_cache_lock on; to the caching location in Nginx.
  2. Add proxy_cache_use_stale updating and proxy_cache_background_update on;.
  3. Send Cache-Control with stale-while-revalidate from your app.
  4. Turn on your CDN’s origin shield (or tiered cache), or run your own shield proxy.
  5. Stop cache keys from splitting on Vary, encoding and query order, then load-test while entries expire.
In this guide
  1. Before You Start
  2. What a Cache Stampede Actually Looks Like
  3. Layer 1: Enable Request Collapsing (Proxy Cache Locking)
  4. Layer 2: Refresh in the Background with stale-while-revalidate
  5. Layer 3: Put an Origin Shield Between Edge PoPs and Origin
  6. Test It: Simulate a Cache Stampede with k6
  7. Still Leaking Requests? Check Vary Headers and Cache Keys
  8. Frequently Asked Questions
  9. Next Steps
Server rack status indicators and network cables showing origin shield traffic handling

Before You Start

  • Root or sudo access to the Nginx server that sits in front of your app, and access to your CDN’s dashboard if you use one.
  • A staging copy of the site, or a quiet period. A wrong cache rule can serve stale or wrong content to every visitor.
  • A backup of your Nginx config, for example sudo cp -r /etc/nginx /etc/nginx.bak.
  • About an hour, including the load test.

What a Cache Stampede Actually Looks Like

A cache stampede (or thundering herd) happens when a high-traffic cache key expires while requests are still pouring in. Instead of one request refreshing the cache while others wait, every incoming request is forwarded straight to your origin.

For example, if your CDN has 45 edge PoPs (Points of Presence, the CDN’s local data centres) and each one gets 30 simultaneous hits for an expired page, your backend receives 1,350 identical database queries or rendering jobs at almost the same moment. CPU usage climbs to 100%, the event loop stalls, and the origin starts returning 504 gateway timeout errors.

Stopping this requires fixing two specific bottlenecks:

  • At the edge: Forcing concurrent incoming requests on any single PoP to share one upstream fetch (Request Collapsing).
  • Across the network: Funneling cache misses across all global PoPs through one intermediate caching layer before anything touches your database (Origin Shielding).

Layer 1: Enable Request Collapsing (Proxy Cache Locking)

Request collapsing means that when 500 requests hit a proxy for an uncached item, only the first one goes upstream. The proxy holds the other 499 until that first response comes back, then serves all of them from the fresh cache entry.

In Nginx, you handle this with the proxy_cache_lock directives. Save this on the proxy server as /etc/nginx/conf.d/caching-proxy.conf, with your own domain and upstream port:

# /etc/nginx/conf.d/caching-proxy.conf
proxy_cache_path /var/cache/nginx/edge levels=1:2 keys_zone=edge_cache:100m max_size=10g inactive=24h use_temp_path=off;
upstream origin_backend {
    server 127.0.0.1:3000;
}
server {
    listen 80;
    server_name api.example.com;
    location / {
        proxy_pass http://origin_backend;
        proxy_cache edge_cache;
        proxy_cache_key $scheme$request_method$host$request_uri;
        proxy_cache_valid 200 301 302 10m;
        # Request Collapsing directives
        proxy_cache_lock on;
        proxy_cache_lock_timeout 5s;
        proxy_cache_lock_age 5s;
        # Headers to help debug edge behavior
        add_header X-Cache-Status $upstream_cache_status always;
        add_header X-Proxy-Host $hostname always;
    }
}

Here is what these directives actually do when traffic spikes:

  • proxy_cache_lock on;: Tells Nginx that only one request can populate a new cache entry at a time.
  • proxy_cache_lock_timeout 5s;: If the upstream request takes longer than 5 seconds, Nginx unblocks the waiting requests and lets them pass through to origin so clients do not hang forever. Those responses are not cached.
  • proxy_cache_lock_age 5s;: If the request populating the cache has not completed after 5 seconds, Nginx lets one more request through to the origin.

Apply it with sudo nginx -t && sudo systemctl reload nginx. Then request a URL that returns 200, such as curl -I http://api.example.com/api/v1/posts, twice: the first response should show X-Cache-Status: MISS and the second X-Cache-Status: HIT.

One limit matters for stampedes: the lock only covers keys that have no cache entry at all. When an existing entry expires, Nginx does not queue requests behind the lock, so you also need the proxy_cache_use_stale updating setup from the next layer.

Layer 2: Refresh in the Background with stale-while-revalidate

Request collapsing protects the database, but the first visitor, and anyone queued behind the lock, still waits for a full trip to the origin. You can avoid that wait with the stale-while-revalidate and stale-if-error cache directives defined in RFC 5861.

With stale-while-revalidate, a CDN that supports the directive serves the stale cached copy immediately and fetches a fresh one from your origin in the background for later requests. Support and its limits differ between CDNs, so check your provider’s documentation.

Set this directly in your application responses. Here is an Express / Node.js example:

// Express route returning stale-while-revalidate directives
app.get('/api/v1/posts', async (req, res) => {
  const posts = await fetchTrendingPostsFromDatabase();
  // Fresh for 60s, stale allowed for 300s, stale on 5xx errors for 24h
  res.set({
    'Cache-Control': 'public, max-age=60, stale-while-revalidate=300, stale-if-error=86400',
    'Content-Type': 'application/json'
  });
  res.json({ data: posts });
});

If you run your own Nginx caching proxy, add these two lines inside the same location block as Layer 1, so Nginx serves stale content while it updates in the background:

# Add to your Nginx location block
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;

The updating parameter tells Nginx to serve stale cache content if an upstream fetch for that specific key is already in flight. After a reload, requests that arrive during a refresh show X-Cache-Status: UPDATING or STALE instead of waiting.

Layer 3: Put an Origin Shield Between Edge PoPs and Origin

Request collapsing on an individual edge node only protects that single machine. If you use a global CDN like Fastly, Cloudflare, or CloudFront, you have dozens of PoPs worldwide. When an item expires everywhere at once, London, New York, Tokyo, and Frankfurt all miss their local caches simultaneously.

An Origin Shield is a designated caching tier placed close to your backend servers. All edge PoPs route their cache misses through the Shield before hitting your actual origin application. CDNs name the feature differently: CloudFront calls it Origin Shield, Fastly calls it shielding, and Cloudflare calls it Tiered Cache.

Here is the flow:

  1. Edge PoPs: User requests hit regional edges (Singapore, Frankfurt, New York). Local request collapsing merges simultaneous hits.
  2. Origin Shield: If a regional edge misses, it queries the Origin Shield. The Shield collapses misses coming in from all global PoPs into one request.
  3. Origin Server: Your backend only handles a single request to regenerate the data, sends it to the Shield, and the Shield passes it down to the edge tier.

If you build your own shield proxy with Nginx on a dedicated VPS, the config on that shield server looks like this:

# /etc/nginx/conf.d/origin-shield.conf
proxy_cache_path /var/cache/nginx/shield levels=1:2 keys_zone=shield_cache:100m max_size=10g inactive=24h use_temp_path=off;
upstream production_app {
    # Internal private IP of app origin
    server 10.0.1.50:8080;
    keepalive 64;
}
server {
    listen 8443 ssl http2;
    server_name shield.internal.example.com;
    ssl_certificate /etc/ssl/certs/shield.crt;
    ssl_certificate_key /etc/ssl/private/shield.key;
    location / {
        proxy_pass http://production_app;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache shield_cache;
        proxy_cache_valid 200 301 302 10m;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 10s;
        proxy_cache_use_stale updating error timeout;
        proxy_cache_background_update on;
    }
}

Lock down your backend origin firewall so it only accepts connections from the shield’s private IP. This stops requests from bypassing your shield. The guide to restrict origin traffic to CDN shield IPs with UFW and Nginx shows how.

Test It: Simulate a Cache Stampede with k6

Do not assume your proxy lock works until you test it under real concurrency while the cache entry expires. This k6 load testing script runs 150 virtual users against a single endpoint. Only run it against servers you own.

Save the script on your own computer or a separate test machine, not on the server under test:

// stampede-test.js
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
  scenarios: {
    traffic_spike: {
      executor: 'constant-vus',
      vus: 150,
      duration: '30s',
    },
  },
};
export default function () {
  const url = 'https://api.example.com/api/v1/posts';
  const res = http.get(url, {
    headers: {
      'Accept-Encoding': 'gzip',
    },
  });
  check(res, {
    'status is 200': (r) => r.status === 200,
    'cache header present': (r) => r.headers['X-Cache-Status'] !== undefined,
  });
  sleep(0.1);
}

Run it from that machine’s terminal:

k6 run stampede-test.js

The test only proves something if the cache entry expires while it runs, so temporarily shorten proxy_cache_valid to a few seconds and watch the origin’s access log:

  • Without request collapsing: every expiry shows up at the origin as a burst of simultaneous requests for the same URL, and k6 reports a latency spike each time.
  • With request collapsing + stale-while-revalidate: the origin sees a single request per expiry, and clients keep getting fast responses marked STALE or UPDATING in X-Cache-Status.

Set proxy_cache_valid back to its normal value when you are done.

Still Leaking Requests? Check Vary Headers and Cache Keys

If a handful of parallel requests still reach your backend on every expiry with proxy_cache_lock enabled, the locks are not broken.

The usual culprit is cache key fragmentation. Request collapsing only works if concurrent requests share the exact same internal cache key.

Three common mistakes split cache keys unexpectedly:

  1. Vary: User-Agent: If your origin sends this header, the cache splits entries for Chrome, Safari, Firefox, and mobile engines. A stampede across different browsers triggers a separate backend fetch for each browser type.
  2. Gzip vs. Brotli: A request with Accept-Encoding: gzip gets a different cache key than one with Accept-Encoding: br. Normalize encoding on your proxy.
  3. Query Parameter Ordering: /api/posts?sort=desc&page=1 and /api/posts?page=1&sort=desc return the same payload, but CDNs treat them as completely different cache keys.

Fix the first two by ignoring the origin’s Vary header and letting the proxy, not the origin, handle compression. Without the Accept-Encoding line below, a gzip-encoded body cached under one key would be served to clients that never asked for gzip. Query-string order has to be normalized before the request reaches the cache, for example with your CDN’s query string sorting option; marketing parameters can be removed at the edge, as in this guide to strip marketing query strings at the CDN edge.

Add these lines to the caching location block:

# Ask the origin for uncompressed responses and compress at the proxy instead
proxy_set_header Accept-Encoding "";
gzip on;
gzip_types application/json text/css application/javascript;
# Ignore origin Vary headers that fragment the cache
proxy_ignore_headers Vary;
proxy_hide_header Vary;
# Send one controlled Vary header to downstream clients
add_header Vary "Accept-Encoding" always;

Two more reasons an endpoint never shows HIT: the response sets a cookie (Nginx does not cache responses that carry Set-Cookie unless told to), or it sends Cache-Control: private or no-store. For more on how proxies evaluate variants, see the MDN Web Docs guide on HTTP Caching.

Frequently Asked Questions

What is the difference between Request Collapsing and Request Coalescing?

They are two names for the same thing. CDNs and reverse proxies use both terms to describe combining multiple concurrent requests for the same URI into a single backend fetch.

Does request collapsing add latency for users?

Only for users who arrive while an expired item is actively being fetched. They wait for that single upstream request, usually well under a second, which is far better than letting hundreds of concurrent queries choke your database and cause timeouts.

Can I use stale-while-revalidate for personalized user dashboards?

No. Never use shared CDN cache directives on authenticated endpoints that return private user data. Keep Cache-Control: private, no-store on any route using session cookies or Bearer tokens.

How long should my stale-while-revalidate window be?

A common starting point is 3 to 5 times your max-age. If a response is fresh for 60 seconds (max-age=60), allow stale responses for 300 seconds (stale-while-revalidate=300). That leaves time to fetch fresh data in the background before anyone hits a cold cache miss.

Next Steps

Turn on request collapsing and stale serving first; they need only a few lines of Nginx config. Then enable your CDN’s shield or tiered cache and run the k6 test once more. For static files such as JavaScript and CSS, long-lived immutable caching removes most expiries altogether: see how to configure immutable Cache-Control and cache busting in Nginx.

all_in_one_marketing_tool