We earn commissions using affiliate links.
Edge caching is an essential technique used to speed up web applications by storing content closer to the user, reducing latency and offloading origin servers. In this guide, we will explore how to implement edge caching by leveraging Cloud Storage and Cloudflare Workers. This solution is ideal for improving performance and scalability while minimizing the costs associated with handling large traffic volumes.
What is Edge Caching?
Edge caching refers to the practice of storing static content at locations geographically closer to the user, known as “edge locations.” These locations are part of a Content Delivery Network (CDN), which caches assets such as images, JavaScript files, and HTML at various edge servers around the world.
By utilizing edge caching, users experience faster load times as the data is served from the nearest edge server rather than the origin server, which could be located far away.
Cloud Storage Setup for Edge Caching
To implement edge caching, you will first need to store your static assets in a cloud storage service such as Amazon S3, Google Cloud Storage, or Azure Blob Storage. This storage acts as the origin for your content.
1. **Create a Cloud Storage Bucket**
Choose your preferred cloud storage service and create a bucket or container to store the files you want to serve via edge caching.
2. **Upload Static Assets**
Upload images, videos, CSS files, JavaScript files, and any other static content to the cloud storage. These assets will be retrieved by Cloudflare Workers and cached at the edge.
3. **Configure Access Permissions**
Ensure that the cloud storage bucket or container is publicly accessible or that you configure the appropriate API keys or authentication tokens for access.
gsutil mb gs://my-edge-cache-bucket
gsutil cp /path/to/static/* gs://my-edge-cache-bucket/
Setting up Cloudflare Workers
Cloudflare Workers allows you to run JavaScript at Cloudflare’s edge locations, giving you the flexibility to control caching, request routing, and other behaviors.
Create a Cloudflare Worker
First, you need to set up a Cloudflare Worker in your Cloudflare account.
Log in to your Cloudflare dashboard.
Navigate to the Workers section and click Create a Worker.
Write a Basic Worker Script for Caching
The worker will intercept requests for static content, fetch the content from the cloud storage, and cache it at the edge. Here’s a simple script for implementing this:
javascript
addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
const cache = caches.default
// Check if the content is cached at the edge
let response = await cache.match(request)
if (!response) {
// Fetch the content from Cloud Storage if it’s not cached
response = await fetchFromCloudStorage(url)
// Cache the response at the edge for future requests
event.waitUntil(cache.put(request, response.clone()))
}
return response
}
async function fetchFromCloudStorage(url) {
const storageUrl = https://my-cloud-storage-url.com/${url.pathname}
const response = await fetch(storageUrl)
return response
}
Cache Control and Expiration
When implementing edge caching, it is crucial to manage how long content stays in the cache before it is considered stale. Cloudflare Workers allows you to control the cache expiration using headers.
Set Cache Expiry Headers
You can use the Cache-Control header to specify how long the content should remain cached at the edge. This can be done in your worker script:
javascript
async function handleRequest(request) {
const url = new URL(request.url)
const cache = caches.default
// Check if the content is cached at the edge
let response = await cache.match(request)
if (!response) {
// Fetch the content from Cloud Storage if it’s not cached
response = await fetchFromCloudStorage(url)
// Set Cache-Control header
response = new Response(response.body, response)
response.headers.set(‘Cache-Control’, ‘max-age=86400’) // Cache for 24 hours
// Cache the response at the edge for future requests
event.waitUntil(cache.put(request, response.clone()))
}
return response
}
Custom Cache Expiry for Specific Content Types
You may want to apply different cache lifetimes based on content type. For example, images might be cached longer than HTML files.
javascript
if (url.pathname.endsWith(‘.jpg’) || url.pathname.endsWith(‘.png’)) {
response.headers.set(‘Cache-Control’, ‘max-age=604800’) // Cache for 7 days
} else {
response.headers.set(‘Cache-Control’, ‘max-age=3600’) // Cache for 1 hour
}
Optimizing Edge Caching Performance
To fully optimize edge caching with Cloudflare Workers, consider the following performance enhancements:
Stale-While-Revalidate
You can serve stale content from the cache while fetching a fresh version from the origin, reducing wait times for the user.
javascript
response = await cache.match(request)
if (!response) {
// Serve stale content immediately, fetch new content in the background
response = new Response(“Stale content”, { status: 200 })
event.waitUntil(fetchFromCloudStorage(url).then(res => cache.put(request, res.clone())))
}
Cache Tags
You can use cache tags to invalidate specific content groups. This can be useful when you have dynamic content but want to cache certain assets separately.
javascript
response.headers.set(‘Cache-Tag’, ‘image, js, css’)
Debugging and Monitoring Cache Performance
Cloudflare provides various tools for monitoring the performance of your workers and cache. You can inspect cache hits and misses through the Cloudflare dashboard and adjust your strategy accordingly.
Analytics Dashboard
Cloudflare offers detailed analytics to track how well your cache is performing and how often requests are served from the edge rather than the origin server.
Cache-Status Headers
To debug caching behavior, you can add Cache-Status headers in your worker script to see whether content was served from cache or fetched from the origin.
javascript
response.headers.set(‘Cache-Status’, ‘HIT’)


