Sub topic 11
Caching responses at the proxy
This chapter assumes you know HTTP methods, status codes and headers, and that you have read the earlier chapters on reverse proxies and how a proxy relays HTTP. It shows how a reverse proxy can answer repeat requests from its own storage instead of asking the backend each time.
Why cache at the proxy
A cache is a store of earlier responses that can be reused. When the proxy holds a fresh copy of a response, it returns that copy directly. The backend does no work, and the client gets the answer sooner.
Caching at the proxy helps in three ways:
- It lowers load on backends, because repeated requests for the same resource never reach them.
- It lowers latency, because the response comes from the proxy's disk or memory.
- It adds resilience, because the proxy can serve an older copy while a backend is failing.
A cache in the reverse proxy is a shared cache. One stored response serves every client that asks for that resource. That is why caching rules need care: a response meant for one user must never be served to another.
The cache flow
On each request, the proxy builds a cache key, usually from the URL and host. It then looks the key up.
A lookup that finds a usable copy is a hit. A lookup that does not is a miss, and the proxy fetches from the backend.
Configuring a cache in nginx
The next configuration caches successful responses under /static/ for ten minutes. It also allows stale copies when the backend fails.
# 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;
}
}The directives work like this:
| Directive | Effect |
|---|---|
| `proxy_cache_path` | Sets the disk directory, a shared memory zone for keys (`keys_zone=app_cache:10m`), a size limit (`max_size=1g`), and how long unused entries are kept (`inactive=60m`). |
| `proxy_cache` | Turns on the named cache for this location. |
| `proxy_cache_valid` | Sets how long 200 and 302 responses count as fresh (10 minutes). |
| `proxy_cache_use_stale` | Allows an expired copy when the backend errors or times out, or while another request is refreshing the entry (`updating`). |
What controls freshness
The proxy decides how long to keep a copy from several sources. Headers sent by the backend normally take priority over a default set on the proxy.
Cache-Control: max-age=600says the response is fresh for 600 seconds.Cache-Control: no-storeforbids storing the response.Cache-Control: privatemarks a response as meant for one user, so a shared cache must not store it.Expiresgives an absolute expiry time. It is the older mechanism.Varynames request headers that change the response, such asAccept-Encoding. The proxy keeps a separate copy for each distinct value.
After a copy expires, the proxy can revalidate it. It asks the backend whether the copy is still current, using validators such as ETag or Last-Modified. A 304 Not Modified reply lets the proxy keep its copy without downloading the body again.
Common errors
- Caching personalized responses. If a page shows a user's name or cart and is cached under a shared key, other users see it. Cache only content that is the same for everyone, and let
Cache-Control: privateon backend responses do its job. - Ignoring cookies and query strings. Two URLs that differ only in a tracking parameter get separate entries, which lowers the hit rate. Requests carrying session cookies may need to bypass the cache.
- Serving stale content too long. A long
proxy_cache_validmeans updates reach users late. Plan how to purge or version URLs, for exampleapp.3f9a1c.js, so a new file gets a new key. - Caching errors. Storing a 500 response for minutes spreads a short failure into a long one. Cache only the status codes you list.
- Too little cache space. If
max_sizeis small, the proxy evicts useful entries, and the hit rate drops.
Exercise
A page at /account shows the logged-in user's name. The backend sends no caching headers, and a teammate proposes caching all of location / for ten minutes. What goes wrong, and what would you change?
Show answer
Because the cache is shared and the key is based on the URL, the first user's /account page is stored and then served to other users, which leaks personal data. Limit caching to locations with identical content for everyone, such as /static/. Have the backend send Cache-Control: private or no-store on personalized pages, and bypass the cache for requests with session cookies.
Exercise
In the nginx example, what does proxy_cache_use_stale error timeout updating let the proxy do?
Show answer
It lets the proxy serve an expired cached copy when the backend returns an error or times out, and while another request is already refreshing that entry. Clients get a response instead of a failure, and the backend is shielded from a burst of refresh requests.