TExcelTAD

Proxy Caching

A response that is the same for everyone (a product page, a public API listing, an image resized by the app) doesn't need to be generated again for every visitor. Nginx can cache backend responses on disk and serve them itself: the backend does the work once per cache period, and a traffic spike hits the cache instead of the database. Done carelessly, the same feature serves one user's private page to everybody, so this lesson covers both halves: making caching work and keeping it safe.

The pieces

nginx
http {
    # where, how the keys are indexed in shared memory, how big, how long unused entries live
    proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=app:10m max_size=1g inactive=60m use_temp_path=off;

    server {
        location / {
            proxy_pass http://app;
            proxy_cache app;                                 # use the zone
            proxy_cache_key $scheme$host$request_uri;        # the default is $scheme$proxy_host$request_uri
            proxy_cache_valid 200 301 10m;                   # only if the backend gives no Cache-Control/Expires
            proxy_cache_valid 404 1m;
            add_header X-Cache-Status $upstream_cache_status always;
        }
    }
}

keys_zone=app:10m holds the keys and metadata in shared memory (one megabyte stores about 8,000 keys); the bodies live in files under the path. $upstream_cache_status tells you what happened to each request:

Status Meaning
MISS not in the cache; fetched from the backend (and stored if cacheable)
HIT served from the cache
EXPIRED in the cache but stale; fetched again
STALE stale, but served anyway because of proxy_cache_use_stale
UPDATING stale, served while another request refreshes it
BYPASS proxy_cache_bypass was true: fetched from the backend (the answer may still be stored)
(empty) the cache wasn't used for this request

What Nginx caches and what it doesn't

Nginx respects the backend: it does not cache responses with Set-Cookie, with Cache-Control: private, no-cache or no-store, or with Vary: *, and a Cache-Control: max-age=N (or s-maxage) from the backend overrides proxy_cache_valid. By default only GET and HEAD are cached. The session's backend counts how often it really works:

