Over the last month or so, my Cloudflare cache rate for this blog has been sitting around 90%, which is pretty high. Also, this blog is completely static and it’s hosted on Netlify, so a high Cloudflare cache rate probably doesn’t matter much anyway. Regardless, I’ve been thinking about how to increase the cache rate even further (because I’m insane), and being more selective with my cache purging was the first thing that came to mind.

After each deployment to Netlify, I use the serverless function below to clear my Cloudflare cache. This is very important because I use Cloudflare to cache HTML in addition to other static assets. If I don’t trigger a cache purge, new posts won’t show up on the home page.

import requests

def clear_cloudflare_cache(request):
	url = "https://api.cloudflare.com/client/v4/zones/ZONE-ID/purge_cache"
	headers = {
    	"X-Auth-Email": "ACCOUNT-EMAIL",
    	"X-Auth-Key": "API-KEY",
    	"Content-Type": "application/json"
    	}
	payload = '{ "purge_everything": true }'
	r = requests.post(url, headers=headers, data=payload)

As you can see, the function above purges everything. If maximizing cache rate is the goal, purging everything is not a good idea. So, today, I made a few tweaks to the curl request to specify a select few URLs to purge after each deployment.

def clear_cloudflare_cache_urls(request):
	url = "https://api.cloudflare.com/client/v4/zones/ZONE-ID/purge_cache"
	headers = {
    	"X-Auth-Email": "ACCOUNT-EMAIL",
    	"X-Auth-Key": "API-KEY",
    	"Content-Type": "application/json"
    	}
	payload = '{ "files": [ "https://brianli.com/", "https://brianli.com/page/2/", "https://brianli.com/page/3/", "https://brianli.com/archive/", "https://brianli.com/index.xml", "https://brianli.com/sitemap.xml" ] }'
	r = requests.post(url, headers=headers, data=payload)

For now, I’m going to purge the following pages.

  • The home page
  • The first few index pages
  • The archive page
  • The RSS feed
  • The sitemap

I think this will have a positive impact on my cache rate. I’ll have more data in a week or so, so I’ll follow up early next month.