nginx - clear cache on http PUT or POST nginx - clear cache on http PUT or POST nginx nginx

nginx - clear cache on http PUT or POST


I had the same question and found that Nginx allows you to "purge" the cached requests:

proxy_cache_path /tmp/cache keys_zone=mycache:10m levels=1:2 inactive=60s;map $request_method $purge_method {    PURGE 1;    default 0;}server {    listen 80;    server_name www.example.com;    location / {        proxy_pass http://localhost:8002;        proxy_cache mycache;        proxy_cache_purge $purge_method;    }}

Then

curl -X PURGE -D – "http://www.example.com/*"

See:

So I guess you could make those calls after each POST/PUT/PATCH/DELETE.

I see 4 caveats:

  1. Seems way more complicated (and probably slower) than the invalidation process offered by other caching strategies. So if you need to invalidate very often I'd probably recommend another caching strategy (e.g. caching the database queries in Redis)

  2. I didn't try it myself and I'm not sure if it's available with the basic version of Nginx (the doc talks only about Nginx Plus, which is their paid product)

  3. What's the granularity offered by this solution? Like is it possible to invalidate a request like GET /cars?year=2010&color=red and keep GET /cars?year=2020&color=green cached?

  4. I don't know if it's a really common thing to do, I couldn't find more about it.


You have not specified what sort of caching you are implementing as there are several options within Nginx.

From your query, I assume you are referring to static files like images which are uploaded to your site.

  1. Proxy Caching This is where Nginx caches the response from a backend server. There is no point in activating this for static files in the first place. The proxy cache is simply a store on your hard disc and the cost of retrieving such files is the same as if you just let Nginx serve them from there actual locations on the filesystem.

  2. FastCGI CachingSame as Proxy Caching. No point for the type of files that may be uploaded using POST or PUT.

  3. MemcacheHere, the items are stored in RAM and there is a benefit to this. There are the basic Memcache and the extended Memc Modules both of which have procedures for both adding to and removing from the cache.

Your query however suggests you are using one of the earlier two and as said, there is absolutely no benefit in doing this for the type of files that may be uploaded using POST or PUT. When cached in Nginx, they will be read from a disc location that they will be kept on just as would be done if referenced from the original disc location. There is also the overhead of copying them from the original disc location to another disc location.

Except of course if I am missing something.