Cloudflare: Cache anonymous requests with a worker

Granted my site is pretty small, but speed drastically improved after setting up Cloudflare edge caching:

my site is faster than yours

In this Cloudflare Blog Post titled ‘Caching Anonymous Page Views’ it is outlined that you can cache anonymous page views on their edge servers and bypass any edge caches with certain cookies:

Cloudflare is determined to help website administrators boost the performance of their websites. From today, Cloudflare users on our Business plan will gain a previously Enterprise-only Page Rule option, “Bypass Cache on Cookie”. When used in conjunction with a “Cache Everything” Page Rule, this setting allows for websites to cache the HTML of anonymous page visits without affecting dynamic content.

By caching anonymous page views, Cloudflare is able to help ensure that your origin webserver doesn’t waste time constantly regenerating pages which change rarely. This ultimately allows us to reduce load on your server and reduce load times when users reach your site.

However with the recent introduction of Cloudflare Workers it is possible to run javascript workers on edge servers with 5ms of execution time to evaluate/modify a http request and response. It’s also possible to control how other features affect the request such as ‘ScrapeShield’, ‘Polish’, ‘Minify’ etc. Here we are going to modify the Edge Cache TTL to instruct Cloudflare not to cache the response at all upon matching the following cookies: wordpress_logged*, comment_*, wordpress_sec*.

Here’s the code:

Positive TTL values indicate in seconds how long Cloudflare should cache the asset for: a TTL of 0 will cause assets to get cached, but expire immediately (revalidate from origin every time), -1, or any negative value will instruct Cloudflare not to cache at all.

Testing using httpstat without triggering cookies (anonymous request)

And now with cookies which will bypass the cache (logged in user/commenter):

Look at how much faster download times are when the site is edge-cached! (Note that network transfer speed is misrepresented as server response times) – mind you I’m half way across the world from my origin right now hence the slow transfer.

Great, now I don’t need to pay $200 a month for a CF business plan, just $5 for the worker (and any requests exceeding 10,000,000)

Apologies if this post is short, the keyboard on my 4 month old MacBook is dying 🙁

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.