Caching
proxy_cache, keys, cache lock, stale-while-revalidate, and stale-if-error
The fastest request to a backend is the one that never happens. Nginx can store responses on disk and serve them itself, with the cache keys in shared memory so every worker sees the same cache.
The backend endpoint takes 200 ms and answers with
Cache-Control: public, max-age=10. Nginx follows that header: the backend
decides what's cacheable and for how long.
Hit and miss
docker compose -f compose_prod.yaml run --rm labs python caching.py
sequential:
MISS backend_hits=1 210.0 ms
HIT backend_hits=1 1.0 ms
HIT backend_hits=1 0.6 ms
HIT backend_hits=1 0.6 ms210 ms to under a millisecond, and the backend saw one request.
The stampede that didn't happen
When a popular entry expires, every client requesting it at that moment misses. Without protection, all of them go to the backend at once: a cache stampede, often exactly when the backend is busiest. 50 concurrent requests right after expiry:
50 concurrent requests just after expiry (proxy_cache_lock, background update):
cache statuses: {'UPDATING': 49, 'STALE': 1} backend_hits seen: [1]
a moment later: HIT backend_hits=1 (10.9 ms): refreshed in the backgroundOne request triggered a background refresh and got the stale copy
(STALE); the other 49 got the stale copy too (UPDATING), instantly. The
backend received one request. This is HTTP's
stale-while-revalidate: slightly old data, served fast, refreshed once.
Stale if error
All three app instances stopped:
all three app instances stopped:
200 STALE took 0.01s, data is 12s old
200 STALE took 0.00s, data is 12s old
...
uncached /api/whoami: 502 in 0.00sWith every backend down, the cached endpoint kept answering 200 from its last good copy, while uncached routes failed. For read-heavy pages (product listings, articles, configuration), stale data is usually far better than an error.
An earlier run, before the upstream used resolve, served the same stale
responses but slowly: about 6 s, then 3 to 4 s, for the first two, while Nginx tried
connecting to each dead instance (2 s connect timeout × 3) before falling
back to stale. Stale-if-error still pays for failed attempts until the
backends are marked down. Short connect timeouts matter for caching too.
What not to cache
- Per-user responses. The cache key here is
$scheme$proxy_host$request_uriby default: two users requesting/api/cached/mewould get each other's data. Nginx doesn't cache responses withSet-Cookie, or withCache-Control: privateorno-store, unless told to ignore them. Keep it that way, and have the backend mark personal responsesprivate. - Responses to authenticated requests, unless the key includes the user and you're sure.
- Errors, beyond a few seconds:
proxy_cache_valid 404 10scan shield a backend from scanners, but a cached 500 hides recovery.
The query string is part of the key: caching.py adds ?run=<random> so
each run starts with a cold cache. That also means ?utm_source=...
variants each get their own entry; normalize keys if that matters.
Purging a single entry needs NGINX Plus or a third-party module in open
source. Design for expiry instead: short max-age with
stale-while-revalidate for data that changes, and fingerprinted URLs for
data that doesn't.
Lab
- Run
caching.py. Then removeproxy_cache_lockandproxy_cache_background_update, reload, and run the stampede part again. How many backend hits now? - Add a cached location for
/api/private/meand check whether Nginx caches it. Why not? - Watch
docker exec nginx ls -R /var/cache/nginx/apiwhile requesting different query strings.