When this skill is activated, always start your first response with the 🧢 emoji.
Edge Computing
A comprehensive skill for building, deploying, and optimizing applications that run at the network edge - close to end users rather than in centralized data centers. This covers the full edge stack: writing Cloudflare Workers and Deno Deploy functions, configuring CDN cache rules and invalidation, implementing geo-routing and A/B testing at the edge, and systematically reducing latency through edge-side processing. The core principle is to move computation to where the user is, not the other way around.
When to use this skill
Trigger this skill when the user:
- Wants to write or debug a Cloudflare Worker, Deno Deploy function, or Vercel Edge Function
- Needs to configure CDN cache headers, cache keys, or invalidation strategies
- Is implementing geo-routing, A/B testing, or feature flags at the edge
- Wants to reduce TTFB or latency by moving logic closer to users
- Needs to transform requests or responses at the CDN layer
- Is working with edge-side KV stores, Durable Objects, or D1 databases
- Wants to implement authentication, rate limiting, or bot protection at the edge
- Is debugging cold start times or execution limits in edge runtimes
Do NOT trigger this skill for:
- General serverless architecture with traditional Lambda/Cloud Functions (use cloud-aws or cloud-gcp skill)
- Full backend API design that belongs in a centralized server (use backend-engineering skill)
Key principles
-
Edge is not a server - respect the constraints - Edge runtimes use V8 isolates, not Node.js. No filesystem access, limited CPU time (typically 10-50ms for free tiers), restricted APIs (no
eval, no native modules). Design for these constraints from the start rather than porting server code and hoping it works. -
Cache aggressively, invalidate precisely - The fastest request is one that never reaches your origin. Set long
Cache-Controlmax-age on immutable assets, usestale-while-revalidatefor dynamic content, and implement surgical cache purging by surrogate key or tag rather than full-site flushes. -
Minimize origin round-trips - Every request back to origin adds 50-200ms of latency. Use edge KV stores for read-heavy data, coalesce multiple origin fetches with Promise.all, and implement request collapsing so concurrent identical requests share a single origin fetch.
-
Fail open, not closed - When the edge function errors or times out, fall through to the origin server rather than showing an error page. Edge logic should enhance performance, not become a single point of failure.
-
Measure from the user's perspective - TTFB measured from your data center is meaningless. Use Real User Monitoring (RUM) with geographic breakdowns to understand actual latency. Synthetic tests from a single region miss the whole point of edge.
Core concepts
V8 isolates vs containers - Edge platforms like Cloudflare Workers use V8 isolates instead of containers. An isolate starts in under 5ms (vs 50-500ms for a cold container), shares a single process with other isolates, and has hard memory limits (~128MB). This architecture enables near-zero cold starts but restricts you to Web Platform APIs only.
Edge locations and PoPs - A Point of Presence (PoP) is a physical data center in the CDN network. Cloudflare has 300+ PoPs, AWS CloudFront has 400+. Your edge code runs at whichever PoP is geographically closest to the requesting user. Understanding PoP distribution matters for cache hit ratios - more PoPs means more cache fragmentation.
Cache tiers - Most CDNs use a tiered caching architecture: L1 (edge PoP closest to user) -> L2 (regional shield/tier) -> Origin. The L2 tier reduces origin load by coalescing requests from multiple L1 PoPs. Configure cache tiers explicitly when available (Cloudflare Tiered Cache, CloudFront Origin Shield).
Edge KV and state - Edge is inherently stateless per-request, but platforms provide persistence layers: Cloudflare KV (eventually consistent, read-optimized), Durable Objects (strongly consistent, single-point coordination), D1 (SQLite at the edge), and R2 (S3-compatible object storage). Choose based on consistency requirements and read/write ratio.
Request lifecycle at the edge - Incoming request -> DNS resolution -> nearest PoP -> edge function executes -> checks cache -> (cache miss) fetches from origin -> transforms response -> caches result -> returns to client. Understanding this flow is essential for placing logic at the right phase.
Common tasks
Write a Cloudflare Worker
Basic request/response handler using the Workers API:
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
// Route handling
if (url.pathname === '/api/health') {
return new Response('OK', { status: 200 });
}
// Fetch from origin and transform
const response = await fetch(request);
const html = await response.text();
const modified = html.replace('</head>', '<script src="/analytics.js"></script></head>');
return new Response(modified, {
status: response.status,
headers: response.headers,
});
},
};
Workers have a 10ms CPU time limit on the free plan (50ms on paid). Use
ctx.waitUntil()for non-blocking async work like logging that should not block the response.
Configure cache headers for optimal CDN behavior
Set cache-control headers that balance freshness with performance:
function setCacheHeaders(response: Response, type: 'static' | 'dynamic' | 'api'): Response {
const headers = new Headers(response.headers);
switch (type) {
case 'static':
// Immutable assets with content hash in filename
headers.set('Cache-Control', 'public, max-age=31536000, immutable');
break;
case 'dynamic':
// HTML pages - serve stale while revalidating in background
headers.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=86400');
headers.set('Surrogate-Key', 'page-content');
break;
case 'api':
// API responses - short cache with revalidation
headers.set('Cache-Control', 'public, max-age=5, stale-while-revalidate=30');
headers.set('Vary', 'Authorization, Accept');
break;
}
return new Response(response.body, { status: response.status, headers });
}
Always set
Varyheaders for responses that change based on request headers (e.g.,Accept-Encoding,Authorization). Missing Vary headers cause cache poisoning where one user gets another's personalized response.
Implement geo-routing at the edge
Route users to region-specific content or origins based on their location:
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const country = request.headers.get('CF-IPCountry') ?? 'US';
const continent = request.cf?.continent ?? 'NA';
// Route to nearest regional origin
const origins: Record<string, string> = {
EU: 'https://eu.api.example.com',
AS: 'https://ap.api.example.com',
NA: 'https://us.api.example.com',
};
const origin = origins[continent] ?? origins['NA'];
// GDPR compliance - block or redirect EU users to compliant flow
if (continent === 'EU' && new URL(request.url).pathname.startsWith('/track')) {
return new Response('Tracking disabled in EU', { status: 451 });
}
const url = new URL(request.url);
url.hostname = new URL(origin).hostname;
return fetch(url.toString(), request);
},
};
Use edge KV for read-heavy data
Store configuration, feature flags, or lookup tables in Cloudflare KV:
interface Env {
CONFIG_KV: KVNamespace;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Re