Dump the code

Cache purging strategies

Created 10 months ago
Posted By admin
3min read
Cache purging is the process of removing or invalidating cached content to ensure that clients receive the most up-to-date information. In Nginx, cache purging strategies involve techniques to clear specific items, groups of items, or the entire cache.

Purging specific URLs:

You can use the proxy_cache_purge module to purge specific URLs from the cache. This requires an additional module, and it is not included in the default Nginx installation. You can use third-party modules like ngx_cache_purge for this purpose.

location ~ /purge(/.*) {
    allow 127.0.0.1;
    deny all;
    proxy_cache_purge my_cache $1$is_args$args;
}
In this example, requests to URLs like /purge/some-url from the localhost (127.0.0.1) are allowed to purge the corresponding items from the cache.

Cache invalidation with cache manager:

Some third-party cache managers or content management systems provide mechanisms to trigger cache invalidation. These systems may have APIs or interfaces that allow you to explicitly purge or invalidate specific content.

Automated cache expiry:

Leverage Nginx's proxy_cache_valid directive to set a relatively short cache expiration time. This ensures that content is automatically considered stale after a certain period, and subsequent requests will fetch fresh content from the backend.

proxy_cache_valid 200 302 5s;
In this example, cached content with a response code of 200 or 302 will expire after 5 seconds.

Manual cache deletion:

If you have access to the cache directory, you can manually delete cached files. This is a straightforward but manual process.

# Assuming the cache directory is /path/to/cache
rm -rf /path/to/cache/*

Cache warm-up scripts:

To ensure that cache is populated with frequently requested content, you can use cache warm-up scripts. These scripts make requests to important URLs, populating the cache in advance.

# Use a tool like curl or wget to make requests to critical URLs
curl http://example.com/critical-page

Soft purging with stale:

Nginx provides the proxy_cache_use_stale directive, allowing clients to receive stale cached content while a new version is being fetched. This provides a seamless experience for users even during cache purging.

location / {
    proxy_pass http://backend_server;
    proxy_cache my_cache;
    proxy_cache_use_stale updating error timeout invalid_header http_500 http_502 http_503 http_504;
    # Other proxy settings
}


These strategies can be used individually or in combination, depending on your specific use case and requirements. Choose a strategy or combination of strategies that best align with your application's behavior and update frequency.
Topics

Mastering Nginx

27 articles

Bash script

2 articles

Crontab

2 articles