We are planning a CDN cache key refactor that introduces:
Device segmentation: The cache key should differentiate between different device types (e.g., mobile, tablet, desktop).
A/B buckets: We want to be able to route a percentage of traffic to a different version (e.g., for A/B testing) and cache separately for each bucket.
Purge metrics: We want to be able to purge by the new segments (device and A/B bucket) and also have metrics on purge operations.
Steps:
Define the cache key structure:
The cache key will now include:
a. The original cache key (e.g., URL, query string, etc.)
b. Device type (derived from User-Agent or a custom header)
c. A/B bucket (from a cookie or a header, or by a hash of the user ID if we want consistent assignment)
We can use the User-Agent string and map to device categories (mobile, tablet, desktop) using a library or regex.
Alternatively, if the client sends a custom header (like X-Device-Type), we can use that.
A/B bucket assignment:
We can assign users to buckets via a cookie (e.g., ab_bucket=control|variant1|variant2).
Alternatively, we can use a header (e.g., X-AB-Bucket) if we want to control it from the client or from a feature flag service.
If we don't have a cookie/header, we might want to assign by a consistent hash (e.g., of user ID or IP) to ensure the same user gets the same bucket. However, note that IP might change and user ID might not be present for anonymous users.
We need to decide on a strategy. Let's assume we are using a cookie named ab_bucket that can have values: control, variant1, variant2, etc.
Cache key construction at the CDN edge:
The CDN (e.g., Cloudflare, Fastly) will need to be configured to construct the cache key using the above components.
Example in Cloudflare (using Workers or Page Rules) or in Fastly (VCL) we can do:
Let's break down:
Original cache key: typically the URL and query string (without certain parameters that are not cacheable, but that's another topic).
Device type: from User-Agent header, we can set a variable device_type by parsing.
A/B bucket: from the Cookie header, we look for ab_bucket and take its value. If not present, we might default to control or a default bucket? Or maybe we don't set and then the cache key doesn't include the bucket? But then we wouldn't separate traffic.
We must decide on a default for the bucket. Let's say if no bucket is assigned, we use default.
So the cache key becomes: {url_without_query?}|{query_string?}|{device_type}|{ab_bucket}
But note: we might not want to include query string in the original cache key? That depends on the site. We are just refactoring the key to include device and bucket.
Purge metrics:
We want to be able to purge by:
a. Device type: so we can purge all mobile caches, for example.
b. A/B bucket: so we can purge a specific variant.
c. Also, we want to be able to purge by the original cache key (without device and bucket) for backward compatibility? Probably not, because the old cache keys are different.
However, note that the cache key has changed. So purging by the old key (without device and bucket) won't work.
We need a way to map old purges to the new keys? Maybe not, because we are changing the cache key structure. We might have to purge everything when we switch? Or we can do a gradual rollout?
Alternatively, we can design the cache key so that it is backward compatible? That might be hard.
Let's assume we are going to switch to the new cache key and we will have to purge the entire cache when we switch? That might be too disruptive.
Alternatively, we can do:
Phase 1: Start using the new cache key for new content, but also keep the old cache key for a while? That would double the cache.
But the requirement is to refactor the cache key. So we are replacing the old one.
We can do:
Step 1: Deploy the new cache key construction, and then purge by the old key for all the old cached items? But the old key doesn't have device and bucket, so we would have to generate all combinations? That's not feasible.
Alternatively, we can purge by a tag? We can tag the old cached items with a tag that we can then purge? But that requires the old cache key to have been tagged? Not necessarily.
Given the complexity, maybe we do:
We change the cache key and then we purge everything (by a wildcard or by a tag that we set on all old items?).
But we don't have a tag on old items.
So the practical approach:
We change the cache key and then we have to wait for the old cache to expire? That might take a long time.
Alternatively, we can do a double-key approach for a while:
In the CDN configuration, we can set two cache keys? Some CDNs allow multiple cache keys? Not typically.
We can use a surrogate key? Or we can set a tag on the new cache entries and then purge by that tag? But the old ones don't have the tag.
Given the constraints, I think we have to accept that we will have a cache miss for all old URLs until they are re-cached with the new key.
However, we can try to mitigate:
We can set a short TTL on the old cache (if we control it) and then when we switch, we set a longer TTL on the new cache.
But if we don't control the origin TTL? Then we have to wait for the old TTL to expire.
Alternatively, we can do:
Purge metrics:
We want to track:
- Number of purges by device type (how many purge requests for mobile, tablet, desktop)
- Number of purges by A/B bucket (control, variant1, etc.)
- Also, we might want to know the total number of purges and the success rate.
How to do this?
We can log each purge request (at the CDN level) and then aggregate by the tags (device and bucket) that we are purging.
But note: a purge request might be for a specific URL (with device and bucket) or for a tag (like all mobile, or all variant1).
We need to design the purge API to accept tags for device and bucket.
Example:
code
Implementation:
We need to modify the CDN configuration (or the origin application if we are setting the surrogate keys from the origin) to set these surrogate keys.
Steps:
a. Parse the User-Agent to get device type. We can use a library or a simple regex. We might have to handle tablet separately.
code
Example mapping:
- If User-Agent contains "Mobile" or "Android" or "iPhone" -> mobile
- If User-Agent contains "Tablet" or "iPad" -> tablet
- Else -> desktop
But this is oversimplified. We might use a library like `mobile-detect.js` or similar.
Since we are at the CDN edge, we might have to use a CDN-provided device detection (like Cloudflare's `Browser` or `Device` variables) or we can use a custom script (Workers for Cloudflare, VCL for Fastly).
b. Get the A/B bucket from the Cookie header (or a header). We'll parse the Cookie header for ab_bucket. If not present, we set to default.
c. Get the original URL (without query string? or with? We have to be consistent). Let's say we use the full URL including query string? But then if the query string is used for cache busting, we might not want to include it? That's a separate decision.
code
We are only concerned with the cache key structure for device and bucket. We assume the original cache key is already defined (by the CDN's default or by our existing rules).
We might have to adjust: we want the original cache key to be the same as before, but now we are adding device and bucket.
So we take the existing cache key (which might be the URL and query string, but without some parameters) and then append device and bucket.
d. Set the surrogate keys:
code
Metrics:
We want to track:
code
- How many purge requests by tag type (url, device, ab_bucket, url_device_bucket)
- How many objects were purged by each? (the CDN might return the count)
We can log the purge requests at the CDN and then aggregate.
For example, in Fastly, we can use the real-time logs or the analytics.
We can set up a dashboard that shows:
code
- Total purges
- Purges by tag type (url, device, ab_bucket, url_device_bucket)
- Success/failure rate
We can also break down by device type and bucket for the purges that use those tags.
But note: a purge request might use multiple tags? Then we count it for each tag? Or we count the request once and then break down by the tags used?
We can log:
code
- timestamp
- purge request type (by surrogate key, by URL, etc.)
- the tags used (list)
- number of objects purged (if available)
- success
Then we can aggregate.
Rollout plan:
Step 1: Implement device detection and A/B bucket extraction in the CDN configuration (or in the origin if setting surrogate keys from origin).
Step 2: Set the new cache key and surrogate keys.
Step 3: Test with a small percentage of traffic? We can use a feature flag to only apply the new cache key for a percentage of users? But then we have two cache keys for the same content? That might be acceptable for a gradual rollout.
Purge by url:<original_cache_key>: purges all device and bucket combinations for that original cache key.
Purge by device:<device_type>: purges all URLs and buckets for that device.
Purge by ab_bucket:<ab_bucket>: purges all URLs and devices for that bucket.
Purge by url_device_bucket:<original_cache_key>:<device_type>:<ab_bucket>: purges exactly that combination.
Metrics:
We log every purge request with:
- timestamp
- the tags used (list of tags)
- number of objects purged (if available from CDN)
- success
Then we can aggregate:
code
- Total purge requests
- By tag type (how many used `url`, how many used `device`, how many used `ab_bucket`, how many used `url_device_bucket`)
- By device type (for purges that used a device tag, break down by device value)
- By bucket (for purges that used an ab_bucket tag, break down by bucket value)
- Success rate
Rollout:
Step 1: Implement the cache key and surrogate tags in the CDN configuration (or in the origin if setting from there).
Step 2: Test with a small percentage of traffic? We can use a feature flag to only apply the new cache key for a percentage? But then we have two cache key structures? That's messy.
Alternatively, we can do a gradual rollout by assigning the A/B bucket cookie to a percentage of users? But device segmentation is for all.
We can do:
code
Implementation details:
We need to implement:
a. Device detection:
code
In Cloudflare Workers:
let deviceType = 'desktop';
const userAgent = request.headers.get('User-Agent') || '';
if (/(mobile|android|iphone|ipod|blackberry|opera mini|iemobile)/i.test(userAgent)) {
deviceType = 'mobile';
} else if (/(tablet|ipad)/i.test(userAgent)) {
deviceType = 'tablet';
}
In Fastly VCL:
set req.device_type = "desktop";
if (req.http.User-Agent ~ "(mobile|android|iphone|ipod|blackberry|opera mini|iemobile)") {
set req.device_type = "mobile";
} else if (req.http.User-Agent ~ "(tablet|ipad)") {
set req.device_type = "tablet";
}
b. A/B bucket:
code
We get from cookie:
In Cloudflare Workers:
let bucket = 'default';
const cookies = request.headers.get('Cookie') || '';
const match = cookies.match(/ab_bucket=([^;]+)/);
if (match) {
bucket = match[1];
}
In Fastly VCL:
set req.ab_bucket = "default";
if (req.http.Cookie ~ "ab_bucket=") {
// extract the value
// VCL regex: set req.ab_bucket = regsub(req.http.Cookie, ".*ab_bucket=([^;]+).*", "\1");
// But note: the cookie might have multiple cookies. We can use:
set req.ab_bucket = regsub(req.http.Cookie, ".*ab_bucket=([^;]+).*", "\1");
}
c. Cache key:
code
Conclusion:
We will:
Always include device and bucket in the cache key.
Device from User-Agent (or header) and bucket from cookie (or default).
Set surrogate keys for purge: url, device, ab_bucket, and url_device_bucket (combination).
In the CDN configuration (Worker or VCL), we set the cache key to include these three and set the surrogate keys.
Rollout:
Phase 1: Deploy with bucket always set to default (ignore cookie) for all users. This will segment by device and by bucket (default). We are building the cache for default bucket.
Phase 2: After a week, start using the cookie for bucket assignment. Then we will have two types of users: default and bucketed.
Purge metrics: log purge requests and aggregate by tag type, device, bucket.
This plan should work for both Cloudflare and Fastly (with slight variations in implementation).
I'll help you plan a comprehensive CDN cache key refactor that introduces device segmentation, A/B testing buckets, and purge metrics. This plan covers design, implementation, rollout, and monitoring.
# Max cardinality limits per segment
MAX_DEVICE_TYPES = 5 # mobile/tablet/desktop/other
MAX_AB_BUCKETS = 20 # experiments + control
# Expected max keys: URLs × devices × buckets
# Circuit breaker: if new key creation rate > threshold,
# fall back to old key + device segment only
B. Rollback Plan:
Feature flag to disable new segments immediately
CDN-level cache purge of all new keys (ab_bucket:* pattern)
Monitoring for cache miss surge during rollback
C. Data Consistency:
Sticky sessions for logged-in users (device+bucket consistency)
Cache warming for high-traffic URLs × segments
Graceful degradation: missing bucket → use device-only key
7. Rollback Triggers
Condition
Action
Timeframe
Hit rate drops >20%
Rollback to old key
Immediate
Cache storage >110%
Throttle new bucket creation
1 hour
Purge errors >1%
Disable purge-by-bucket
Immediate
Bucket distribution skew
Rebalance assignments
24 hours
8. Post-Implementation Review (4 weeks after)
Success Criteria:
Mobile cache hit rate improved by ≥8%
A/B experiments running without cache contamination
This refactor provides the flexibility for personalization while maintaining cache efficiency. The key is gradual rollout with comprehensive monitoring to catch cardinality explosions or hit rate regressions early.
When we switch, we set a rule that if the request doesn't have the device and bucket (i.e., the old way) then we force a cache miss and re-fetch from origin, and then cache with the new key.
But then the first request for each old URL will be a miss.
So the plan:
a. Deploy the new cache key configuration.
b. Purge the entire cache (if possible) to avoid serving old content with the new key? But if we purge the entire cache, then we have to re-cache everything with the new key.
Alternatively, we can do:
We can set the cache key to:
If the request has the ab_bucket cookie and we can determine the device, then use the new key.
Otherwise, use the old key (without device and bucket) for a transition period.
Then we can gradually roll out the cookie and device detection? But the requirement is to have device segmentation and A/B buckets for all.
Given the requirement, I think we have to have the new key for all requests.
So we must accept that we will have cache misses for all URLs until they are re-requested.
To minimize impact, we can:
Pre-warm the cache for important URLs? We can script requests for important URLs with various device types and buckets? But that might be a lot.
Purge by URL: we have to specify the full cache key (with device and bucket) or we can specify a pattern?
Alternatively, we can have:
- Purge by URL (without device and bucket) -> this will purge all device and bucket combinations for that URL? That might be what we want.
But then we have to generate the cache keys for all devices and buckets for that URL? That's not efficient.
Alternatively, we can tag each cache entry with:
- The original URL (without device and bucket) as a tag? And then we can purge by that tag? And also by device and bucket?
So we can have:
Tags on a cache entry:
- `url:<original_url>`
- `device:<device_type>`
- `ab_bucket:<bucket_name>`
Then we can purge by:
- `url:<original_url>`: purges all devices and buckets for that URL.
- `device:mobile`: purges all mobile cache entries (for all URLs and buckets).
- `ab_bucket:control`: purges all control bucket (for all URLs and devices).
And combinations? Like `url:example.com/page1 AND device:mobile`? That might be more complex and not supported by all CDNs.
We have to check the CDN's purge capabilities.
For example, Fastly supports purging by tags (surrogate keys) and by URL.
So we can set surrogate keys for each cache entry:
surrogate-key: url:<original_url> device:<device_type> ab_bucket:<bucket_name>
Then we can purge by any of these tags individually.
But note: the CDN might have a limit on the number of surrogate keys per object? And also, we are adding 3 tags per object.
Alternatively, we can use a single surrogate key that is a combination? Then we can't purge by individual attributes.
So we want multiple tags.
We have to check the CDN's limits.
Let's assume we can set multiple surrogate keys.
Then:
- When we cache a response, we set the surrogate keys to:
- `url:<original_url>`
- `device:<device_type>`
- `ab_bucket:<bucket_name>`
Then we can purge by:
- `url:<original_url>`: purges all devices and buckets for that URL.
- `device:mobile`: purges all mobile (for all URLs and buckets).
- `ab_bucket:control`: purges all control (for all URLs and devices).
We can also purge by multiple tags? That depends on the CDN.
For example, Fastly supports:
POST / purge / surrogate-key?key=url:example.com/page1&key=device:mobile
That would purge entries that have both tags? Actually, in Fastly, it's an OR? Let me check: Fastly's surrogate key purge is by OR? Actually, when you purge by multiple keys, it's an OR (any object that has at least one of the keys). So if we want AND, we have to do multiple purges? Or we can set a combined key?
So if we want to purge by URL and device, we might have to do:
purge by `url:example.com/page1` and then by `device:mobile`? That would purge all with that URL and all with that device, which is more than just the intersection.
So we need a way to purge the intersection.
Alternatively, we can set a combined key for the triple:
`url_device_bucket:<original_url>:<device_type>:<bucket_name>`
Then we can purge by that exact key? But then we can't purge by just device or just bucket? We would have to know all the combinations? That's not feasible.
So we have two options:
Option 1: Set three separate tags and accept that we can only purge by one tag at a time (OR). Then to purge the intersection, we have to do multiple purges and accept that we might purge more than needed? Or we can purge by the URL and then by the device and bucket separately? That would purge:
- All devices and buckets for the URL (from the first purge)
- Then all the device for all URLs (from the second) and all the bucket for all URLs (from the third) -> that's too much.
Option 2: Set a combined tag for the triple and then also set the individual tags? Then we can purge by the combined tag for exact matches, and by individual tags for broader purges.
Example:
surrogate-key:
- `url_device_bucket:<original_url>:<device_type>:<bucket_name>`
- `url:<original_url>`
- `device:<device_type>`
- `ab_bucket:<bucket_name>`
Then:
- Purge by `url_device_bucket:example.com/page1:mobile:control` -> only that exact combination.
- Purge by `url:example.com/page1` -> all devices and buckets for that URL.
- Purge by `device:mobile` -> all mobile for all URLs and buckets.
- Purge by `ab_bucket:control` -> all control for all URLs and devices.
This way we have flexibility.
But note: we are setting 4 tags per object. We have to check the CDN's limit.
Let's assume the CDN allows at least 4 tags.
We can adjust: maybe we don't need the individual tags? But then we can't purge by device or bucket alone.
Given the requirement to purge by device and by A/B bucket, we need at least the individual device and bucket tags.
So we set:
surrogate-key:
- `url_device_bucket:<original_url>:<device_type>:<bucket_name>`
- `device:<device_type>`
- `ab_bucket:<bucket_name>`
And maybe also `url:<original_url>`? Because we might want to purge by URL without caring about device and bucket? That would purge all devices and buckets for that URL.
But note: the `url_device_bucket` already includes the URL, so if we purge by `url_device_bucket` for a specific URL, device, bucket, that's one. Then if we want to purge all for a URL, we would have to know all the device and bucket combinations? Not feasible.
So we need the `url` tag to purge by URL.
So we set:
surrogate-key:
- `url:<original_url>`
- `device:<device_type>`
- `ab_bucket:<bucket_name>`
- `url_device_bucket:<original_url>:<device_type>:<bucket_name>` [optional, for exact triple]
Then:
- To purge by URL (all devices and buckets): use `url:<original_url>`
- To purge by device: use `device:<device_type>`
- To purge by bucket: use `ab_bucket:<bucket_name>`
- To purge by exact triple: use `url_device_bucket:<original_url>:<device_type>:<bucket_name>`
But note: when we purge by `url:<original_url>`, we are purging all the entries that have that URL tag, which includes all devices and buckets for that URL. That's what we want.
And when we purge by `device:<device_type>`, we are purging all entries that have that device tag, which includes all URLs and buckets for that device.
So we don't really need the `url_device_bucket` tag? Because if we want to purge a specific combination, we can do:
purge by `url:<original_url>` and then by `device:<device_type>` and then by `ab_bucket:<bucket_name>`? That would be three separate purges and would purge:
- All URLs with that device (including the one we want) -> too much.
- All URLs with that bucket (including the one we want) -> too much.
- Then by the URL -> but we already did by URL and device and bucket? Actually, we would have to do:
purge by `url:<original_url>` -> purges all device and bucket for that URL.
then we have to re-cache the ones we didn't want to purge? That's not good.
So without the `url_device_bucket` tag, we cannot purge the intersection without purging more.
Therefore, we need the `url_device_bucket` tag for exact triple purges.
So we set 4 tags.
Let `original_cache_key` be the string that the CDN uses for the original cache key (without device and bucket). We can get that by the CDN's variable (like `req.url` in Fastly, or `request.url` in Cloudflare) and then remove the query string if needed? Actually, we want the same as before.
We have to be careful: if the original cache key already includes some device-related stuff? Then we are changing it.
We assume the original cache key does not include device or bucket.
Then:
surrogate-key:
- `url:<original_cache_key>` [Note: we are using the original cache key as the URL tag? But the original cache key might include query string? We want to purge by the same string that we use for the cache key? Yes, so that when we purge by `url:<original_cache_key>`, it purges all device and bucket for that original key.
But note: the original cache key might be too long? And we are using it as a tag? We have to check the CDN's tag length limit.
Alternatively, we can use a hash of the original cache key? But then we have to store the mapping? Not necessary.
We can set:
surrogate-key:
- `url_hash:<hash_of_original_cache_key>`
- `device:<device_type>`
- `ab_bucket:<bucket_name>`
- `url_hash_device_bucket:<hash_of_original_cache_key>:<device_type>:<bucket_name>`
Then we purge by the hash? But then we have to compute the same hash when purging.
That might be acceptable.
Let's stick to using the original cache key string (without device and bucket) as the URL tag? But note: the original cache key might include the query string? And if we want to purge by a URL without query string? That's a problem.
We have to decide: what is the "URL" for purge by URL? Is it the full URL (with query string) or without?
Typically, when we purge by URL, we mean the full URL including query string? But then if we have multiple query strings that are cacheable, we have to purge each one.
So maybe we want to purge by the path without query string? That would purge all query strings for that path? That might be too broad.
Given the complexity, maybe we define:
The "URL" for tagging and purging is the full URL (including query string) as it is used in the cache key.
So if the original cache key includes the query string, then the `url` tag is the full URL with query string.
Then when we purge by `url:https://example.com/page?foo=bar`, it purges only that specific query string.
But if we want to purge all query strings for a path, we would have to purge by a pattern? Not supported.
So we have to accept that.
Alternatively, we can use the path (without query string) for the `url` tag? Then we can purge by path and it will purge all query strings for that path? But then we are purging more than needed? And we are not able to purge a specific query string? We can use the `url_device_bucket` tag for the full key.
Let's define:
Let `original_cache_key` be the string that we use for the cache key before adding device and bucket. This is typically the URL (including query string) but without certain parameters (like session IDs) that are stripped.
We set:
surrogate-key:
- `url_path:<path>` [the path without query string]
- `url_query:<query_string>` [the query string? But then we have to combine?]
This is getting too complex.
Given the time, let's stick to:
We use the full original cache key (which is the URL and query string as used in the cache key) for the `url` tag.
Then:
- Purge by `url:<original_cache_key>` will purge all devices and buckets for that exact original cache key.
And we also set:
- `device:<device_type>`
- `ab_bucket:<bucket_name>`
- `url_device_bucket:<original_cache_key>:<device_type>:<bucket_name>` [for exact triple]
Then we can also purge by device and bucket individually.
But note: the `url_device_bucket` tag is redundant because we can achieve the same by purging by `url` and then by `device` and then by `ab_bucket`? But as we saw, that would be OR and not AND.
So we need `url_device_bucket` for the exact triple.
And we need `url` for purging by the original cache key (which is the same as the old cache key, but note: the old cache key didn't have device and bucket, so the old cache key is exactly the `original_cache_key`? Yes.
So when we purge by `url:<original_cache_key>`, we are purging all the new cache entries that have that original cache key (with any device and bucket). That is the same as purging by the old cache key? Yes, because the old cache key was exactly `original_cache_key` (without device and bucket). So we are purging all the new entries for that URL? Yes.
That is what we want.
So:
- To purge what used to be the old cache entry (which now is split by device and bucket), we purge by `url:<original_cache_key>`.
That's good.
And if we want to purge a specific device and bucket for a URL, we use `url_device_bucket:<original_cache_key>:<device_type>:<bucket_name>`.
And if we want to purge all mobile, we use `device:mobile`.
And if we want to purge all control bucket, we use `ab_bucket:control`.
We can do:
If the request has a cookie `ab_bucket` (or we assign one) then we use the new cache key? But then we are only segmenting for users with the cookie? That might be acceptable for A/B testing.
But the requirement is to have device segmentation for all. So we want device segmentation even for users without an A/B bucket? Yes.
So we have to apply the device segmentation for all.
But for A/B bucket, we only want to segment if the user is in a bucket? And if not, we use a default bucket? Then we are segmenting by device for all, and by bucket only for bucketed users.
That's acceptable.
So:
- Device type: always determined (even if we don't have an A/B bucket).
- A/B bucket: if the user has the cookie, use that bucket; else, use `default`.
Then the cache key becomes:
`{original_cache_key}|{device_type}|{ab_bucket}`
And the surrogate keys:
- `url:<original_cache_key>`
- `device:<device_type>`
- `ab_bucket:<ab_bucket>`
- `url_device_bucket:<original_cache_key>:<device_type>:{ab_bucket}`
But note: if the user is not bucketed (i.e., `ab_bucket=default`), then we are creating a separate cache for default? That's okay, but then we have to purge the default bucket when we update the content? Yes.
Alternatively, we might not want to create a separate cache for default? Because then we are caching the same content multiple times (once for each device and once for default?).
Actually, if we have device segmentation, then even without bucket we are already segmenting by device. So we have:
For a user without bucket (default) and mobile: cache key = `original|mobile|default`
For a user with bucket (control) and mobile: cache key = `original|mobile|control`
So we are caching two different objects for the same device (mobile) but different buckets.
That's the point.
But if we don't want to segment by bucket for non-bucketed users, then we should not include the bucket in the cache key? But then how do we segment? We only want to segment for bucketed users.
So:
If the user has a bucket, then the cache key includes the bucket.
If not, then the cache key does not include the bucket? Then we have two different cache key structures? That's messy.
Alternatively, we always include the bucket, and if the user doesn't have a bucket, we set it to `default`. Then we are segmenting by bucket for everyone, but the `default` bucket is for non-bucketed users.
That's simpler.
But then we are caching the same content for the same device in two different buckets (if we have a bucketed user and a non-bucketed user, they get different caches). That might be acceptable because the content might be the same? But we are serving different cached objects? That's a waste.
We can avoid that by not including the bucket in the cache key for non-bucketed users? But then we have to conditionally build the cache key.
Let's do:
If the user has an A/B bucket (cookie set), then cache key = `{original_cache_key}|{device_type}|{ab_bucket}`
Else, cache key = `{original_cache_key}|{device_type}`
Then we have two cache key structures. That means:
- For non-bucketed users, the cache key is 2 parts.
- For bucketed users, 3 parts.
Then the surrogate keys become:
For non-bucketed:
- `url:<original_cache_key>`
- `device:<device_type>`
- (no bucket tag? or we set bucket to a special value? We don't have a bucket)
For bucketed:
- `url:<original_cache_key>`
- `device:<device_type>`
- `ab_bucket:<ab_bucket>`
- `url_device_bucket:<original_cache_key>:<device_type>:<ab_bucket>`
Then when we purge by `ab_bucket:control`, we only purge the bucketed ones.
But what about purging by `url`? We want to purge both bucketed and non-bucketed for that URL? We can purge by `url:<original_cache_key>` and that will purge both because both have the `url` tag.
And what about purging by device? We purge both bucketed and non-bucketed for that device.
But then how do we purge the non-bucketed ones? We don't have a bucket tag for them. So we cannot purge by bucket for non-bucketed because they don't have a bucket.
That's acceptable because non-bucketed users are not in a bucket.
But then if we want to purge all content for a device (including non-bucketed), we purge by `device:<device_type>`.
So we have:
For non-bucketed users:
cache key: `{original_cache_key}|{device_type}`
tags: `url:<original_cache_key>`, `device:<device_type>`
For bucketed users:
cache key: `{original_cache_key}|{device_type}|{ab_bucket}`
tags: `url:<original_cache_key>`, `device:<device_type>`, `ab_bucket:<ab_bucket>`, `url_device_bucket:<original_cache_key>:{device_type}:{ab_bucket}`
Then when we purge by `url_device_bucket:<original_cache_key>:mobile:control`, we only purge the bucketed control for mobile.
And when we purge by `url:<original_cache_key>`, we purge both bucketed and non-bucketed for that URL.
And when we purge by `device:mobile`, we purge all mobile (bucketed and non-bucketed) for all URLs.
And when we purge by `ab_bucket:control`, we purge all bucketed control (for all URLs and devices).
This seems to work.
But note: the non-bucketed cache entries do not have the `url_device_bucket` tag, so we cannot purge a specific non-bucketed device and URL? We can purge by `url` and `device`? That would purge all devices for that URL and all URLs for that device? Actually, we have to purge by `url:<original_cache_key>` and then by `device:<device_type>`? That would be two separate purges and would purge:
- All non-bucketed and bucketed for that URL (from the first)
- Then all non-bucketed and bucketed for that device (from the second)
That's too much.
So for non-bucketed, we don't have a way to purge a specific non-bucketed entry (by URL and device) without also purging the bucketed ones? We can purge by `url:<original_cache_key>` and then we have to re-cache the bucketed ones? Not ideal.
Alternatively, we can set a bucket tag for non-bucketed users? We set it to `non-bucketed`? Then we have:
For non-bucketed:
cache key: `{original_cache_key}|{device_type}|non-bucketed`
tags: `url:<original_cache_key>`, `device:<device_type>`, `ab_bucket:non-bucketed`, `url_device_bucket:<original_cache_key>:{device_type}:non-bucketed`
Then we have the same structure for both.
But then we are creating a separate cache for non-bucketed users? That might be acceptable.
And then we can purge:
- By `ab_bucket:non-bucketed` to purge all non-bucketed.
- By `url_device_bucket:<original_cache_key>:mobile:non-bucketed` to purge a specific non-bucketed mobile for a URL.
But then we are caching the same content for bucketed and non-bucketed users separately? Yes, but if the content is the same, we are wasting cache.
We can avoid that by not including the bucket in the cache key for non-bucketed? But then we are back to the problem of not being able to purge a specific non-bucketed entry.
Alternatively, we can include the bucket in the cache key for non-bucketed as `default`? Then:
All users have a bucket (either from cookie or `default`).
Then cache key: `{original_cache_key}|{device_type}|{ab_bucket}`
And tags: same for all.
Then we can purge:
- By `url:<original_cache_key>`: purges all devices and buckets for that URL.
- By `device:<device_type>`: purges all buckets for that device.
- By `ab_bucket:<bucket>`: purges all devices and URLs for that bucket.
- By `url_device_bucket:<original_cache_key>:{device_type}:{bucket}`: purges that exact.
And we don't have the problem of non-bucketed vs bucketed.
But then we are caching the same content for `default` and for a bucketed user if the bucket is `control` and the content is the same? That's a waste, but we are A/B testing so the content might be different.
However, for users without a bucket, we are using `default` and if we later assign them to a bucket, they will get a different cache? That's intended.
So let's do:
Every user has a bucket (from cookie or `default`).
Then we always have three parts in the cache key.
That simplifies everything.
So:
cache key = `{original_cache_key}|{device_type}|{ab_bucket}`
tags:
- `url:<original_cache_key>`
- `device:<device_type>`
- `ab_bucket:<ab_bucket>`
- `url_device_bucket:<original_cache_key>:<device_type>:<ab_bucket>`
Then we can purge by any of these.
And we don't have a special case for non-bucketed.
This is the simplest.
- For 100% of users, we determine the device.
- For A/B bucket, we only assign a bucket (and set the cookie) for a percentage of users? Then the rest get `default`.
That way, we are only segmenting by bucket for the bucketed users, and for the rest we use default.
But then we have to change the cache key for all users? Yes, because we are always including the bucket (even if it's default).
So we are changing the cache key for all users.
We can do:
code
- Deploy the new cache key for 1% of users (by some random hash) and then gradually increase? But then we have two cache keys for the same content? That would double the cache for those users? And we might have inconsistent content.
Given the complexity, maybe we do:
code
- Deploy the new cache key for all users at once, and then we have to accept the cache miss for all URLs until they are re-cached.
We can mitigate by:
code
- Setting a very short TTL on the old cache (if we control it) so that the old cache expires quickly.
- Pre-warming the cache for important URLs by making requests with various device and bucket combinations.
Alternatively, we can do a blue-green deployment:
code
- Create a new cache namespace (if the CDN supports it) and switch over? That might not be possible.
Given the constraints, we might have to do a big bang.
But if we can, we can:
code
- Deploy the new cache key, but for the first week, we set the bucket to `default` for everyone (i.e., ignore the cookie) and then after a week, we start using the cookie.
That way, we are only segmenting by device for the first week? But we are still including the bucket (as `default`) in the cache key. So we are creating a separate cache for `default` bucket.
Then after a week, we start using the cookie. Then we will have:
- For users without the cookie: bucket = `default` (same as before)
- For users with the cookie: bucket = the value.
Then we are gradually introducing the bucket segmentation.
But note: we are already segmenting by device for everyone.
So:
code
Week 1:
- Device segmentation for all.
- Bucket: always `default` (ignore cookie).
Then after a week:
- Device segmentation for all.
- Bucket: from cookie if present, else `default`.
Then we are gradually introducing bucket segmentation.
But during the first week, we are caching with default bucket for everyone. Then when we start using the cookie, we will have:
code
- For a user who gets the cookie, we will cache with their bucket.
- For a user without cookie, we will cache with `default`.
So we are not changing the cache key for non-bucketed users? They were already cached with default? Yes.
And for bucketed users, we are now caching with their bucket, which is a new cache key.
So during the first week, we are building the cache for default bucket for all devices.
Then when we introduce the cookie, we will have cache misses for bucketed users until they request and get cached with their bucket.
That's acceptable.
So rollout:
code
Phase 1 (Week 1):
- Ignore the `ab_bucket` cookie and always set `ab_bucket` to `default`.
- Use the new cache key with device and `default` bucket.
Phase 2 (After Week 1):
- Start using the `ab_bucket` cookie if present, else `default`.
Then we are gradually introducing bucket segmentation.
But note: during Phase 1, we are not using the cookie, so we are not assigning buckets? We are just using default for everyone.
Then in Phase 2, we start assigning buckets? How? We need to set the cookie for users we want to bucket.
We can set the cookie via JavaScript? Or via the origin? That's separate.
So the cache key change is independent of how we assign the bucket.
We can change the cache key to use the bucket (from cookie or default) and then separately we can start setting the cookie for some users.
So:
code
Step 1: Change the cache key to use the bucket (but until we set the cookie, everyone is `default`).
Step 2: Start setting the cookie for a percentage of users (via JavaScript or origin) and then those users will get a different bucket.
Then we are gradually introducing bucket segmentation.
That seems safe.
In Cloudflare, we can set the cache key in a Worker by:
const originalCacheKey = ...? We can use `request.url`? But note: the original cache key might be different (if we have other rules). We have to replicate the existing cache key logic.
Alternatively, we can set the cache key via `caches.default`? Actually, in Cloudflare, we can set the cache key by setting `request` object? Not exactly.
We can use `cacheKey` in the `fetch` event? Actually, we can override the cache key by using `request` and `response` in a Worker? We can use `cacheKey` in the `caches.default.match`? But that's for reading.
To set the cache key for the response, we can set the `cf` object? Not directly.
Alternatively, we can use `Cache API` and set a custom cache key? We can do:
let cacheKey = new Request(originalUrl, request);
// but we want to change the cache key? We can set the `url` of the cacheKey to include the device and bucket? But then the cache key is the full URL? That's not what we want.
Actually, the cache key in Cloudflare is by default the URL (including query string). We can change it by using `cacheKey` in the `fetch` event? Not directly.
We can use `request` and `response` and set the `Cache-Control` header? That doesn't change the cache key.
In Cloudflare, to change the cache key, we typically use a `Page Rule` or `Transform Rules` (now called `Cache Rules`). But in a Worker, we can use the `Cache API` and set a custom cache key by creating a synthetic request with the desired URL? But that would change the URL that the origin sees? We don't want that.
Alternatively, we can use `request` and `response` and set the `cacheKey` in the `cf` object? There is `request.cf` but that's read-only.
So in Cloudflare, we cannot change the cache key in a Worker? We can only change the cache behavior by setting headers (like `Cache-Tag`, `Surrogate-Key`)? But the cache key is still the URL.
So for Cloudflare, we might have to use `Cache Rules` (in the dashboard) to change the cache key? Or we can use `Workers` to set the `Surrogate-Key` and then use `Cache-Tag`? But the cache key remains the URL.
This is a problem.
We might have to use a different approach for Cloudflare: we can use the `URL` as the cache key and then include the device and bucket in the URL? That would change the URL that the origin sees? We don't want that.
Alternatively, we can use the `Cache API` and store the response under a custom key (by creating a synthetic request with the desired key) and then when serving, we look up by that key? But then we have to handle cache misses and fetching from origin ourselves.
That's complex.
Given the complexity, maybe we do:
We set the cache key to be the original URL (without device and bucket) and then we set the `Surrogate-Key` to include device and bucket? Then we can purge by device and bucket? But the cache key is still the original URL, so we are not segmenting by device and bucket in the cache? That's not what we want.
We want the cache key to be different for different devices and buckets so that we store different objects.
So we must change the cache key.
In Cloudflare, we can change the cache key by using `Cache Rules` (which is in the dashboard) and we can set the cache key to be a combination of:
- The URL (without query string? or with)
- A header (like `Device-Type` or `AB-Bucket`) that we set in a Worker?
So we can:
Step 1: In a Worker, we set two headers:
- `X-Device-Type: mobile` (or whatever)
- `X-AB-Bucket: control` (or from cookie)
Step 2: Then in a Cache Rule, we set the cache key to be:
`http.request.url` (or with query string) and `http.request.headers["x-device-type"]` and `http.request.headers["x-ab-bucket"]`
But note: the Worker runs after the cache? Actually, the Worker runs at the edge and we can set the headers and then the cache rule can use those headers.
But the cache rule might run before the Worker? We have to check the order.
Alternatively, we can do everything in a Worker:
We can use the `Cache API` and set a custom cache key? But then we are bypassing the CDN's cache? Not exactly, we are using the CDN's cache but with a custom key.
In Cloudflare Workers, we can do:
let cacheKey = new Request(request.url, request);
// But we want to change the cache key? We can set the `url` of the cacheKey to include the device and bucket? But then the origin request would be to that URL? We don't want that.
We can use the `cacheKey` option in `caches.default.match`? But that's for reading.
We can do:
let cacheKey = new Request(request.url, request);
// then modify the cacheKey's URL to include the device and bucket as query parameters? But then the origin would see those? We don't want that.
Alternatively, we can use the `Cache API` with a custom key that is not a URL? The `Cache` API in Workers uses the request URL as the key? Actually, the `match` method takes a request or a string (URL). So we have to create a request with a URL that represents the cache key.
We can do:
let customUrl = request.url + '|device=' + deviceType + '|bucket=' + bucket;
let cacheKey = new Request(customUrl, request);
Then when we do:
let response = await caches.default.match(cacheKey);
And then when we put:
await caches.default.put(cacheKey, response);
Then the cache key is the customUrl.
But note: the customUrl is not a real URL, so we are creating a synthetic request. And we are not changing the origin request.
This might work.
However, we are using the CDN's cache, but with a custom key that includes device and bucket.
And we can set surrogate keys on the response? We can set the `Surrogate-Key` header on the response? Then we can purge by those keys.
So:
In the Worker:
let deviceType = ...;
let bucket = ...;
let cacheKey = new Request(request.url + '|device=' + deviceType + '|bucket=' + bucket, request);
let response = await caches.default.match(cacheKey);
if (!response) {
response = await fetch(request);
// Set surrogate keys on the response? We can clone and set headers?
let newResponse = response.clone();
let originalCacheKey = request.url; // This might include query string? We want the same as the original cache key? We are using request.url which is the full URL.
// But note: the original cache key might be different if we have other rules? We are using the full URL as the original cache key.
// Set surrogate keys:
let surrogateKeys = [
'url:' + originalCacheKey,
'device:' + deviceType,
'ab_bucket:' + bucket,
'url_device_bucket:' + originalCacheKey + ':' + deviceType + ':' + bucket
];
newResponse.headers.set('Surrogate-Key', surrogateKeys.join(' '));
await caches.default.put(cacheKey, newResponse);
return newResponse;
} else {
return response;
}
But note: we are setting the surrogate keys on the response, but we are caching by the custom cacheKey.
And when we purge by `url:<originalCacheKey>`, we are purging by the tag that we set on the response? But the cache key is custom, and the tag is set on the response.
How does purge by tag work? The CDN (Cloudflare) will look at the `Surrogate-Key` header and purge any cached response that has that tag, regardless of the cache key.
So that should work.
But we are using the `caches.default` which is the CDN's cache? In Cloudflare Workers, `caches.default` is the CDN's cache? Actually, it's the browser's cache? No, in Cloudflare Workers, `caches.default` is the CDN's cache? According to the docs, it's the cache that is shared across all users? Actually, it's the CDN's edge cache.
Yes, `caches.default` in Cloudflare Workers is the CDN's cache.
So this approach should work.
However, we are changing the cache key to a custom string that includes the device and bucket. And we are setting the surrogate keys on the response.
Then we can purge by the surrogate keys.
But note: the `Surrogate-Key` header is set by us in the Worker. And we are setting it only when we fetch from origin? What about when we serve from cache? We are not setting the header on the cached response? We set it when we put into cache, so when we serve from cache, the header is already there? Yes, because we stored the response with the header.
So that should work.
But what about the original cache key? We are using `request.url` as the `originalCacheKey`? That includes the query string? Yes.
And when we purge by `url:<request.url>`, it will purge all the cache entries that have that tag? And we set that tag on every response for that URL? Yes.
So:
- When we purge by `url:https://example.com/page?foo=bar`, we are purging all the cached responses for that URL (with any device and bucket) because they all have the tag `url:https://example.com/page?foo=bar`.
That's what we want.
And we are also setting `device` and `ab_bucket` tags, and the combined tag.
So this seems to work.
But note: we are creating a custom cache key that includes the device and bucket. So we are segmenting the cache by device and bucket.
And we are setting tags for purge.
This approach works for Cloudflare Workers.
For Fastly, we can do something similar in VCL:
In `vcl_recv`:
set req.device_type = ...;
set req.ab_bucket = ...;
# Then we change the cache key by hashing? Or by appending to the URL? We can do:
set req.url = req.url + "|device=" + req.device_type + "|bucket=" + req.ab_bucket;
But then the origin will see the modified URL? We don't want that.
In Fastly, we can use `beresp.hash`? Actually, we can change the cache key without changing the request URL by setting `bereq.hash`? Not exactly.
In Fastly, we can use `sub vcl_hash` to change the hash:
sub vcl_hash {
hash_data(req.url);
hash_data(req.device_type);
hash_data(req.ab_bucket);
}
Then the cache key is the hash of these three.
And we can set the surrogate keys in `vcl_deliver`? Actually, we set them in `vcl_backend_response`:
set beresp.http.Surrogate-Key = "url:" + req.url + " device:" + req.device_type + " ab_bucket:" + req.ab_bucket + " url_device_bucket:" + req.url + ":" + req.device_type + ":" + req.ab_bucket;
But note: `req.url` in `vcl_backend_response` is the backend URL? We might have modified it? We don't want to modify the backend URL.
We want the original URL (without device and bucket) for the `url` tag? So we have to save the original URL.
We can do:
In `vcl_recv`:
set req.original_url = req.url;
Then in `vcl_hash`:
hash_data(req.url); // the original URL? But we are going to modify req.url? We don't want to modify req.url because that would change the backend request.
Actually, in Fastly, we can change the cache key without changing the backend request by using `hash_data` in `vcl_hash` and not changing `req.url`.
So:
In `vcl_recv`:
set req.device_type = ...;
set req.ab_bucket = ...;
set req.original_url = req.url; # save the original
In `vcl_hash`:
hash_data(req.original_url);
hash_data(req.device_type);
hash_data(req.ab_bucket);
Then in `vcl_backend_response`:
set beresp.http.Surrogate-Key = "url:" + req.original_url + " device:" + req.device_type + " ab_bucket:" + req.ab_bucket + " url_device_bucket:" + req.original_url + ":" + req.device_type + ":" + req.ab_bucket;
Then the cache key is the hash of original_url, device_type, and ab_bucket.
And we set the surrogate keys on the response.
Then when we purge by `url:<original_url>`, it will purge all the cached responses that have that tag? Yes.
And we are not changing the backend request URL.
So that works.