← Back to blog
magentoperformancevarnish

Optimizing Magento 2 Performance with Varnish Cache

·2 min read

Why Varnish Matters for Magento

Magento 2 is a powerful e-commerce platform, but out of the box, its full-page rendering can be resource-intensive. Varnish Cache sits in front of your web server and serves cached pages directly from memory, dramatically reducing response times.

In production environments, I've seen Varnish reduce time-to-first-byte (TTFB) from 800ms+ down to under 50ms for cached pages.

Basic Setup

Magento 2 ships with a built-in VCL (Varnish Configuration Language) generator. You can export it from:

Admin > Stores > Configuration > Advanced > System > Full Page Cache

Set the caching application to Varnish Cache and export the VCL file for your Varnish version.

Key Configuration Tips

1. Health Checks

Always configure backend health checks to ensure Varnish doesn't serve stale content when your backend is down:

backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .probe = {
        .url = "/health_check.php";
        .interval = 5s;
        .timeout = 1s;
        .window = 5;
        .threshold = 3;
    }
}

2. Cache Warming

After deploying new code or flushing cache, your site will be slow until pages are re-cached. Implement a cache warmer that crawls your most important URLs:

#!/bin/bash
while read url; do
    curl -s -o /dev/null -w "%{http_code} %{time_total}s %{url_effective}\n" "$url"
done < urls.txt

3. Hole Punching with ESI

For pages that are mostly static but have dynamic elements (like the mini-cart or customer greeting), use Edge Side Includes (ESI):

<esi:include src="/customer/section/load/?sections=cart" />

Magento 2 handles ESI blocks automatically through its layout XML system.

Monitoring

Use varnishstat to monitor your hit rate. A well-configured Magento + Varnish setup should achieve a 90%+ cache hit ratio for anonymous traffic.

varnishstat -f MAIN.cache_hit -f MAIN.cache_miss

Conclusion

Varnish is essential for any production Magento 2 store. The combination of full-page caching, ESI for dynamic blocks, and proper cache invalidation gives you the best of both worlds: fast page loads and dynamic content.