bash · try it yourself
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
calls = {}
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        calls[self.path] = calls.get(self.path, 0) + 1
        self.send_response(200)
        if self.path.startswith("/account"):
            self.send_header("Cache-Control", "private")
        elif self.path.startswith("/news"):
            self.send_header("Cache-Control", "max-age=1")
        self.end_headers()
        self.wfile.write(f"{self.path} generated (call #{calls[self.path]})\n".encode())
    def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  proxy_cache_path cache levels=1:2 keys_zone=app:1m max_size=50m inactive=10m use_temp_path=off;
  server {
    listen 127.0.0.1:8080;
    location / {
      proxy_pass http://127.0.0.1:9000;
      proxy_cache app;
      proxy_cache_valid 200 10m;
      proxy_cache_bypass $http_x_refresh;       # a non-empty header value skips the cache lookup
      add_header X-Cache-Status $upstream_cache_status always;
    }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
get() { printf '%-26s %-8s %s\n' "$1 ${2:+(refresh)}" "$(curl -s -D - -o body.txt ${2:+-H "X-Refresh: 1"} 127.0.0.1:8080$1 | grep -i x-cache | cut -d' ' -f2 | tr -d '\r')" "$(cat body.txt)"; }
get /products/7; get /products/7; get /products/7
get /products/7 yes; get /products/7
get /account/me; get /account/me
get /news; get /news; sleep 3; get /news; get /news
find cache -type f | wc -l
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1
/products/7                MISS     /products/7 generated (call #1)
/products/7                HIT      /products/7 generated (call #1)
/products/7                HIT      /products/7 generated (call #1)
/products/7 (refresh)      BYPASS   /products/7 generated (call #2)
/products/7                HIT      /products/7 generated (call #2)
/account/me                MISS     /account/me generated (call #1)
/account/me                MISS     /account/me generated (call #2)
/news                      MISS     /news generated (call #1)
/news                      HIT      /news generated (call #1)
/news                      EXPIRED  /news generated (call #2)
/news                      HIT      /news generated (call #2)
2

Read the backend's call counter in each line:

  • /products/7 was generated once and then served from the cache. The X-Refresh request bypassed the cache (call #2) and the fresh answer replaced the cached one, so the next request is a HIT showing call #2. That is a convenient way to warm or refresh a single URL.
  • /account/me said Cache-Control: private, so it was never stored: two requests, two calls.
  • /news said max-age=1, which overrode the 10 minutes of proxy_cache_valid: three seconds later it was EXPIRED and generated again. (Nginx counts cache lifetimes in whole seconds, so very short lifetimes are approximate.)
  • The cache folder holds two files, one per stored key: /products/7 and /news.

Keeping private data out of the cache

The dangerous case is the reverse: a page that depends on the user but doesn't say so. If the backend returns a personalised page with no Cache-Control and no Set-Cookie on that response (the session cookie was set earlier), Nginx caches it under the URL, and the next visitor gets the first visitor's page. Defences, in order of importance:

  1. The app marks personalised responses Cache-Control: private (or no-store). This is the app's job; make it a framework default.
  2. Don't cache requests that carry a session: proxy_cache_bypass $cookie_session; proxy_no_cache $cookie_session;. (proxy_cache_bypass skips the lookup; proxy_no_cache prevents storing. You usually want both.)
  3. Cache only what you chose: enable proxy_cache per location (/products/, /static/), not for the whole site.
  4. Never add proxy_ignore_headers Cache-Control Set-Cookie; to "make caching work" without understanding every route it covers.

Surviving backend failures with stale content

proxy_cache_use_stale lets Nginx serve an expired copy when the backend is failing, and proxy_cache_background_update (since 1.11.10) refreshes stale entries in the background while clients get the old one immediately. proxy_cache_lock makes concurrent misses for the same key wait for one backend request instead of all going through (the "thundering herd"):

bash · try it yourself
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.send_header("Cache-Control", "max-age=1"); self.end_headers()
        self.wfile.write(b"price list v1\n")
    def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  proxy_cache_path cache keys_zone=app:1m;
  server {
    listen 127.0.0.1:8080;
    location / {
      proxy_pass http://127.0.0.1:9000;
      proxy_cache app;
      proxy_cache_use_stale error timeout http_500 http_502 http_503 updating;
      proxy_cache_background_update on;
      proxy_cache_lock on;
      add_header X-Cache-Status $upstream_cache_status always;
    }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
show() { curl -s -D - -o body.txt 127.0.0.1:8080/prices > hdr.txt; echo "$(grep -i x-cache hdr.txt | tr -d '\r') | status $(head -1 hdr.txt | cut -d' ' -f2) | $(cat body.txt)"; }
show; show
kill %1; sleep 3
echo "--- backend stopped, entry expired:"
show; show
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
X-Cache-Status: MISS | status 200 | price list v1
X-Cache-Status: HIT | status 200 | price list v1
--- backend stopped, entry expired:
X-Cache-Status: STALE | status 200 | price list v1
X-Cache-Status: STALE | status 200 | price list v1

With the backend gone and the entry expired, clients still got the price list with status 200, marked STALE (or UPDATING while a background refresh is attempted). Whether serving old content is acceptable is a product decision: for a news page, yes; for an account balance, no.

Purging

Open-source Nginx has no purge command (proxy_cache_purge is an NGINX Plus directive or a third-party module). The options are: let entries expire (keep max-age short and rely on proxy_cache_background_update), refresh single URLs with a bypass header as above (restricted to internal clients with geo), or delete the cache directory's files and reload. For content that changes on deploy, put a version or hash in the URL (app.3f9c2.js) and cache it for a year.

Test yourself

The backend sends Cache-Control: max-age=30 and the location has proxy_cache_valid 200 10m;. How long is the response cached?

  1. 10 minutes
  2. 30 seconds: the backend's Cache-Control takes precedence
  3. 40 minutes
  4. Not at all

What is the difference between proxy_cache_bypass and proxy_no_cache?

  1. None
  2. bypass skips looking up the cache for the request; no_cache prevents storing the response
  3. bypass deletes the entry
  4. no_cache disables the cache zone

What does proxy_cache_use_stale error timeout updating; achieve?

  1. Caches errors
  2. Serves an expired cached copy when the backend fails or while it is being refreshed
  3. Deletes stale entries
  4. Disables the cache on errors