We are going to design a CDN edge compute layer with the following components:
- Routing Rules: Define how requests are routed to different backends or cached.
- Cache Keys: How we generate cache keys for objects.
- KV/Object Storage: A distributed key-value store at the edge for caching.
- Canaries: A mechanism for gradual rollouts and A/B testing.
Let's break down each component and design a system that can be implemented on a CDN edge (like Cloudflare Workers, Fastly Compute@Edge, AWS CloudFront with Lambda@Edge, etc.)
However, note that we are designing a conceptual system that can be implemented in such environments.
-
Routing Rules:
- We can define a set of rules that match on request properties (URL, headers, cookies, etc.) and then route to different backends or cache behaviors.
- Example:
- If request URL matches /api/*, route to API backend.
- If request has a specific cookie (e.g., "user_status=beta"), route to beta backend.
- Otherwise, serve from cache or default backend.
-
Cache Keys:
- The cache key is typically a combination of the request URL and some selected request headers (like Accept-Language) and maybe cookies (if needed for personalization).
- We might also include the host (for multi-tenant) and scheme (http vs https).
- We can design a function that takes the request and returns a string (or a structured key) that will be used to look up in the cache.
-
KV/Object Storage:
- This is the cache storage at the edge. We need a distributed key-value store that is highly available and fast.
- In practice, we might use the CDN's built-in cache (which is often a key-value store) or a separate system (like Cloudflare Workers KV, or a Redis cluster) that is accessible from the edge.
- The storage should support:
- Get(key)
- Set(key, value, ttl)
- Delete(key) [optional for cache invalidation]
-
Canaries:
- We want to route a percentage of traffic (or based on a cookie) to a new version of the backend (or new cache configuration) for testing.
- We can implement this in the routing rules by:
- Checking a cookie (or a JWT claim, etc.) that indicates the user is in the canary group.
- Or by hashing something (like user IP or user ID) and taking a modulo to assign a percentage.
- Then, we route that traffic to a different backend or use a different cache key prefix (so we cache separately for canary and stable).
Let's design a high-level flow for a request:
Step 1: Incoming request to the CDN edge.
Step 2: Evaluate routing rules to determine:
- Which backend to use (if any) or if we can serve from cache.
- Whether this request is part of a canary.
Step 3: Generate cache key based on:
- URL (without query parameters? or with? we might want to include some query parameters, but not all. We can have a rule for that.)
- Selected headers (e.g., Accept-Language, User-Agent for device type, etc.)
- For canary: we might want to separate cache for canary and stable, so we might include a "canary version" in the cache key.
Step 4: Look up in the cache (KV storage) using the cache key.
- If found and not expired, return the cached response.
- If not found, forward to the backend (as determined by routing rules) and then cache the response (with appropriate TTL) and return.
However, note that for canary we might want to cache separately so that we don't serve stable cached content to canary users and vice versa.
Let's design the components in more detail:
Routing Rules:
We can have an ordered list of rules. Each rule has:
- Matcher: a function that takes request and returns boolean.
- Action: what to do if matched. Action can be:
- "cache": use the cache (with the generated cache key) and if not in cache, go to backend (and then cache).
- "bypass_cache": don't use cache, always go to backend.
- "redirect": redirect to another URL.
- "rewrite": rewrite the request URL (and then continue processing, maybe with a new cache key?).
We can also have a default rule at the end.
Example rule set:
Rule 1: if request.url starts with "/api/", then action: bypass_cache, backend: "api_backend"
Rule 2: if request has cookie "user_status=beta", then action: cache, but with canary version "beta", backend: "beta_backend"
Rule 3: if request.url matches "/static/*", then action: cache, with long TTL (1 year), backend: "static_backend"
Rule 4: default: action: cache, backend: "default_backend"
But note: the canary version might affect the cache key and also the backend.
We can design the rule to set a "context" that is then used by the cache key generator and the backend selector.
Alternatively, we can have the routing rule directly set:
- which backend to use
- and also a "cache namespace" (or prefix) for canary.
Let's say each rule sets:
- backend: the origin to fetch from (if needed)
- cache_behavior: "cache" or "bypass" or "cache_with_canary" (but we can combine canary into cache_behavior by having a canary flag)
We can have:
rule = {
matcher: (request) => boolean,
action: {
backend: string, // identifier for the backend (could be a hostname or an internal name)
cache: "use" | "bypass" | "canary", // "canary" means use cache but with a canary prefix (so separate cache)
ttl?: number, // optional TTL for cache (if not set, use default)
}
}
But note: the cache key generation might also depend on the rule? For example, for static assets we might want to ignore query parameters.
Alternatively, we can have the cache key generator be a function that takes the request and the rule's context (like the cache_behavior and any canary version) and returns a key.
We can design:
function generateCacheKey(request, ruleContext) {
let key = request.url;
// If rule says to ignore query parameters for cache key, then remove query string?
// We can have a ruleContext option: ignoreQuery: true
if (ruleContext.ignoreQuery) {
key = request.url.split('?')[0];
}
// Add selected headers (like Accept-Language) if needed.
// For canary: if ruleContext.cache === 'canary', then we might prefix the key with "canary:" + ruleContext.canaryVersion?
// But note: the ruleContext might have a canaryVersion (like "v2") and then we want to cache separately for that version.
// Let's assume the ruleContext has:
// cacheNamespace: string (optional) to prefix the cache key. For canary, we set cacheNamespace to the canary version.
if (ruleContext.cacheNamespace) {
key = ruleContext.cacheNamespace + ':' + key;
}
// Also, we might want to include the host? But in a CDN, the host might be the same for multiple tenants?
// Actually, the CDN edge might be serving multiple domains, so we should include the host (or the edge's host?).
// Typically, the cache key includes the scheme, host, and path. But note: the request already has the full URL.
// However, if we are rewriting the request (changing the host) then we must use the original host or the rewritten?
// It depends. But for simplicity, we use the request's host? Actually, if we are routing to a different backend by host, then we might want to include the original host?
// But note: the cache is at the edge, and the same edge might serve multiple domains. So we should include the original host (the one in the request) in the cache key.
// Let's do:
key = request.headers.get('host') + ':' + key;
// Also, we might want to vary by other headers (like Accept-Language) for language-specific content.
// We can have a list of headers to include in the cache key. This list might be per rule? or global?
// Let's assume we have a global list of headers to vary by, but also the rule can override.
// But note: including too many headers in the cache key leads to cache fragmentation.
// Alternatively, we can have the rule specify a list of headers to vary by.
// For simplicity, let's have a global setting: headersToVary = ['accept-language', 'user-agent']? But user-agent might be too many.
// Actually, the CDN might already handle the Vary header from the backend. But if we are generating the cache key at the edge, we have to decide.
// Since we are designing, let's assume we have a function that, given a request and a rule, returns a cache key string.
return key;
}
However, note that the rule might also set a cache TTL. So the rule context might have:
{
backend: string,
cache: 'use' | 'bypass' | 'canary',
ttl: number, // in seconds
cacheNamespace: string, // for canary, set to the canary version, otherwise empty
ignoreQuery: boolean, // if true, remove query string from URL for cache key
varyHeaders: array of header names (optional, overrides global list)
}
And then we can have a global list of headers to vary by (if the rule doesn't specify).
- KV/Object Storage:
We need a distributed cache that is accessible from the edge. The edge function will do:
let cacheKey = generateCacheKey(request, ruleContext);
let cachedResponse = await kv.get(cacheKey);
if (cachedResponse) {
return cachedResponse;
} else {
let response = await fetch(backendUrl, request); // we might need to modify the request (like change host) to point to the backend.
// We might want to set the response in cache only if it's cacheable (status 200, etc.) and with the TTL from ruleContext.
if (ruleContext.cache !== 'bypass' && response.status === 200) {
let ttl = ruleContext.ttl || defaultTtl;
await kv.set(cacheKey, response, ttl);
}
return response;
}
But note: the response might have a Cache-Control header that overrides? We can decide to respect the origin's Cache-Control or use the rule's TTL.
Also, we might want to cache only certain types of responses (by content-type). We can add that in the rule.
- Canaries:
We can have a canary configuration that maps a canary version (like "v2") to a backend and a set of routing rules that apply to that canary.
Alternatively, we can have a rule that checks for a cookie (or a header) and then sets the ruleContext.canaryVersion and then uses that in the cache key and backend.
Example:
We have two backends:
stable_backend: https://stable.example.com
beta_backend: https://beta.example.com
Rule for canary by cookie:
if request.cookies.get('canary_version') == 'v2', then:
ruleContext = {
backend: 'beta_backend',
cache: 'canary',
cacheNamespace: 'v2', // so cache keys are prefixed with 'v2:'
ttl: 60, // maybe shorter TTL for canary
... other settings
}
Then, when generating the cache key, we prefix with 'v2:' so that stable and beta are cached separately.
We can also have a rule that does percentage-based canary:
if (hash(request.ip) % 100 < 5) { // 5% of traffic
ruleContext = {
backend: 'beta_backend',
cache: 'canary',
cacheNamespace: 'v2',
ttl: 60
}
}
But note: the request.ip might be the client IP at the edge? We can get that from the request.
However, note that the same user might get different backends on different requests if we use IP hash? We might want to use a cookie to stick the user to a version.
So, we can combine: first check for a cookie, if not set, then do percentage-based and set a cookie for the user.
But setting a cookie at the edge is possible (by adding a Set-Cookie header in the response). However, we are in a compute layer that runs on every request.
We can do:
let canaryCookie = request.cookies.get('canary_version');
if (canaryCookie) {
// use the version in the cookie
if (canaryCookie == 'v2') {
// route to beta
} else {
// route to stable (or other versions)
}
} else {
// assign by percentage
let assignedVersion = hash(request.ip) % 100 < 5 ? 'v2' : 'stable';
// We want to set a cookie so that the user sticks to that version.
// But note: we are in the request phase, we can modify the response to set a cookie.
// So we set a flag that we need to set a cookie in the response.
ruleContext.setCanaryCookie = assignedVersion;
}
Then, after we get the response from the backend, if ruleContext.setCanaryCookie is set, we add a Set-Cookie header.
But note: we are caching the response. If we set a cookie in the response, then the cached response will have that Set-Cookie?
That might be okay if we want every user in the canary to get the same cookie? Actually, we want to set the cookie only for the user who was assigned.
So, we cannot cache the response with the Set-Cookie header because then every user would get the same cookie.
Therefore, we should not cache the response if we are setting a cookie? Or we should remove the Set-Cookie header before caching?
Alternatively, we can set the cookie in the edge without affecting the cache? Actually, the cache key is generated from the request, and the cookie is in the request. So:
User A (no cookie) -> assigned to v2 -> response with Set-Cookie: canary_version=v2 -> cached with key (without cookie? but we include cookie in cache key?).
Then User B (with canary_version=v2) -> cache key includes the cookie? so they get the same cached response (with Set-Cookie set to v2? but that's the same).
But note: the Set-Cookie header is in the response. When we cache the response, we cache the entire response including headers.
Then, when User C (without cookie) comes and gets the same cache key (because we don't include the cookie in the cache key? or do we?).
We must decide: if the cache key includes the cookie, then User A (without cookie) and User B (with cookie) would have different cache keys?
But we want User A to be assigned and then get a cookie, and then on the next request they have the cookie and should get the same backend.
So, we don't want to include the cookie in the cache key? Because then the same URL without cookie and with cookie would be different cache entries?
But we are using the cookie to determine the backend, so we want the same cache for all users in the same canary group?
Actually, we want:
User without cookie -> assigned to v2 (by percentage) -> then we set a cookie and return the response from v2 backend.
Then, on the next request, the user has the cookie and we route to v2 again, and we want to use the same cache as the previous request?
But note: the previous request was without cookie and the current is with cookie. If we don't include the cookie in the cache key, then the cache key for the same URL without cookie and with cookie would be the same?
However, the cookie is not in the URL. So if we don't vary by cookie, then the cache key for the same URL (without considering cookie) would be the same.
But wait: the rule context for the first request (without cookie) used the percentage-based assignment and set cacheNamespace to 'v2'.
The second request (with cookie) also sets cacheNamespace to 'v2'. So the cache key would be:
first request: host + url (without query? as per rule) + (maybe some headers) -> prefixed with 'v2:'
second request: same, because the cookie is not in the cache key?
But we are not including the cookie in the cache key, so yes, same cache key.
However, the first request set a Set-Cookie in the response. That Set-Cookie is cached? Then when the second request (with cookie) comes, we return the cached response which has Set-Cookie: canary_version=v2?
That would reset the cookie? But the user already has it. It's okay to set it again? But we don't want to set it on every response?
Actually, we only want to set the cookie on the first request (when the user is assigned). So we should not cache the Set-Cookie header?
We have two options:
1. Do not cache responses that have Set-Cookie (or at least remove Set-Cookie from the cached response).
2. Or, do not include the Set-Cookie in the cache key and then when we serve from cache, we don't add the Set-Cookie? But then the user who was assigned might not get the cookie?
Actually, the user who was assigned already has the cookie from the first response. So we don't need to set it again. So we can remove the Set-Cookie header before caching.
But note: the first request (without cookie) gets the response from the backend (which might not set the cookie) and then we set the cookie at the edge. So the cached response would have the Set-Cookie we set?
We are setting the cookie in the edge, so the cached response would have that Set-Cookie? Then when we serve from cache, every user in the same canary group would get the Set-Cookie header?
That's not what we want. We only want to set the cookie once (when the user is assigned). So we should:
- For the first request (without cookie): we assign and set the cookie in the response, but we do not cache this response with the Set-Cookie?
Or we cache without the Set-Cookie?
Alternatively, we can separate the assignment and the response:
Step 1: Check for cookie. If not present, assign a version and set a cookie in the response (but don't cache this response? because the next request will have the cookie and we want to cache without the Set-Cookie).
Step 2: Then, using the version (from cookie or assignment), we route to the appropriate backend and cache.
So we can do:
let canaryVersion = request.cookies.get('canary_version');
if (!canaryVersion) {
// assign and set cookie
canaryVersion = assignCanaryVersion(request);
// We will set a cookie in the response later, but note: we don't want to cache this response with the Set-Cookie.
// So we set a flag that we are in the assignment phase and we should not cache.
ruleContext.bypassCache = true; // because we don't want to cache the response that sets the cookie.
ruleContext.setCanaryCookie = canaryVersion;
}
// Then, based on canaryVersion, set the backend and cache namespace.
Then, in the caching logic:
if (ruleContext.bypassCache) {
// don't cache, just fetch and then set the cookie in the response.
} else {
// use cache as usual.
}
But note: the assignment request (without cookie) will bypass cache and go to the backend? But we want to show the same content as the canary backend?
Actually, we want the assignment request to be handled by the canary backend (if assigned to canary) and then set the cookie. So we should route the assignment request to the canary backend?
Yes. So:
if (!canaryVersion) {
canaryVersion = assignCanaryVersion(request);
ruleContext.setCanaryCookie = canaryVersion;
// Now, set the ruleContext based on canaryVersion (backend, cacheNamespace, etc.)
// But note: we are in the same rule? We might have multiple rules? Actually, the assignment is part of the rule evaluation.
Alternatively, we can have a separate rule for assignment? But it's easier to handle in one rule.
We can design the rule to have an "assignment" function if the cookie is missing.
Let's design a rule type for canary:
rule = {
matcher: (request) => boolean, // e.g., matches all requests? or a specific path?
canary: {
assignment: (request) => string, // returns canary version (like 'v2') or null if not assigned (but if the rule matches, we want to assign?).
backends: {
'v2': { backend: 'beta_backend', cacheNamespace: 'v2', ttl: 60 },
'stable': { backend: 'stable_backend', cacheNamespace: 'stable', ttl: 3600 }
},
cookieName: 'canary_version'
}
}
Then, when the rule matches:
let cookie = request.cookies.get(rule.canary.cookieName);
let canaryVersion = cookie;
if (!canaryVersion) {
canaryVersion = rule.canary.assignment(request);
if (canaryVersion) {
ruleContext.setCanaryCookie = { name: rule.canary.cookieName, value: canaryVersion };
}
}
if (canaryVersion && rule.canary.backends[canaryVersion]) {
ruleContext = rule.canary.backends[canaryVersion];
} else {
// if no canary version or unknown, then maybe use stable? or default?
ruleContext = rule.canary.backends['stable'];
}
But note: what if the rule doesn't match? Then we don't do canary.
Also, we can have multiple canary rules? Maybe for different paths?
Alternatively, we can have a global canary configuration that applies to all requests?
Given the complexity, let's stick to one canary rule that applies to a set of paths (like the entire site) and then other rules for API, etc.
5. Putting it all together:
We have a list of routing rules. We evaluate each rule in order until one matches.
Each rule can be of different types? Actually, we can have a unified rule structure that includes:
rule = {
matcher: function(request): boolean,
action: {
type: 'proxy' | 'redirect' | 'rewrite',
... depending on type
}
}
But we also want to include canary assignment? Maybe we can have:
rule = {
matcher: function(request): boolean,
action: {
type: 'proxy', // meaning forward to a backend and cache (or bypass)
backend: string, // or a function that returns a backend based on request?
cache: 'use' | 'bypass' | 'canary?',
ttl: number,
ignoreQuery: boolean,
varyHeaders: array,
canary?: { // optional canary config
assignment: function(request): string, // returns canary version or null
cookieName: string,
backends: { [version]: { backend: string, cacheNamespace: string, ttl: number } }
}
}
}
Then, when we match a rule, we evaluate:
let context = {};
if (rule.action.canary) {
let cookie = request.cookies.get(rule.action.canary.cookieName);
let canaryVersion = cookie;
if (!canaryVersion) {
canaryVersion = rule.action.canary.assignment(request);
if (canaryVersion) {
context.setCanaryCookie = { name: rule.action.canary.cookieName, value: canaryVersion };
}
}
if (canaryVersion && rule.action.canary.backends[canaryVersion]) {
Object.assign(context, rule.action.canary.backends[canaryVersion]);
} else {
// fallback to stable? or to the rule's default?
// Maybe the rule has a default backend? Or we can have a 'stable' version in the backends.
// Let's assume the backends has a 'stable' version.
Object.assign(context, rule.action.canary.backends['stable']);
}
} else {
// non-canary rule
context.backend = rule.action.backend;
context.cache = rule.action.cache;
context.ttl = rule.action.ttl;
context.ignoreQuery = rule.action.ignoreQuery;
context.varyHeaders = rule.action.varyHeaders;
}
// Then, we also have the rule's action.type? Actually, we are only doing proxy? But we can have redirect and rewrite too.
// If action.type is 'proxy', then we do the caching and backend fetching as above.
// If action.type is 'redirect', then we return a 302 with Location header.
// If action.type is 'rewrite', then we rewrite the request URL and then continue to next rule? Or we treat it as a new request?
// Actually, rewrite might change the URL and then we should re-evaluate the rules? Or we just set the request.url and then continue with the same rule?
// Typically, rewrite changes the request and then we might match a different rule? So we should restart the rule evaluation?
// But note: we are in an edge function, we can modify the request and then re-run the rule engine?
// Alternatively, we can have rewrite as a final action that changes the request and then we do the same proxy/cache logic?
// Let's keep it simple: we only have 'proxy' and 'redirect'. Rewrite can be done by the proxy by changing the backend?
// Actually, rewrite is changing the request URL (path) and then we might want to cache the rewritten URL?
// We can support rewrite by having:
rule.action.type = 'rewrite'
rule.action.to: string // regex replacement? or a fixed string?
// Then, we rewrite the request.url and then continue to the next rule?
// But note: we might have multiple rewrites? So we can do:
for each rule:
if rule.matcher(request) and rule.action.type == 'rewrite':
request.url = rewrite(request.url, rule.action.to);
// and continue to next rule?
if rule.matcher(request) and rule.action.type == 'proxy':
// then do the proxy with the current request (which might have been rewritten)
// So we can have a loop:
let currentRequest = request;
for (rule of rules) {
if (rule.matcher(currentRequest)) {
if (rule.action.type == 'rewrite') {
currentRequest.url = applyRewrite(currentRequest.url, rule.action.to);
continue; // go to next rule with the rewritten request
} else if (rule.action.type == 'proxy') {
// evaluate canary and set context as above, then do proxy with currentRequest and context.
break;
} else if (rule.action.type == 'redirect') {
return response.redirect(rule.action.location, rule.action.status);
}
}
}
// if no rule matched, then we can have a default rule? or return 404?
// But note: the rewrite might change the request so that it matches a later rule. So we need to re-evaluate the rules after a rewrite?
// Actually, we are in a loop and we continue to the next rule with the rewritten request. So if the rewritten request matches a later rule, that rule will be applied.
// However, what if we want to rewrite and then proxy in the same rule? Then we can have:
rule.action.type = 'rewrite_and_proxy'
// But let's not complicate.
6. Implementation:
We'll assume we are writing a function that takes a request and returns a response.
Steps:
let currentRequest = request;
for (rule of routingRules) {
if (rule.matcher(currentRequest)) {
if (rule.action.type === 'rewrite') {
currentRequest.url = rewrite(currentRequest.url, rule.action.to);
continue;
} else if (rule.action.type === 'redirect') {
return Response.redirect(rule.action.location, rule.action.status);
} else if (rule.action.type === 'proxy') {
let context = evaluateRuleContext(rule, currentRequest);
return handleProxy(currentRequest, context);
}
}
}
// No rule matched. We can have a default rule? Or return 404.
The evaluateRuleContext function will handle canary assignment and set the backend, cache settings, etc.
The handleProxy function will:
let cacheKey = generateCacheKey(currentRequest, context);
let cached = await kv.get(cacheKey);
if (cached) {
// If we are in a canary assignment and need to set a cookie? But note: the cached response was set without the Set-Cookie?
// Actually, we set the cookie only in the assignment request (which bypasses cache). So cached responses don't have the Set-Cookie.
// But what if the backend sets a cookie? We are caching that? Then we would serve the backend's cookie to everyone?
// We might want to remove Set-Cookie from cached responses? Or we can have a rule that says: if the response has Set-Cookie, don't cache?
// That's a more advanced topic.
// For now, we return the cached response.
return cached;
} else {
// Construct the backend URL:
// context.backend might be a hostname (like 'stable.example.com') and we use the currentRequest's path?
// But note: we might have rewritten the request. So we use currentRequest.url? But we want to change the host.
// We can do:
let url = new URL(currentRequest.url);
url.hostname = context.backend; // if backend is just a hostname? or it could be a full URL?
// Actually, the backend might be a full URL? We can have:
// context.backend: string (the host and protocol, e.g., 'https://stable.example.com')
// Then:
let backendUrl = context.backend + url.pathname + url.search + url.hash;
// But note: we might want to forward the original request's method, headers, body, etc.
let fetchRequest = new Request(backendUrl, {
method: currentRequest.method,
headers: currentRequest.headers,
body: currentRequest.body,
redirect: 'manual' // we handle redirects? or let fetch handle?
});
let response = await fetch(fetchRequest);
// Check if we should cache this response.
if (context.cache !== 'bypass' && response.status === 200) {
// We might want to check response headers? e.g., Cache-Control?
// Let's assume we use the rule's ttl.
let ttl = context.ttl;
// But note: the response might have a Cache-Control header with max-age? We can override by rule?
// We can decide: rule's ttl takes precedence? or we take the minimum?
// For simplicity, we use rule's ttl.
// Also, we might want to remove headers that are not cache-friendly? Like Set-Cookie?
// We can remove Set-Cookie from the response before caching?
// But if the backend sets a cookie for personalization, then we are breaking that by caching?
// So we might not want to cache responses with Set-Cookie?
// Let's check: if response has Set-Cookie, then we don't cache?
if (response.headers.has('Set-Cookie')) {
// don't cache
} else {
// We need to clone the response because we are going to return it and also cache it.
let responseToCache = response.clone();
await kv.set(cacheKey, responseToCache, ttl);
}
}
// Now, if we need to set a canary cookie, we add it to the response.
if (context.setCanaryCookie) {
response.headers.append('Set-Cookie', `${context.setCanaryCookie.name}=${context.setCanaryCookie.value}; Path=/; HttpOnly`);
}
return response;
}
However, note: the above fetch does not forward the original request's headers? We are passing currentRequest.headers, which is the original request's headers?
But we might have rewritten the request? Then the headers are still the original?
Actually, the rewrite only changes the URL. So the headers are the same.
But what about the Host header? When we fetch to the backend, we want the Host header to be the backend's host?
The fetch API will set the Host header to the host of the backendUrl by default?
However, if we want to forward the original Host header (for the CDN) then we don't change it? But the backend might require the Host header to be its own.
So we might want to set the Host header to the backend's host?
We can do:
fetchRequest.headers.set('Host', new URL(backendUrl).hostname);
But note: the original request might have a Host header (the CDN's host). We are changing it to the backend's host.
That's typical for a reverse proxy.
- Edge Cases:
-
We are not handling request bodies for methods like POST. We are only caching GET? Actually, we should only cache GET and HEAD?
We can check the request method and only cache if it's GET or HEAD.
-
We are not handling query parameters correctly: we might want to ignore some query parameters? The rule has ignoreQuery.
-
We are not handling the Vary header from the backend. If the backend sets Vary, then we should include those headers in the cache key?
But we are generating the cache key at the edge. We can either:
a) Ignore Vary and rely on our own varyHeaders setting in the rule.
b) Parse the Vary header from the backend response and then for subsequent requests, include those headers in the cache key?
This is complex because the first response we get from the backend might have Vary, and then we cache it. But the cache key we used didn't include those headers?
Then we might serve the wrong cached response to a request that has different headers (that the backend varies on).
So we have two options:
-
When we get a response from the backend, we look at the Vary header and then adjust the cache key for that response? But then we already stored it with the old key.
-
We don't rely on the backend's Vary and we set our own varyHeaders in the rule. This is safer because we control the cache key.
Given the complexity, let's assume we set our own varyHeaders in the rule and ignore the backend's Vary.
-
We are not handling cache invalidation. We only have TTL. We might need a way to purge by URL or by tag? That would require an admin API.
-
We are not handling different cache layers (browser cache vs edge cache). We are only doing edge cache.
- Summary:
We have designed:
- A routing rule engine that can rewrite, redirect, and proxy.
- A canary assignment mechanism that sets a cookie and uses a separate cache namespace and backend.
- A cache key generator that uses the rule's context (including canary version) and request properties.
- A simple KV storage interface for caching.
This design can be implemented in an edge compute environment like Cloudflare Workers, but note that we are using a hypothetical KV storage that is accessible from the edge.
In practice, on Cloudflare Workers we would use the Cache API (which is built-in) and we would use the environment's cache (which is per-zone and shared).
But note: the Cache API in Cloudflare Workers does not allow arbitrary cache keys? It uses the request URL and some headers?
Actually, the Cache API in Cloudflare Workers uses the request's URL and method and some headers (like Vary) to create the cache key?
We might need to use the Cache API with a custom cache key? We can use caches.default.put(request, response) and the request is the cache key?
But the request for the cache key should be the same as the request we are going to make to the backend?
Alternatively, we can use a custom cache key by using a Request object with the desired URL and headers?
Example:
let cacheKeyRequest = new Request(cacheKey, { method: 'GET' }); // but we are using GET for cache?
let cachedResponse = await caches.default.match(cacheKeyRequest);
But note: the Cache API might not use the entire request object as the key? It uses the URL, method, and headers?
So we can construct a Request object with the desired cache key (which is a URL? but our cache key is a string that might not be a valid URL).
We can encode the cache key into a URL? For example, use a custom scheme?
Alternatively, we can use a separate KV store (like Workers KV) that allows arbitrary keys? But Workers KV is not a cache (it's a key-value store with eventual consistency) and it's not designed for high-throughput caching?
Cloudflare's Cache API is designed for caching and uses a LRU and is shared across workers?
Given the constraints, we might have to adapt to the platform.
But since this is a design, we assume we have a key-value cache that we can use with arbitrary keys.
- Example:
Let's say we have two rules:
Rule 1:
matcher: request.url.startsWith('/api/')
action: { type: 'proxy', backend: 'api.example.com', cache: 'bypass', ttl: 0 }
Rule 2:
matcher: request.url.startsWith('/static/')
action: { type: 'proxy', backend: 'static.example.com', cache: 'use', ttl: 31536000, ignoreQuery: true, varyHeaders: [] }
Rule 3:
matcher: always matches (for the rest)
action: {
type: 'proxy',
canary: {
assignment: (request) => Math.random() < 0.05 ? 'v2' : 'stable',
cookieName: 'canary_version',
backends: {
'v2': { backend: 'beta.example.com', cacheNamespace: 'v2', ttl: 60 },
'stable': { backend: 'www.example.com', cacheNamespace: 'stable', ttl: 3600 }
}
}
}
Then, for a request to '/static/image.png':
matches rule 2:
context = { backend: 'static.example.com', cache: 'use', ttl: 31536000, ignoreQuery: true, varyHeaders: [] }
cacheKey = host + '/static/image.png' (without query) -> then we look up in cache.
For a request to '/':
matches rule 3:
no cookie -> assign by random: 5% chance of 'v2'
if assigned 'v2', then context = { backend: 'beta.example.com', cacheNamespace: 'v2', ttl: 60 }
cacheKey = host + '/' -> but prefixed with 'v2:' -> 'v2:host/'
Then we cache the response from beta.example.com under that key.
For the same user (with cookie 'canary_version=v2'):
matches rule 3:
cookie = 'v2'
context = { backend: 'beta.example.com', cacheNamespace: 'v2', ttl: 60 }
cacheKey = 'v2:host/' -> same as above.
So the canary users share the cache.
- Limitations:
-
We are not handling POST, PUT, etc. for caching? We only cache GET and HEAD? We should check the method.
-
We are not handling the case where the backend returns a redirect? We are just returning the response. The fetch will follow redirects? We set redirect: 'manual'?
Actually, we set redirect: 'manual'? We didn't set it, so by default fetch follows redirects? We might want to handle redirects?
-
We are not handling error responses (like 404, 500) in cache? We might not want to cache them? But we can if we want.
-
We are not handling the case where the backend sets a cookie and we want to bypass cache? We can add a rule that bypasses cache if the response has Set-Cookie?
Given the complexity, we should keep the design simple and extend as needed.
This is a basic design. In practice, we would need to adjust for the specific edge platform's APIs and constraints.
I'll design a comprehensive CDN edge compute layer with modern patterns. This architecture uses a hierarchical approach with edge nodes, regional caches, and origin integration.
Architecture Overview
Client Request → Edge Node (Compute@Edge) → Regional Cache → Origin
↑ ↑
Routing Rules KV Storage
↓ ↓
Canary Control Cache Keys
1. Routing Rules Engine
Rule Matching Priority (highest to lowest):
# Rule format:
- priority: 100
match:
host: ["api.example.com"]
path_pattern: "^/v1/.*"
header:
"x-api-key": ".*" # regex match
cookie:
"user_tier": "premium"
action:
type: "proxy"
backend: "api-primary"
cache_zone: "api-zone"
ttl: 300 # 5 minutes
- priority: 90
match:
path_extension: [".jpg", ".png", ".css", ".js"]
action:
type: "static_asset"
cache_zone: "static-zone"
ttl: 31536000 # 1 year
edge_cache_control: true
- priority: 80
match:
country: ["US", "CA"]
device_type: ["mobile"]
action:
type: "dynamic"
backend: "mobile-origin"
cache_zone: "dynamic-mobile"
ttl: 60
- priority: 1 # fallback
match: {}
action:
type: "proxy"
backend: "origin-default"
cache_zone: "default-zone"
ttl: 3600
Rule Features:
- Multi-condition matching: Host, path, headers, cookies, geo, device, query params
- Priority-based evaluation: First match wins
- Action types:
proxy: Forward to backend with caching
redirect: 301/302 redirects
rewrite: URL rewriting (e.g., /old/(.*) → /new/$1)
error_response: Custom error pages
ab_test: Define canary cohorts
- Cache zone inheritance: Rules can reference named cache configurations
2. Cache Key Generation Strategy
Primary Key Components:
function generateCacheKey(request, ruleContext) {
const components = [
// 1. Normalized URL (scheme + host + path)
`${request.scheme}://${request.host}${normalizePath(request.url.pathname)}`,
// 2. Query string (configurable: all/whitelist/blacklist)
ruleContext.query_handling === 'ignore' ? '' :
ruleContext.query_handling === 'whitelist' ?
sortQueryParams(filterQueryParams(request.url.search, ruleContext.query_whitelist)) :
request.url.search,
// 3. Vary headers (Accept-Language, User-Agent, etc.)
...ruleContext.vary_headers.map(h =>
`${h}:${request.headers.get(h) || ''}`
),
// 4. Canary version token (if applicable)
ruleContext.canary_version ? `canary:v${ruleContext.canary_version}` : '',
// 5. Device/geography context (optional)
ruleContext.include_geo ? `geo:${request.geo.country}` : '',
// 6. Authorization scope (for personalized content)
request.headers.get('authorization') ?
`auth:${hashString(extractToken(request.headers.get('authorization')))}` : ''
].filter(Boolean);
return hash256(components.join('|'));
}
Key Features:
- Configurable query handling:
ignore: /product?id=1 = /product?id=2
whitelist: Only specified params matter
blacklist: Ignore tracking params (utm_*, fbclid)
- Header-based variance: Language, device, etc.
- Canary segregation: Different versions never share cache
- Personalization support: Hash auth tokens for per-user cache
3. Edge KV / Object Storage
Storage Hierarchy:
Edge Node LRU (1-5GB) → Regional Edge Cache (100GB-1TB) → Origin KV → S3/Backend
↑ ↑
Sub-second 5-50ms latency
KV Implementation Options:
Option A: Rust/WASM Edge Runtime (Fastly, Cloudflare Workers)
// Fastly Compute@Edge example
struct EdgeStore {
kv: fastly::KVStore,
lru: LruCache<String, Response>,
}
impl EdgeStore {
async fn get(&self, key: &str) -> Option<Response> {
// 1. Check local LRU
if let Some(resp) = self.lru.get(key) {
return Some(resp.clone());
}
// 2. Check regional KV (read-through)
if let Ok(Some(bytes)) = self.kv.get(key).await {
let resp = deserialize(bytes);
self.lru.put(key.to_string(), resp.clone());
return Some(resp);
}
None
}
}
Option B: JavaScript/TypeScript (Cloudflare Workers, AWS Lambda@Edge)
class EdgeObjectStore {
private localCache: Map<string, CacheEntry> = new Map();
private readonly KV_NAMESPACE: KVNamespace;
private readonly REGIONAL_KV_URL: string;
async get(key: string): Promise<Response | null> {
// 1. Local micro-cache (1MB limit)
const local = this.localCache.get(key);
if (local && !this.isExpired(local)) {
return local.response;
}
// 2. Regional KV (cloud storage)
const regionalData = await this.KV_NAMESPACE.get(key, { type: 'json' });
if (regionalData) {
const response = new Response(regionalData.body, regionalData.options);
this.localCache.set(key, {
response,
expires: Date.now() + regionalData.ttl * 1000
});
return response;
}
return null;
}
}
Storage Tiers & TTL Strategies:
| Asset Type | Edge LRU | Regional KV | Origin | TTL Policy |
|---|
| HTML | ❌ No | ✅ Yes | ✅ Yes | 5min (stale-while-revalidate) |
| CSS/JS | ✅ Yes | ✅ Yes | ✅ Yes | 1 year (immutable hash) |
| Images | ✅ Yes | ✅ Yes | ✅ Yes | 1 year (CDN cache) |
| API JSON | ❌ No | ✅ Yes | ✅ Yes | 30s (surrogate-key purges) |
| Personalized | ❌ No | ❌ No | ✅ Yes | 0 (bypass cache) |
Cache Invalidation API:
// Purge by cache key
POST /cache/purge
{
"keys": ["https://example.com/product/123", "https://example.com/api/v1/..."],
"zone": "production",
"grace_period": 30 // seconds
}
// Purge by surrogate key (tag-based)
POST /cache/purge/tag
{
"tags": ["product:123", "campaign:summer2024"],
"invalidate_children": true
}
// Canary promotion (atomic switch)
POST /canary/promote
{
"version": "v2.1.0",
"from_percentage": 5,
"to_percentage": 100,
"rollback_version": "v2.0.3"
}
4. Canary Deployment System
Canary Configuration:
canary_configs:
- name: "new-checkout-flow"
enabled: true
traffic_split:
stable: 95
v2.1: 5
targeting:
- cookie: "checkout_experiment=v2"
- header: "x-ab-test: new_checkout"
- hash_user_id: 5% # Consistent hashing
metrics:
success_criteria:
- "error_rate < 1%"
- "p95_latency < 500ms"
- "conversion_rate > baseline + 2%"
auto_rollback: true
evaluation_period: 300 # seconds
- name: "image-optimization"
enabled: false # paused
traffic_split:
stable: 100
Edge Implementation:
class CanaryManager {
private configs: CanaryConfig[];
private redis: RedisClient; // For consistent hashing state
async route(request: Request): Promise<Backend> {
const userHash = this.hashUser(request);
for (const config of this.configs) {
if (!config.enabled) continue;
if (this.matchesTargeting(config, request, userHash)) {
const version = this.selectVersion(config, userHash);
return {
backend: config.backends[version],
cache_namespace: `canary:${config.name}:${version}`,
headers: {
'x-canary-version': version,
'x-canary-name': config.name
}
};
}
}
return this.defaultBackend();
}
private matchesTargeting(config: CanaryConfig, request: Request, userHash: number): boolean {
// Cookie targeting
if (config.targeting.cookie) {
const [name, value] = config.targeting.cookie.split('=');
if (request.cookies.get(name) === value) return true;
}
// Header targeting
if (config.targeting.header) {
const [header, expected] = config.targeting.header.split(':');
if (request.headers.get(header.trim())?.includes(expected.trim())) {
return true;
}
}
// Percentage-based (consistent hash)
if (config.targeting.hash_user_id) {
const percentage = config.targeting.hash_user_id;
return (userHash % 100) < percentage;
}
return false;
}
}
Metrics Collection:
// Attach to all canary responses
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const start = Date.now();
const response = await handleRequestWithCanary(request);
const duration = Date.now() - start;
// Emit metrics (to Kafka/StatsD/OTel)
const canaryInfo = getCanaryInfo(request);
if (canaryInfo) {
emitMetric('canary.request', {
version: canaryInfo.version,
name: canaryInfo.name,
status: response.status,
duration_ms: duration,
content_type: response.headers.get('content-type')
});
}
return response;
}
5. Complete Request Flow
sequenceDiagram
participant C as Client
participant E as Edge Node
participant KV as KV Storage
participant R as Regional Cache
participant O as Origin
C->>E: GET /product/123?utm=foo
Note over E: Routing Rules:
- Matches product:* pattern
- Cache zone: products
- Vary: Accept-Language
E->>E: Generate cache key:
"https://example.com/product/123|en-US"
E->>KV: GET cacheKey
alt Cache HIT
KV-->>E: Cached Response
E->>C: Return cached (200)
else Cache MISS
E->>R: Check regional cache
alt Regional HIT
R-->>E: Response
E->>KV: SET cacheKey (async)
E->>C: Return response
else Regional MISS
E->>O: Forward request (with canary headers if applicable)
O-->>E: Response (200)
E->>KV: SET cacheKey with TTL
E->>C: Return response
end
end
6. Implementation Examples
Cloudflare Workers (JavaScript):
// worker.js
export default {
async fetch(request, env) {
// 1. Parse request
const url = new URL(request.url);
// 2. Apply routing rules
const rule = matchRules(request, env.ROUTING_RULES);
const context = applyRule(rule, request);
// 3. Check canary
const canary = await checkCanary(request, env.CANARY_CONFIG);
const namespace = canary ? `canary:${canary.name}:${canary.version}` : '';
// 4. Generate cache key
const cacheKey = generateCacheKey(request, {
...context,
canary_version: canary?.version,
cache_namespace: namespace
});
// 5. Try cache
const cache = env.CACHE_NAMESPACE;
const cached = await cache.get(cacheKey, 'json');
if (cached) {
const response = new Response(cached.body, cached.options);
if (canary) response.headers.set('x-canary-version', canary.version);
return response;
}
// 6. Fetch from origin
const originUrl = buildOriginUrl(request, rule.backend);
const originRequest = new Request(originUrl, request);
const originResponse = await fetch(originRequest);
// 7. Cache if applicable
if (shouldCache(originResponse, rule)) {
const ttl = getTTL(originResponse, rule.ttl);
await cache.put(cacheKey, originResponse.clone().json(), { expirationTtl: ttl });
}
// 8. Add canary headers
const response = new Response(originResponse.body, originResponse);
if (canary) {
response.headers.set('x-canary-version', canary.version);
response.headers.set('x-canary-name', canary.name);
}
return response;
}
};
Fastly Compute@Edge (Rust):
// main.rs
fastly_compute::start!(|ctx| async {
let req = ctx.req.as_ref().clone();
// 1. Route
let route = match router::route(&req) {
Some(r) => r,
None => return ctx.send(req),
};
// 2. Canary check
let canary = canary::check(&req, &route).await;
let cache_namespace = if let Some(c) = &canary {
format!("canary-{}-{}", route.id, c.version)
} else {
route.cache_zone.clone()
};
// 3. Cache key
let cache_key = cache::generate_key(&req, &route, canary.as_ref());
// 4. Cache lookup
if let Some(resp) = cache::lookup(&ctx, &cache_key, &route).await {
return ctx.send(resp);
}
// 5. Origin fetch
let mut backend = ctx.backend(&route.backend).unwrap();
let mut origin_req = req.clone();
origin_req.set_url(&route.rewrite_url(&req.url().path()));
let origin_resp = backend.send_async(origin_req).await?;
// 6. Cache store
if cache::should_cache(&origin_resp, &route) {
cache::store(&ctx, &cache_key, origin_resp.clone(), &route).await;
}
// 7. Add headers
let mut final_resp = origin_resp;
if let Some(c) = canary {
final_resp.set_header("x-canary-version", &c.version);
final_resp.set_header("x-canary-cohort", &c.cohort);
}
ctx.send(final_resp)
});
7. Monitoring & Observability
Metrics to Track:
{
"edge": {
"requests_total": "counter",
"cache_hit_ratio": "gauge",
"cache_hits": "counter",
"cache_misses": "counter",
"response_time_p95": "histogram",
"rule_match_distribution": "counter"
},
"canary": {
"traffic_split": "gauge",
"error_rate": "gauge",
"latency_p95": "gauge",
"promotion_events": "counter"
},
"kv": {
"gets_total": "counter",
"sets_total": "counter",
"evictions_total": "counter",
"hit_ratio_by_zone": "gauge"
}
}
Debug Headers (enable via debug=true):
X-Cache: HIT/MISS/BYPASS
X-Cache-Key: <generated_key>
X-Cache-TTL: 45
X-Cache-Zone: api-zone
X-Routing-Rule: rule_42
X-Canary-Version: v2.1.0
X-Canary-Cohort: beta_testers
X-Edge-Node: sjc-1a
X-Edge-Latency: 12ms
8. Security & Best Practices
-
Cache Poisoning Prevention:
- Validate and sanitize all cache key inputs
- Never cache responses with
Set-Cookie unless explicitly allowed
- Use separate cache namespaces for authenticated vs anonymous
-
Canary Safety:
- Automatic rollback on error rate > threshold
- Gradual traffic increase (1% → 5% → 25% → 100%)
- Separate metrics for canary vs stable
-
KV Storage:
- Encrypt sensitive data at rest
- Implement rate limiting per key
- Use versioned keys for atomic updates
-
Observability:
- Log all rule matches (debug mode only)
- Track cache efficiency per rule
- Alert on canary metric deviations
9. Configuration Management
Store all rules/configs in version-controlled config:
// config/routing-rules.json
{
"version": "1.2.0",
"rules": [...],
"canary_configs": [...],
"cache_zones": {
"api-zone": {
"ttl": 300,
"stale_ttl": 600,
"respect_origin_headers": false
}
},
"deployment": {
"rollout_steps": [1, 5, 25, 100],
"rollback_on_errors": true,
"max_concurrent_canaries": 3
}
}
Deploy via API:
curl -X POST https://edge-config.example.com/v1/deploy \
-H "Authorization: Bearer $TOKEN" \
-d @config/routing-rules.json
This design provides:
- Flexible routing with priority-based rules
- Intelligent caching with configurable keys & zones
- Safe canaries with gradual rollouts & auto-rollback
- Multi-tier storage (LRU → Regional KV → Origin)
- Observability with debug headers & metrics
- Production-ready patterns used by major CDNs
Would you like me to elaborate on any specific component or provide implementation details for a particular edge platform (Cloudflare Workers, Fastly, AWS Lambda@Edge, etc.)?