Search code examples
cachingvarnishvarnish-vcl

Varnish 4 Hit Miss Header?


Does anyone have an updated hit miss header working for Varnish 4?

Last one I found was for version 3.

https://www.varnish-cache.org/trac/wiki/VCLExampleHitMissHeader#Varnish3.0

Looking for these:

set beresp.http.X-Cacheable = "NO:Not Cacheable"; "NO:Got Session"; "NO:Cache-Control=private"; "YES";

and possibly other useful debug output on why requests were missed.


Solution

  • Yes, I have:

    sub vcl_deliver {
        if (obj.hits > 0) { # Add debug header to see if it's a HIT/MISS and the number of hits, disable when not needed
            set resp.http.X-Cache = "HIT";
        } else {
            set resp.http.X-Cache = "MISS";
        }
        # Please note that obj.hits behaviour changed in 4.0, now it counts per objecthead, not per object
        # and obj.hits may not be reset in some cases where bans are in use. See bug 1492 for details.
        # So take hits with a grain of salt
        set resp.http.X-Cache-Hits = obj.hits;
    }
    

    A direct translation of the varnish 3 version of the requested headers to varnish 4:

    sub vcl_backend_response {
    
        if (bereq.http.Cookie ~ "(UserID|_session)") {
            set beresp.http.X-Cacheable = "NO:Got Session";
            set beresp.uncacheable = true;
            return (deliver);
    
        } elsif (beresp.ttl <= 0s) {
            # Varnish determined the object was not cacheable
            set beresp.http.X-Cacheable = "NO:Not Cacheable";
    
        } elsif (beresp.http.set-cookie) {
            # You don't wish to cache content for logged in users
            set beresp.http.X-Cacheable = "NO:Set-Cookie";
            set beresp.uncacheable = true;
            return (deliver);
    
        } elsif (beresp.http.Cache-Control ~ "private") {
            # You are respecting the Cache-Control=private header from the backend
            set beresp.http.X-Cacheable = "NO:Cache-Control=private";
            set beresp.uncacheable = true;
            return (deliver);
    
        } else {
            # Varnish determined the object was cacheable
            set beresp.http.X-Cacheable = "YES";
        }
    
        # ....
    
        return(deliver);
    }
    

    There is some documentation about upgrading to Varnish 4 that covers this things:

    vcl_fetch is now vcl_backend_response

    hit_for_pass objects are created using beresp.uncacheable

    req.* not available in vcl_backend_response

    req.* used to be available in vcl_fetch, but after the split of functionality, you only have 'bereq.*' in vcl_backend_response.