1. Deconstruct the Request:
* Goal: Build a CDN edge compute layer.
* Key Components: Routing rules, cache keys, KV/object storage, canaries.
* Implied Context: This is a system design/architecture task. It's about defining the structure and logic of a modern CDN edge worker (like Cloudflare Workers, Fastly Compute@Edge, or AWS Lambda@Edge).
-
Determine the Scope & Strategy:
- I need to design a system, not just write code. Diagrams (Mermaid) and explanations are crucial.
- I will use a "Code + Architecture" approach. I'll write a mock implementation in a language like TypeScript/JavaScript (common for edge runtimes like Workers) to demonstrate the logic, while explaining the architectural decisions around it.
-
Architectural Components:
- The "Edge" Concept: It's a function running close to the user, intercepting HTTP requests.
- Routing Rules: How do we decide where the request goes? (Path matching, headers, geo).
- Cache Keys: How do we ensure efficient caching? (Standard URL vs. Custom Vary headers).
- KV/Storage: Where does state live? (Read-heavy, eventually consistent).
- Canaries: How do we roll out new code safely? (Percentage-based routing).
-
Drafting the "Code" Implementation (The Core Logic):
- Entry Point:
fetch(event) handler.
- Config: Needs a configuration object to drive the logic without hardcoding.
- Step 1: Canary Check. Before anything else, check if this user should see the new version.
- Logic: Hash user ID or random %.
- Step 2: Routing.
- Logic: Map paths to backends (origin servers).
- Example:
/api/* -> API Origin, /static/* -> S3/Storage.
- Step 3: Cache Logic.
- Construct the cache key.
- Check Cache API.
- If miss, fetch from origin, store, return.
- Step 4: KV/Object Storage.
- Maybe redirect static assets to an R2/S3 binding or read metadata from a KV store (e.g., feature flags).
-
Refining the Components (Mental Sandbox):
- Routing: Needs to support regex or simple prefix.
- Cache Keys: Crucial point: Vary headers. If I cache based on
Accept-Encoding but ignore Accept-Language, I serve English to a French user. I need to show how to construct a custom cache key.
- Canaries: Needs to be deterministic (sticky sessions) so a user doesn't flip-flop between versions.
hash(ip or cookie) % 100 < canary_percent.
-
Structuring the Output:
- Architecture Overview: High-level diagram.
- The Edge Controller (The Code): A TypeScript implementation using a Cloudflare Workers-style syntax (it's the industry standard for this).
- Deep Dive - Routing: Explanation of the routing logic.
- Deep Dive - Caching: Explanation of cache keys and TTLs.
- Deep Dive - Canaries: Explanation of traffic splitting.
- Deep Dive - Storage: KV vs. Object.
-
Writing the Content (Iterative refinement):
- Diagram: User -> Edge (Canary?) -> (Cache?) -> (KV?) -> Origin.
- Code:
- Define interfaces for
Route, Config.
handleCanary: Check cookie/header.
resolveRoute: Iterate routes.
fetchWithCache: The caching layer. Self-correction: Don't just rely on browser cache, use the Edge Cache API.
handleKV: Simulated feature flag lookup.
-
Adding "Pro" touches:
- Mention Surrogate-Key for purging.
- Mention Shielding (connecting to a specific data center before origin).
- Mention Deterministic Hashing for canaries.
-
Final Review against User Prompt:
- Routing rules? Yes.
- Cache keys? Yes.
- KV/Object storage? Yes.
- Canaries? Yes.
-
Final Polish: formatting, clear headings, comments in code. (Proceeding to generate output).
Self-Correction during code writing: I initially thought about just modifying headers for caching, but the prompt asks to "Build" it. A programmatic cache (using a Cache API) is more powerful than just letting the CDN defaults handle it because it allows custom keys (e.g., caching mobile differently without changing the URL). I will implement a custom cache key strategy.
-
Constructing the response. (This aligns with the provided good response).
This design outlines a production-grade Edge Compute Layer (similar to Cloudflare Workers or Fastly Compute@Edge). It handles high-throughput routing, caching logic, storage binding, and safe deployment strategies.
1. High-Level Architecture
The system acts as a programmable proxy sitting between the User and the Origin.
graph LR
A[Client] -->|Request| B(Edge Network)
B --> C{Edge Logic Layer}
subgraph "Edge Logic (per request)"
C --> D[1. Canary Check]
D --> E[2. Router / Middleware]
E --> F[3. Storage Binding]
F --> G{4. Cache Lookup}
G -- Hit --> H[Response]
G -- Miss --> I[Origin Fetch]
I --> J[Cache Write]
J --> H
end
2. The Code Implementation (TypeScript)
This implementation uses a standard Service Worker API format (used by Cloudflare Workers, Deno Deploy, etc.).
// types.ts - Defining the shape of our Edge logic
interface RouteConfig {
path: RegExp;
origin: string;
cacheTTL?: number;
}
interface CanaryConfig {
percentage: number;
cookieName: string;
}
interface Env {
KV_STORE: KVNamespace; // Simulated KV Binding
OBJECT_STORE: ObjectStore; // Simulated R2/S3 Binding
ROUTES: RouteConfig[];
CANARY: CanaryConfig;
}
// --------------------------
// 1. Routing Layer
// --------------------------
const resolveOrigin = (url: string, routes: RouteConfig[]): string | null => {
const pathName = new URL(url).pathname;
// Find first matching route
const match = routes.find(r => r.path.test(pathName));
return match ? match.origin : null;
};
// --------------------------
// 2. Canary Release Logic
// --------------------------
const shouldServeCanary = (request: Request, config: CanaryConfig): boolean => {
// 1. Check for explicit cookie override (User opt-in)
const cookie = request.headers.get('Cookie') || '';
if (cookie.includes(`${config.cookieName}=new`)) return true;
if (cookie.includes(`${config.cookieName}=old`)) return false;
// 2. Deterministic hash based on Request ID (Sticky Sessions)
// This ensures a specific user always sees the same version
const reqId = request.headers.get('x-request-id') || crypto.randomUUID();
// Simple hash function to turn string into number 0-100
let hash = 0;
for (let i = 0; i < reqId.length; i++) {
hash = ((hash << 5) - hash) + reqId.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return Math.abs(hash % 100) < config.percentage;
};
// --------------------------
// 3. Cache Key Generation
// --------------------------
const generateCacheKey = (request: Request): string => {
const url = new URL(request.url);
// Base Key: URL + Path
let key = url.origin + url.pathname;
// Vary Cache by Headers (e.g., Mobile vs Desktop, or Currency)
const deviceType = request.headers.get('Sec-CH-UA-Mobile') ? '?mobile' : '?desktop';
const currency = request.headers.get('X-Currency') || 'USD';
// Append custom query params or headers logic here
key += `:${deviceType}:${currency}`;
return key;
};
// --------------------------
// Main Event Handler
// --------------------------
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
// A. Canary Check
const isCanary = shouldServeCanary(request, env.CANARY);
const versionHeader = isCanary ? 'canary-v2' : 'stable-v1';
// B. Routing
const origin = resolveOrigin(request.url, env.ROUTES);
if (!origin) return new Response("No route found", { status: 404 });
// C. Storage Binding Check (e.g., Feature Flags from KV)
// Fast reads at the edge
const featureFlag = await env.KV_STORE.get('enable-dark-mode', 'text');
const theme = featureFlag === 'true' ? 'dark' : 'light';
// D. Cache Logic
const cacheKey = generateCacheKey(request);
const cache = caches.default; // Global Edge Cache
// Check Cache
let response = await cache.match(new Request(cacheKey, request));
if (response) {
// Cache Hit
const newHeaders = new Headers(response.headers);
newHeaders.set('X-Cache-Status', 'HIT');
newHeaders.set('X-Edge-Version', versionHeader);
return new Response(response.body, { ...response, headers: newHeaders });
}
// Cache Miss - Prepare Origin Request
const originUrl = new URL(request.url);
originUrl.hostname = origin; // Rewrite hostname
// Add headers for origin
const originHeaders = new Headers(request.headers);
originHeaders.set('X-Edge-Cache-Key', cacheKey);
originHeaders.set('X-Edge-Theme', theme);
// E. Object Storage Short-circuit (Check for static assets in Object Store first)
if (request.url.includes('/static/assets/')) {
const objectKey = request.url.split('/assets/')[1];
const obj = await env.OBJECT_STORE.get(objectKey);
if (obj) {
return new Response(obj.body, {
headers: {
'Content-Type': 'image/webp',
'Cache-Control': 'public, max-age=31536000'
}
});
}
}
// F. Fetch from Origin
response = await fetch(originUrl.toString(), {
method: request.method,
headers: originHeaders,
body: request.body
});
// G. Write to Cache (Only cache 200 OK responses)
if (response.status === 200) {
// We must clone the response to store it in cache
const responseToCache = new Response(response.body, response);
responseToCache.headers.set('Cache-Control', 'public, max-age=3600');
// Put in cache (waitUntil ensures this happens async without delaying user)
ctx.waitUntil(cache.put(new Request(cacheKey), responseToCache));
}
// Return Response
const finalHeaders = new Headers(response.headers);
finalHeaders.set('X-Cache-Status', 'MISS');
finalHeaders.set('X-Edge-Version', versionHeader);
return new Response(response.body, { ...response, headers: finalHeaders });
}
};
3. Detailed Component Breakdown
A. Routing Rules
Instead of hardcoding if/else statements, a production edge layer usually uses a declarative configuration map.
- Path Matching: We use Regex for flexibility (e.g.,
/api/v1/*).
- Origin Rewriting: The edge layer keeps the public URL (
www.shop.com) but secretly fetches from internal-api.service or s3-bucket.
- Middleware Chain: In the code above, routing happens after Canary checks. This allows you to route "Canary users" to an entirely different infrastructure (e.g., a V2 kubernetes cluster) transparently.
B. Cache Keys (The Art of Invalidation)
A naive cache key is just the URL. A robust CDN edge key includes:
- Query String Normalization: Sorting query params (
?id=1&ref=tw is the same as ?ref=tw&id=1).
- Vary Headers: The
generateCacheKey function above varies the cache based on X-Currency. This is crucial for internationalization (don't serve USD prices to EUR users).
- Surrogate Keys: In a real implementation, you would add a
Surrogate-Key header (e.g., product-123). This allows you to purge all cache entries related to product 123 via an API call later, without knowing the specific URLs.
C. KV vs. Object Storage
Edge computing relies on two types of storage:
- KV (Key-Value): Used for metadata, config flags, and user sessions.
- Latency: Sub-millisecond.
- Consistency: Eventually consistent (read-heavy optimized).
- Use case: Checking if a feature flag is on/off before rendering.
- Object Storage (R2/S3): Used for large blobs (images, videos, logs).
- Latency: Milliseconds.
- Use case: Serving user-uploaded images directly from the edge without hitting the main application server.
D. Canaries (Traffic Shifting)
The shouldServeCanary function implements Deterministic Canarying.
- Problem: Random traffic splitting (50% chance) causes "flapping" (a user sees the new site, refreshes, and sees the old site).
- Solution: Hash the User ID or Request ID.
- If
hash(id) % 100 < 10, the user is always in the 10% bucket.
- This ensures a consistent user experience and makes debugging easier.
- Cookie Override: Allows developers to force themselves onto the new version via a browser cookie, regardless of the traffic percentage.
4. Deployment & Configuration (JSON)
This JSON represents how you would configure the edge layer without changing code.
{
"canary": {
"percentage": 10,
"cookieName": "edge_beta"
},
"routes": [
{
"path": "^/api/checkout",
"origin": "checkout.internal.svc.cluster.local",
"cacheTTL": 0
},
{
"path": "^/static",
"origin": "cdn-bucket.s3.amazonaws.com",
"cacheTTL": 86400
},
{
"path": "^/.*",
"origin": "legacy-web.appspot.com",
"cacheTTL": 3600
}
]
}