basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    nginx caching: proxy_cache, microcaching, stale responses, and spike protection

    Line-by-line proxy_cache config: disk storage and cache keys, thundering-herd protection with proxy_cache_lock, serving cached pages during backend outages (proxy_cache_use_stale), background refresh, 1–5 second microcaching, and cache bypass for logged-in users.

    Browser cache vs. server-side proxy_cache

    The two caching layers solve different problems and complement each other:

    Layer Where copies live What it saves Controlled by
    Browser cache On a single visitor’s device Re-downloading static assets for the same visitor (Static & SPA) Cache-Control, ETag headers
    Server cache (proxy_cache) On nginx’s own disk App and database load: a thousand different visitors share one rendered response proxy_cache_* directives in nginx

    Even a 1–5 second microcache absorbs a 10x traffic spike on a modest VPS: instead of 500 requests per second hitting Python or Node.js, the backend sees one request per second while nginx serves the other 499 from memory and disk.

    Line-by-line proxy_cache config

    Create the disk cache directory owned by the nginx worker user first:

    sudo mkdir -p /var/cache/nginx/app
    sudo chown -R nginx:nginx /var/cache/nginx/app
    /etc/nginx/conf.d/cached.example.org.conf
    proxy_cache_path /var/cache/nginx/app
                     levels=1:2
                     keys_zone=APP_CACHE:20m
                     inactive=60m
                     max_size=512m
                     use_temp_path=off;
    Key part

    Declared in the http context (outside server). levels=1:2 spreads files across two-level subdirectories so a single folder never slows down with millions of entries. keys_zone=APP_CACHE:20m allocates 20 MB of shared memory for metadata (~160,000 keys). inactive=60m evicts unused entries after an hour, max_size=512m caps disk usage, and use_temp_path=off writes files straight into the cache directory without copying across filesystems.

    default:inactive 10muse_temp_path on

    map $http_cookie $has_session {
        default 0;
        ~*sessionid= 1;
    }
    
    server {
        listen 80;
        server_name cached.example.org;

    Flag requests that must bypass the cache: any Authorization header or sessionid cookie. A map table in the http context is evaluated only when referenced.

        location / {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
    
            proxy_cache APP_CACHE;
            proxy_cache_key "$scheme$request_method$host$request_uri";
            proxy_cache_valid 200 302 10s;
            proxy_cache_valid 404 1m;
    Key part

    Enable the APP_CACHE zone, define the cache key, and set TTLs: cache 200/302 responses for 10s (microcache; raise to 5m–1h for rarely changing pages) and 404 responses for 1m so scanners probing missing URLs don’t hammer the backend.

            proxy_cache_lock on;
            proxy_cache_lock_timeout 5s;
            proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
            proxy_cache_background_update on;
    Key part

    Outage and spike protection: proxy_cache_lock on lets only one request per missing key reach the backend while the rest wait for the populated entry. proxy_cache_use_stale serves the last stored copy (STALE) if the backend is down, returns 502/503/504, or is currently refreshing. proxy_cache_background_update on refreshes expired entries in the background without blocking the client.

    default:proxy_cache_lock offproxy_cache_use_stale offproxy_cache_background_update off

            proxy_cache_bypass $http_authorization $has_session;
            proxy_no_cache     $http_authorization $has_session;
            add_header X-Cache-Status $upstream_cache_status always;
    
            proxy_pass http://127.0.0.1:3000;
        }
    }

    Authenticated requests bypass the cache (bypass skips reading from cache; no_cache skips writing the response to cache). X-Cache-Status exposes the cache decision for debugging.

    What X-Cache-Status values mean

    Value What happened
    MISS Entry wasn’t cached — nginx fetched it from the backend and stored it
    HIT Served straight from nginx’s cache without touching the backend
    BYPASS Skipped cache due to proxy_cache_bypass (authenticated user, POST)
    EXPIRED Entry TTL elapsed; nginx fetched a fresh response from the backend
    STALE Served an expired copy (backend unavailable or background refresh running)
    UPDATING Cache refresh is running in the background; client got the stale copy with no wait

    How to check

    1. Validate and reload the config:
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify MISS turning into HIT, and BYPASS with an Authorization header:
      curl -sI -H "Host: cached.example.org" http://127.0.0.1/ | grep -iE '^(HTTP/|x-cache-status)'
      # HTTP/1.1 200 OK
      # X-Cache-Status: MISS
      
      curl -sI -H "Host: cached.example.org" http://127.0.0.1/ | grep -iE '^(HTTP/|x-cache-status)'
      # HTTP/1.1 200 OK
      # X-Cache-Status: HIT
      
      curl -sI -H "Host: cached.example.org" -H "Authorization: Bearer tok" http://127.0.0.1/ \
        | grep -iE '^(HTTP/|x-cache-status)'
      # HTTP/1.1 200 OK
      # X-Cache-Status: BYPASS
    3. Test backend outage survival: wait for proxy_cache_valid to expire, stop the test app, and send a request — nginx should still return 200 OK with X-Cache-Status: STALE.

    If it doesn’t work

    proxy_cache is enabled, yet X-Cache-Status always shows MISS or stays empty

    Cause
    The backend sends Cache-Control: private, no-cache, no-store, or Set-Cookie — nginx refuses to cache those responses by default.
    Fix
    Inspect the raw backend headers with curl -sI http://127.0.0.1:3000/. If the page is public, fix Cache-Control in the app (or use proxy_ignore_headers Cache-Control; selectively on strictly anonymous routes).

    A logged-in user’s private page landed in the cache and was served to another visitor

    Cause
    Cache bypass for Authorization and session cookies (proxy_cache_bypass and proxy_no_cache) was missing, or proxy_ignore_headers Set-Cookie; was applied to an authenticated route.
    Fix
    Never set proxy_ignore_headers Set-Cookie; on dynamic routes with logins, and always bypass the cache on the Authorization header and your session cookie name.

    nginx fails on startup with mkdir() "/var/cache/nginx/app" failed (13: Permission denied)

    Cause
    The cache directory is owned by root, so the nginx worker user cannot write cache files into it.
    Fix
    Create the directory with the worker user as owner: sudo mkdir -p /var/cache/nginx/app && sudo chown -R nginx:nginx /var/cache/nginx/app.

    Cache expired on a hot page and 500 concurrent requests hit the backend at once, overloading the database

    Cause
    proxy_cache_lock on; is missing, so all 500 requests saw MISS/EXPIRED and went to regenerate the same page simultaneously.
    Fix
    Enable proxy_cache_lock on; (lets only one request per key hit the backend) and pair proxy_cache_background_update on; with proxy_cache_use_stale updating; so other clients get the stale copy while nginx refreshes in the background.

    After publishing updated content, the old version stays live because of a long proxy_cache_valid

    Cause
    Open-source nginx lacks proxy_cache_purge (it exists only in NGINX Plus or third-party modules).
    Fix
    Use a short microcache (1s–10s) for frequently updated pages, clear the cache directory (sudo rm -rf /var/cache/nginx/app/*), or add a bypass query parameter for editors.