brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: proxy_cache_use_stale keeps nginx serving pages while the backend is down

Nginx
~/tips/tip-nginx-proxy-cache-use-stale

proxy_cache app;

Serves the last cached copy of a page when the backend errors out or is busy refreshing.

A small proxy cache in front of an app has a bonus beyond speed: when the app falls over, nginx can keep handing out the last good copy instead of an error.

proxy_cache_path /var/cache/nginx/app keys_zone=app:10m max_size=1g inactive=1h;

location / {
    proxy_pass http://127.0.0.1:8081;
    proxy_cache app;
    proxy_cache_valid 200 1m;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    proxy_cache_background_update on;
    add_header X-Cache $upstream_cache_status;
}

Pages stay fresh for a minute. After that, if the backend errors or times out, nginx serves the expired copy instead. With updating and proxy_cache_background_update, a visitor also gets the stale copy while nginx fetches a new one in the background, so nobody waits for the refresh. The X-Cache header shows MISS, HIT, STALE or UPDATING; a second request for the same page should show HIT.

proxy_cache_path goes in the http block, and inactive=1h decides how long an unused copy survives, so that is also how long the fallback lasts.

Only cache what is the same for everyone. nginx does not cache responses that set cookies by default, but a page that shows a logged-in name without a cookie in the response could be served to the next visitor. I’d keep this for public pages and leave admin and account paths out of it.

Further reading: proxy_cache_use_stale, proxy_cache_background_update

Going deeper: Guide: fix a 502 Bad Gateway in Nginx Proxy Manager, with a checklist that finds the cause

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link