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_lock lets one request fill an empty cache while others wait

Cache
~/tips/tip-proxy-cache-lock-stampede

proxy_cache app;

Protect a slow backend when many visitors ask for an expired page at once.

When a popular page is not cached yet, every visitor who asks at that moment goes through to the backend. nginx can queue them behind the first one.

Add the lock where you already use proxy_cache:

location / {
    proxy_pass http://127.0.0.1:9000;
    proxy_cache app;
    proxy_cache_valid 200 1m;
    proxy_cache_lock on;
    proxy_cache_lock_timeout 5s;
    add_header X-Cache-Status $upstream_cache_status;
}

The app zone comes from a proxy_cache_path line in the http block. With the lock on, only one request at a time is allowed to fetch a new item for a given cache key. The others wait for it to land in the cache. Test with nginx -t before you reload.

The waiting has limits, and that matters. After proxy_cache_lock_timeout a waiting request goes to the backend itself, and its answer is not cached. proxy_cache_lock_age lets one more request try if the first is taking too long. Both default to five seconds.

It helps for new items. For pages that expired and are being refreshed, look at proxy_cache_use_stale with updating too. I would skip it on responses that are never cacheable, where waiting gains nothing.

Further reading: nginx: ngx_http_proxy_module

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

More Cache tips fincore /var/lib/example/data.db npm cache verify fc-cache -f -v ~/.local/share/fonts Cache-Control: no-cache Cache-Control: max-age=60, stale-while-revalidate=600 All Cache tips (24) All topics

Link