Learn Labs
Caching & Limits

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.

proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:10mmax_size=1g inactive=10m use_temp_path=off;keys_zone 10 MB of keys in shared memory, about 80,000 entriesmax_size bodies on disk; least recently used are evicted beyond thisinactive entries not requested for 10 min are removed, fresh or notlocation /api/cached/ {proxy_pass http://app;proxy_cache api_cache;proxy_cache_valid 200 10s;only if the backend sends no caching headersproxy_cache_lock on;one request fills a missing entry; others waitproxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;proxy_cache_background_update on;refresh expired entries behind a stale responseadd_header X-Cache-Status $upstream_cache_status always;}

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 ms

210 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 background
expiresoutagecacheMISSHIT, ~1 msstale, 1 refreshHITSTALE (outage)backend210 ms1 refreshall 3 downtime →

One 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.00s

With 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.

What not to cache

  • Per-user responses. The cache key here is $scheme$proxy_host$request_uri by default: two users requesting /api/cached/me would get each other's data. Nginx doesn't cache responses with Set-Cookie, or with Cache-Control: private or no-store, unless told to ignore them. Keep it that way, and have the backend mark personal responses private.
  • Responses to authenticated requests, unless the key includes the user and you're sure.
  • Errors, beyond a few seconds: proxy_cache_valid 404 10s can 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.

Lab

  1. Run caching.py. Then remove proxy_cache_lock and proxy_cache_background_update, reload, and run the stampede part again. How many backend hits now?
  2. Add a cached location for /api/private/me and check whether Nginx caches it. Why not?
  3. Watch docker exec nginx ls -R /var/cache/nginx/api while requesting different query strings.

On this page