Cloudflare Cache Adds Invalidation: Refresh Content Without Re-downloading Unchanged Files!
Hi everyone, it's Shii-chan!
Cloudflare ChangelogToday's news is a new Cloudflare Cache feature. If you've ever wanted to purge a group of assets without re-fetching the ones that didn't change, this one is for you!
What was announced?
The Cloudflare Changelog announced that you can now invalidate cached content instead of purging it.
Invalidation marks matching content as stale. On the next request, Cloudflare revalidates it with your origin. If the origin responds with 304 Not Modified, Cloudflare reuses the cached content instead of downloading it again.
The story so far
Purging removes content from the cache. So when you refreshed a group of assets, for example everything sharing a cache tag, all of it had to be fetched from the origin again, even if only a few files had actually changed.
What changes
- When you refresh a group, unchanged assets are answered with 304 and not downloaded again
- Unchanged content stays in the cache, which helps keep origin transfer down
This is handy for groups like product images, where there are many files but only some change.
Dive Deep
Using it feels a lot like purging.
- It supports the same selectors as purge: URLs, cache tags, hostnames, URL prefixes, and everything
- Your origin must return an
ETagorLast-Modifiedheader and support conditional requests - The API is a POST to the new
invalidate_cacheendpoint
curl --request POST \
"https://api.cloudflare.com/client/v4/zones/$ZONE_ID/invalidate_cache" \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--data '{"tags":["product-images"]}'
In the dashboard, use Invalidate Cache on the Caching > Configuration page.
A few things to keep in mind:
- Your cache settings determine whether Cloudflare serves stale content while it revalidates
- Cloudflare can also serve invalidated content stale if your origin returns a 5xx error or can't be reached
- If you need to stop serving cached content, purge it instead
- Invalidation requests count toward the same rate limits as purge requests
Wrap-up
- The new invalidate_cache marks content stale and has your origin revalidate it
- If the origin returns 304, unchanged assets aren't downloaded again
- Selectors match purge, and it works from both the API and the dashboard
- Your origin needs
ETagorLast-Modifiedplus conditional request support
This is for anyone who refreshes content by tag and cares about origin load and transfer!