Magento 2 Debug Varnish cache in production mode

Hello,

By default, Magento 2 offers to debug Varnish if pages are in MISS or HIT mode when Developer mode is enabled. You can debug the store in two ways in the Production mode.

1) varnishlog
varnishlog is a CLI tool written to read the output from the Varnish service in format order. You can print output on the terminal, parse it to other formats, stream outside of the container or service, or similar. For more details about the varnishlog tool, you can read the following https://varnish-cache.org/docs/trunk/reference/varnishlog.html address.

To limit output only to your IP address, we can use the following CLI command:

varnishlog -q "ReqHeader eq 'X-Real-IP: 178.223.40.243'"  

Note: Update your real IP address. You can use X-Real-IP or X-Forward-For depending on your Upstream and Webserver settings.

The standard output has a lot of information, but mostly it starts with:

<< Request  >>  

Then it has a timestamp, ReqStart, ReqMethod (GET, POST...), ReqURL, and ReqProtocol, but the longest part is ReqHeader and RespHeader section. varnishlog is not the tool you want to collect logs to store. However, it’s the perfect choice to obtain debugging data thanks to the indecent amount of data it produces.

The one I find important to debug the Varnish cache is:

VCL_call  

It can end up as DELIVER (not cached) or HIT (cached). You can read Varnish documentation pages Varnish Output on how many other options can be used. Typically followed by VCL_call Deliver is RespHeader Age: 0

alt alt

2) If you find this hard and not efficient enough (yeah, I know the browser/inspect header sounds better), we can do the following to debug and make it easier.

  • Under sub vcl_deliver { section comment few lines.
 //if (resp.http.X-Magento-Debug) {
        if (resp.http.x-varnish ~ " ") {
            set resp.http.X-Magento-Cache-Debug = "HIT";
        } else {
            set resp.http.X-Magento-Cache-Debug = "MISS";
        }
    //} else {
       // # unset resp.http.Age;
    //}

Note: by default, it's without //

Save the VCL file, test, and reload your Varnish cache. You will see there is a new RespHeader added on page load.

alt

What is x-magento-cache-debug you can read here:
https://experienceleague.adobe.com/docs/commerce-operations/configuration-guide/cache/varnish/config-varnish-final.html

That's it! Now you follow this simple trick, leave your store in the Production mode, and still debug your Varnish cache if pages are HIT or MISS.

Good luck!