Sub topic 13
Caching upstream responses
This chapter assumes you can already proxy requests to an upstream group and reload Nginx safely. Here you will add a response cache in front of the backends, so repeated requests for the same content are answered from disk without contacting an application server.
What the proxy cache does
When proxy_cache is enabled for a location, Nginx computes a key for each request and looks it up in a cache zone. On a hit, it sends the stored response directly. On a miss, it forwards the request upstream, returns the response to the client, and stores it if the response is cacheable.
The cache has two parts:
- Response bodies and headers are stored as files in a directory on disk.
- Keys and metadata are held in a shared memory zone, so Nginx can check for a hit without touching the disk.
Defining the cache zone
proxy_cache_path is valid only in the http context. Files in /etc/nginx/conf.d/ are already included inside http, so a top-level line there is fine.
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app_cache:10m
max_size=1g inactive=60m use_temp_path=off;| Parameter | Meaning |
|---|---|
| `levels=1:2` | Two-level subdirectory layout, so no single directory holds millions of files. |
| `keys_zone=app_cache:10m` | Zone name and shared memory size. About 8,000 keys fit in 1 MB. |
| `max_size=1g` | Upper limit for cached data. The cache manager process removes least recently used entries beyond it. |
| `inactive=60m` | Entries not requested for 60 minutes are removed, even if still fresh. |
| `use_temp_path=off` | Writes files directly into the cache directory instead of copying from a temporary location. |
The directory must exist and be writable by the worker user. That user is www-data on Debian and Ubuntu, and nginx on RHEL-based systems.
sudo mkdir -p /var/cache/nginx/app
sudo chown www-data:www-data /var/cache/nginx/appEnabling the cache in a location
The inactive timer and the freshness time are separate settings. inactive controls how long an unused entry is kept. proxy_cache_valid controls how long a response is considered fresh.
server {
listen 80;
server_name example.com;
location / {
proxy_cache app_cache;
proxy_cache_valid 200 301 10m;
proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://app_backend;
}
}Test and reload, then request the same URL twice:
sudo nginx -t && sudo systemctl reload nginx
curl -sI http://example.com/ | grep -i x-cache-status
curl -sI http://example.com/ | grep -i x-cache-statusThe first call should print MISS and the second HIT. If both print MISS, see the troubleshooting section below.
Values of `$upstream_cache_status`
| Value | Meaning |
|---|---|
| `MISS` | Not in the cache. The request went upstream. |
| `HIT` | Served from a fresh cached entry. |
| `EXPIRED` | The entry was stale, so Nginx fetched a new copy. |
| `STALE` | A stale entry was served because the upstream failed (see `proxy_cache_use_stale`). |
| `UPDATING` | A stale entry was served while another request refreshed it. |
| `REVALIDATED` | A conditional request confirmed the stale entry was still valid. |
| `BYPASS` | The cache was skipped because of `proxy_cache_bypass`. |
What Nginx will and will not cache
By default only GET and HEAD responses are cached. If you give proxy_cache_valid only a time, such as proxy_cache_valid 10m;, it applies to status codes 200, 301 and 302. Use any to include every status code.
Freshness comes from the first of these that applies:
- The
X-Accel-Expiresresponse header. Cache-Controlwithmax-ageors-maxage, or anExpiresheader.- The
proxy_cache_validdirective.
Nginx refuses to cache a response when any of these is true:
- The response has a
Set-Cookieheader. Cache-Controlcontainsprivate,no-cacheorno-store.X-Accel-Expiresis0, orExpiresis in the past.Vary: *is present.
This is usually the correct behavior. A response that sets a session cookie is probably specific to one user. You can override it with proxy_ignore_headers, but only do that when you know the content is identical for everyone.
The cache key
The default key is $scheme$proxy_host$request_uri. Two requests share a cache entry only if their keys are equal. Define the key explicitly when the default is not precise enough:
proxy_cache_key "$scheme$request_method$host$request_uri";If several server_name values point to the same upstream but serve different content per hostname, include $host. If the response depends on a request header, such as Accept-Language or Accept-Encoding, either add it to the key or make sure the upstream sends a correct Vary header.
Bypassing the cache for some requests
Two directives control different halves of the behavior:
proxy_cache_bypassskips the lookup, so the request always goes upstream.proxy_no_cacheprevents the response from being stored.
Both accept variables. If any value is non-empty and not 0, the condition applies. For logged-in users, you normally want both:
location / {
proxy_cache app_cache;
proxy_cache_valid 200 10m;
proxy_cache_bypass $cookie_session $http_authorization;
proxy_no_cache $cookie_session $http_authorization;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://app_backend;
}If you set only proxy_cache_bypass, a logged-in user's response is still stored and may be served to anonymous users later.
Serving stale content and protecting the backend
A cache can also hide backend failures and limit load spikes. The following settings go in the same location block:
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
proxy_cache_min_uses 2;proxy_cache_use_staleserves an expired entry when the upstream errors, times out, or is already being refreshed. Users see old content instead of a 502.proxy_cache_background_update onreturns the stale entry immediately and refreshes it in a separate subrequest.proxy_cache_lock onlets only one request per key populate a missing entry. Others wait, up toproxy_cache_lock_timeout(5 seconds by default). Without it, a popular expired URL causes a burst of identical upstream requests.proxy_cache_min_uses 2stores a response only after the key has been requested twice. This keeps one-off URLs from filling the disk.
Inspecting and clearing the cache
Open-source Nginx has no purge directive. That feature is in Nginx Plus. These options work without it:
- Delete files under the cache directory. Removing everything is safe while Nginx runs:
sudo find /var/cache/nginx/app -type f -delete. - Force a refresh of one URL by sending a header you have wired to
proxy_cache_bypass, for exampleproxy_cache_bypass $http_x_refresh;, thencurl -H "X-Refresh: 1" http://example.com/page. The bypassed request still stores its response unlessproxy_no_cachealso matches. - Use a short
proxy_cache_validfor content that changes often.
Each cache file starts with a KEY: line. This command shows which keys exist:
sudo grep -a -r "^KEY:" /var/cache/nginx/app | headTroubleshooting a cache that never hits
Work through these checks in order:
- Run
curl -Itwice and readX-Cache-Status. If the header is missing, theadd_headerline is not in effect in that location. - Look at the upstream response headers. A
Set-CookieorCache-Control: no-storeexplains persistentMISS. - Check that the key is stable. A cache-busting query string such as
?_=1699999999makes every request unique. - Confirm that the request method is
GETorHEAD. - Check the error log for permission errors on the cache directory (
sudo tail /var/log/nginx/error.log). - Check
proxy_cache_min_uses. A value of 2 means the first two requests are alwaysMISS.
You can log the status next to the upstream fields from the earlier logging chapter by adding cache=$upstream_cache_status to the log_format. This lets you compute your hit ratio from the access log.
Exercise
Users report that after Alice logged in, anonymous visitors briefly saw Alice's name on the home page. The location has proxy_cache app_cache; and proxy_cache_valid 200 10m;, and the app does not send Set-Cookie on that page when the session cookie is already present. Which directives would you add, and why is proxy_cache_bypass alone not enough?
Show answer
Add proxy_cache_bypass $cookie_session; so logged-in requests skip the cache lookup, and proxy_no_cache $cookie_session; so their responses are never stored. With only proxy_cache_bypass, Alice's request goes upstream but the response is still written to the cache under the shared key, and later anonymous requests receive it as a HIT. The alternative is to put the session or user identity into proxy_cache_key, but that gives each user a separate entry and a low hit rate.
Exercise
Your backend is down for two minutes. You want visitors to keep getting pages that were cached up to an hour ago, and you want a burst of traffic on an expired URL to cause only one upstream request. Which directives do you use?
Show answer
Use proxy_cache_use_stale error timeout http_502 http_503 http_504 updating; to serve expired entries when the upstream fails, and proxy_cache_lock on; so only one request per key refreshes the entry while others wait. Adding proxy_cache_background_update on; returns the stale copy immediately during the refresh. Also make sure inactive in proxy_cache_path is long enough, since entries unused for that time are deleted and cannot be served stale.