Sub topic 11
Caching responses at the proxy
This chapter assumes you know HTTP methods and headers, can read basic nginx configuration, and know what a reverse proxy does. It builds on the earlier chapters on reverse proxies and HTTP proxying mechanics.
Why cache at the proxy
A proxy sees every request and response that passes through it. If the same response is requested again, the proxy can answer from a stored copy instead of contacting the backend. This is a shared cache: one stored copy serves many users. A browser cache, by contrast, is private to one user.
Caching at the proxy gives you three things:
- Lower latency, because a local disk or memory read replaces a network round trip and backend work.
- Less backend load, because popular objects are generated once and reused.
- Some resilience, because the proxy can serve old copies while the backend is down.
Both proxy types can cache. A reverse proxy caches for the servers it fronts, such as static assets and public API responses. A forward proxy such as Squid caches for its clients, so one employee's download of a package benefits the next. This chapter uses a reverse proxy (nginx) for the examples. The ideas carry over to forward proxies.
The life of a cached request
On each request the proxy computes a cache key, looks it up, and checks whether the stored entry is still fresh. A fresh entry is a hit. A missing entry is a miss, and the proxy fetches from the backend and stores the result if it is allowed to.
Configuring a cache in nginx
Two pieces are needed: a cache storage area defined once, and a proxy_cache directive in each location that should use it.
# In the http {} context
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m max_size=1g inactive=60m;
server {
listen 80;
server_name example.com;
location /static/ {
proxy_pass http://app_servers;
proxy_cache app_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_use_stale error timeout updating;
}
}This example assumes the app_servers upstream from the load balancing chapter is defined. What each directive does:
| Directive | Effect |
|---|---|
| `proxy_cache_path ... levels=1:2` | Stores files in a two-level directory tree so no single directory grows huge. |
| `keys_zone=app_cache:10m` | Names the cache and reserves 10 MB of shared memory for keys and metadata. |
| `max_size=1g` | When the disk cache exceeds 1 GB, nginx removes the least recently used entries. |
| `inactive=60m` | Removes entries not requested for 60 minutes, even if they are still fresh. |
| `proxy_cache app_cache` | Turns caching on for this location, using that zone. |
| `proxy_cache_valid 200 302 10m` | Treats 200 and 302 responses as fresh for 10 minutes. |
| `proxy_cache_use_stale ...` | Serves an expired copy when the backend fails or an update is in progress. |
Note that inactive and freshness are separate. Freshness decides whether a stored copy may be served without asking the backend. inactive only controls when unused files are deleted.
The cache key
The default key in nginx is $scheme$proxy_host$request_uri. Two requests with the same scheme, upstream host and URI (including query string) share one entry. You can change it:
location /api/public/ {
proxy_pass http://app_servers;
proxy_cache app_cache;
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_valid 200 1m;
}If the key is too narrow, you get cache poisoning by collision: two different responses share one key, and users see the wrong one. If the key is too broad, such as including a session cookie, every user gets a separate entry and the hit rate drops to nearly zero. Choose the smallest set of request properties that fully determines the response.
What gets cached, and for how long
Freshness comes from several sources. In nginx, the order is:
X-Accel-Expiresfrom the backend, if present.Cache-Control(max-age,s-maxage) orExpiresfrom the backend.proxy_cache_valid, only when the backend sends none of the above.
So proxy_cache_valid 200 302 10m is a fallback, not an override. If the backend sends Cache-Control: max-age=30, the entry lives 30 seconds. To ignore backend headers, you must say so with proxy_ignore_headers, and doing so is a deliberate risk.
s-maxage applies only to shared caches such as your proxy, which lets the backend give browsers and proxies different lifetimes.
nginx also refuses to cache, by default:
- Any method other than GET and HEAD.
- Responses with
Cache-Control: private,no-cacheorno-store. - Responses with a
Set-Cookieheader. - Responses with
Vary: *. - Responses with no explicit lifetime and no
proxy_cache_validrule.
These defaults protect you from leaking personal content. Override them only when you understand the content.
Observing the cache
Expose the outcome in a response header. Without it, debugging is guesswork.
location /static/ {
proxy_pass http://app_servers;
proxy_cache app_cache;
proxy_cache_valid 200 302 10m;
add_header X-Cache-Status $upstream_cache_status always;
}Test it with curl:
curl -sI http://example.com/static/app.css | grep -i x-cache-status
curl -sI http://example.com/static/app.css | grep -i x-cache-statusThe first call usually prints MISS and the second prints HIT. Other values include EXPIRED (the entry was stale and refetched), STALE (an old copy was served because of proxy_cache_use_stale), UPDATING, REVALIDATED and BYPASS.
Serving stale content on purpose
proxy_cache_use_stale error timeout updating covers two situations:
- Backend trouble. On a connection error or timeout, the proxy returns the old copy instead of a 502 or 504. Users see slightly old data rather than an error page.
- Update in progress. While one request refreshes an expired entry, others get the old copy (
updating).
You can extend this with http_500 http_502 http_503 http_504 to cover backend error responses too. Adding proxy_cache_background_update on lets nginx refresh the entry in a subrequest while the client gets the stale copy immediately.
Cache stampedes
When a popular entry expires or is missing, many requests can arrive before the first one finishes refilling it. Each one misses and goes to the backend. This burst is a cache stampede (or thundering herd), and it can overload the very backend the cache protects.
proxy_cache_lock fixes this:
location /static/ {
proxy_pass http://app_servers;
proxy_cache app_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
proxy_cache_use_stale error timeout updating;
}With the lock on, only one request per key goes to the backend. The others wait up to five seconds for the entry to appear. If the timeout passes, waiting requests are sent to the backend anyway, and their results are not cached. Combining the lock with updating gives the best behavior: one refresher, everyone else served.
Bypassing and invalidation
Sometimes a request must skip the cache, for example when a logged-in user's request hits a location that is otherwise public.
map $http_cookie $has_session {
default 0;
~*session= 1;
}
server {
listen 80;
server_name example.com;
location /catalog/ {
proxy_pass http://app_servers;
proxy_cache app_cache;
proxy_cache_valid 200 5m;
proxy_cache_bypass $has_session;
proxy_no_cache $has_session;
}
}The two directives do different things:
proxy_cache_bypassmeans "do not answer this request from the cache".proxy_no_cachemeans "do not store this response".
You usually want both, or a bypassed personal response is stored and later served to others.
Invalidation is harder. Open-source nginx has no purge command. The common options are:
- Short lifetimes, so mistakes fix themselves.
- Versioned URLs such as
/static/app.3f9a1c.css, so a change creates a new key and the old entry is never requested again. This is the most reliable approach for static assets. - Deleting files from the cache directory, or using a third-party purge module or NGINX Plus.
Pitfalls
- Leaking personal data. Caching a response that depends on a cookie or
Authorizationheader serves one user's data to another. Keep personalized paths out of cached locations, or key on or bypass by the identifying value. - Ignoring
Vary. If the backend varies output byAccept-EncodingorAccept-Language, the cache must account for it. Respect theVaryheader, and do not setproxy_ignore_headers Varywithout a reason. - Caching errors.
proxy_cache_valid any 10malso stores 404 and 500 responses. A brief backend failure then lingers for ten minutes. Cache errors only briefly, such asproxy_cache_valid 404 10s. - Query-string explosion. Tracking parameters like
?utm_source=xcreate separate entries for identical content. Strip them from the key if they do not change the response. - Disk and memory limits. A key zone of 10 MB holds roughly 80,000 keys. If the zone fills, nginx evicts older entries early even when disk space remains.
- Per-instance caches. Each proxy node has its own cache. With several nodes behind a load balancer, each fills separately, so hit rates drop and entries can differ between nodes. Consistent hashing on the URL can send each key to the same node.
Exercise
A backend sends Cache-Control: max-age=30 on /static/logo.png. Your nginx location has proxy_cache_valid 200 10m. How long does the proxy treat the entry as fresh, and why?
Show answer
30 seconds. Backend headers (X-Accel-Expires, Cache-Control, Expires) take priority. proxy_cache_valid applies only when the backend gives no lifetime, unless proxy_ignore_headers is used.
Exercise
After a backend outage, users keep seeing a "not found" page for a product page that now exists, for ten minutes. The config has proxy_cache_valid any 10m. What is the cause, and what is a safer rule?
Show answer
any caches every status code, including 404 and 5xx responses, for ten minutes. Cache only the codes you want for a long time, for example proxy_cache_valid 200 10m; and proxy_cache_valid 404 10s;, and leave 5xx uncached.
Exercise
Under load, a popular entry expires and the backend receives hundreds of identical requests at once. Name the problem and the two directives that reduce it.
Show answer
This is a cache stampede. Use proxy_cache_lock on so only one request per key refreshes the entry, and proxy_cache_use_stale updating so other requests get the old copy meanwhile.