Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx cache inactive vs proxy_cache_valid

Tags:

nginx

Nginx cache config:

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g 
                 inactive=60m use_temp_path=off;

server {
    # ...
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 5m;
        proxy_pass http://my_upstream;
    }
}

inactive

inactive specifies how long an item can remain in the cache without being accessed. In this example, a file that has not been requested for 60 minutes is automatically deleted from the cache by the cache manager process, regardless of whether or not it has expired.

proxy_cache_valid

Sets caching time for different response codes.If only caching time is specified then only 200, 301, and 302 responses are cached.

Does proxy_cache_valid override inactive? 5m later does the cached file exist or not?

like image 478
zhuguowei Avatar asked Oct 01 '20 08:10

zhuguowei


1 Answers

From this blog two quotes:

Turns out proxy_cache_valid instructs Nginx that the resource could be cached for 1y IF the resource doesn’t become inactive first. When you request a resource that has longer expiration but has become inactive due lack of requests, it causes a cache miss.

Conclusion proxy_cache_path should have a higher inactive time than the Expiration time of the requests (proxy_cache_valid).

From official Nginx guide:

inactive specifies how long an item can remain in the cache without being accessed. In this example, a file that has not been requested for 60 minutes is automatically deleted from the cache by the cache manager process, regardless of whether or not it has expired. The default value is 10 minutes (10m). Inactive content differs from expired content. NGINX does not automatically delete content that has expired as defined by a cache control header (Cache-Control:max-age=120 for example). Expired (stale) content is deleted only when it has not been accessed for the time specified by inactive. When expired content is accessed, NGINX refreshes it from the origin server and resets the inactive timer.

So, the answers for your questions:

Does proxy_cache_valid override inactive? 5m later does the cached file exist or not?

No. They work in pair.

  1. proxy_cache_valid makes cache expired in 5 mins.

  2. If cache (does not matter expired or not) has not been accessed within 10 mins - Nginx removes it.

  3. If expired cache has been accessed within 10 mins - NGINX refreshes it from the origin server and resets the inactive timer.

Also this answer can help to understand proxy_cache_valid and inactive better.

like image 146
TitanFighter Avatar answered Oct 11 '22 20:10

TitanFighter