Edge Computing Patterns
Overview
Edge computing runs code closer to users worldwide, reducing latency from seconds to milliseconds. This skill covers Cloudflare Workers, Vercel Edge Functions, and Deno Deploy patterns for building globally distributed applications.
When to use this skill:
- Global applications requiring <50ms latency
- Authentication/authorization at the edge
- A/B testing and feature flags
- Geo-routing and localization
- API rate limiting and DDoS protection
- Transforming responses (image optimization, HTML rewriting)
Platform Comparison
| Feature |
Cloudflare Workers |
Vercel Edge |
Deno Deploy |
| Cold Start |
<1ms |
<10ms |
<10ms |
| Locations |
300+ |
100+ |
35+ |
| Runtime |
V8 Isolates |
V8 Isolates |
Deno |
| Max Duration |
30s (paid: unlimited) |
25s |
50ms-5min |
| Free Tier |
100k req/day |
100k req/month |
100k req/month |
Cloudflare Workers
// worker.ts
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url)
// Geo-routing
const country = request.cf?.country || 'US'
if (url.pathname === '/api/hello') {
return new Response(JSON.stringify({
message: `Hello from ${country}!`
}), {
headers: { 'Content-Type': 'application/json' }
})
}
// Cache API
const cache = caches.default
let response = await cache.match(request)
if (!response) {
response = await fetch(request)
// Cache for 1 hour
response = new Response(response.body, response)
response.headers.set('Cache-Control', 'max-age=3600')
await cache.put(request, response.clone())
}
return response
}
}
// Durable Objects for stateful edge
export class Counter {
private state: DurableObjectState
private count = 0
constructor(state: DurableObjectState) {
this.state = state
}
async fetch(request: Request) {
const url = new URL(request.url)
if (url.pathname === '/increment') {
this.count++
await this.state.storage.put('count', this.count)
}
return new Response(JSON.stringify({ count: this.count }))
}
}
Vercel Edge Functions
// middleware.ts (Edge Middleware)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// A/B testing
const bucket = Math.random() < 0.5 ? 'a' : 'b'
const url = request.nextUrl.clone()
url.searchParams.set('bucket', bucket)
// Geo-location
const country = request.geo?.country || 'US'
const response = NextResponse.rewrite(url)
response.cookies.set('bucket', bucket)
response.headers.set('X-Country', country)
return response
}
export const config = {
matcher: '/experiment/:path*'
}
// Edge API Route
export const runtime = 'edge'
export async function GET(request: Request) {
return new Response(JSON.stringify({
timestamp: Date.now(),
region: process.env.VERCEL_REGION
}))
}
Edge Runtime Constraints
✅ Available:
fetch, Request, Response, Headers
URL, URLSearchParams
TextEncoder, TextDecoder
ReadableStream, WritableStream
crypto, SubtleCrypto
- Web APIs (atob, btoa, setTimeout, etc.)
❌ Not Available:
- Node.js APIs (
fs, path, child_process)
- Native modules
- Some npm packages
- File system access
Common Patterns
Authentication at Edge
import { verify } from '@tsndr/cloudflare-worker-jwt'
export default {
async fetch(request: Request, env: Env) {
const token = request.headers.get('Authorization')?.replace('Bearer ', '')
if (!token) {
return new Response('Unauthorized', { status: 401 })
}
const isValid = await verify(token, env.JWT_SECRET)
if (!isValid) {
return new Response('Invalid token', { status: 403 })
}
// Proceed with authenticated request
return fetch(request)
}
}
Rate Limiting
export default {
async fetch(request: Request, env: Env) {
const ip = request.headers.get('CF-Connecting-IP')
const key = `ratelimit:${ip}`
// Use KV for rate limiting
const count = await env.KV.get(key)
const currentCount = count ? parseInt(count) : 0
if (currentCount >= 100) {
return new Response('Rate limit exceeded', { status: 429 })
}
await env.KV.put(key, (currentCount + 1).toString(), {
expirationTtl: 60 // 1 minute
})
return fetch(request)
}
}
Edge Caching
async function handleRequest(request: Request) {
const cache = caches.default
const cacheKey = new Request(request.url, request)
// Try cache first
let response = await cache.match(cacheKey)
if (!response) {
// Fetch from origin
response = await fetch(request)
// Cache successful responses
if (response.status === 200) {
response = new Response(response.body, response)
response.headers.set('Cache-Control', 'max-age=3600')
await cache.put(cacheKey, response.clone())
}
}
return response
}
Best Practices
- ✅ Keep bundles small (<1MB)
- ✅ Use streaming for large responses
- ✅ Leverage edge caching (KV, Durable Objects)
- ✅ Handle errors gracefully (edge errors can't be recovered)
- ✅ Test cold starts and warm starts
- ✅ Monitor edge function performance
- ✅ Use environment variables for secrets
- ✅ Implement proper CORS headers
Resources
1---2name: edge-computing-patterns3description: Deploy to edge runtimes (Cloudflare Workers, Vercel Edge, Deno Deploy) for globally distributed, low-latency applications. Master edge middleware, streaming, and runtime constraints for 2025+ edge computing.4version: 1.0.05author: AI Agent Hub6tags: [edge, cloudflare, vercel, deno, serverless, 2025]7---89# Edge Computing Patterns1011## Overview1213Edge computing runs code closer to users worldwide, reducing latency from seconds to milliseconds. This skill covers Cloudflare Workers, Vercel Edge Functions, and Deno Deploy patterns for building globally distributed applications.1415**When to use this skill:**16- Global applications requiring <50ms latency17- Authentication/authorization at the edge18- A/B testing and feature flags19- Geo-routing and localization20- API rate limiting and DDoS protection21- Transforming responses (image optimization, HTML rewriting)2223## Platform Comparison2425| Feature | Cloudflare Workers | Vercel Edge | Deno Deploy |26|---------|-------------------|-------------|-------------|27| Cold Start | <1ms | <10ms | <10ms |28| Locations | 300+ | 100+ | 35+ |29| Runtime | V8 Isolates | V8 Isolates | Deno |30| Max Duration | 30s (paid: unlimited) | 25s | 50ms-5min |31| Free Tier | 100k req/day | 100k req/month | 100k req/month |3233## Cloudflare Workers3435```typescript36// worker.ts37export default {38 async fetch(request: Request, env: Env): Promise<Response> {39 const url = new URL(request.url)4041 // Geo-routing42 const country = request.cf?.country || 'US'4344 if (url.pathname === '/api/hello') {45 return new Response(JSON.stringify({46 message: `Hello from ${country}!`47 }), {48 headers: { 'Content-Type': 'application/json' }49 })50 }5152 // Cache API53 const cache = caches.default54 let response = await cache.match(request)5556 if (!response) {57 response = await fetch(request)58 // Cache for 1 hour59 response = new Response(response.body, response)60 response.headers.set('Cache-Control', 'max-age=3600')61 await cache.put(request, response.clone())62 }6364 return response65 }66}6768// Durable Objects for stateful edge69export class Counter {70 private state: DurableObjectState71 private count = 07273 constructor(state: DurableObjectState) {74 this.state = state75 }7677 async fetch(request: Request) {78 const url = new URL(request.url)7980 if (url.pathname === '/increment') {81 this.count++82 await this.state.storage.put('count', this.count)83 }8485 return new Response(JSON.stringify({ count: this.count }))86 }87}88```8990## Vercel Edge Functions9192```typescript93// middleware.ts (Edge Middleware)94import { NextResponse } from 'next/server'95import type { NextRequest } from 'next/server'9697export function middleware(request: NextRequest) {98 // A/B testing99 const bucket = Math.random() < 0.5 ? 'a' : 'b'100 const url = request.nextUrl.clone()101 url.searchParams.set('bucket', bucket)102103 // Geo-location104 const country = request.geo?.country || 'US'105106 const response = NextResponse.rewrite(url)107 response.cookies.set('bucket', bucket)108 response.headers.set('X-Country', country)109110 return response111}112113export const config = {114 matcher: '/experiment/:path*'115}116117// Edge API Route118export const runtime = 'edge'119120export async function GET(request: Request) {121 return new Response(JSON.stringify({122 timestamp: Date.now(),123 region: process.env.VERCEL_REGION124 }))125}126```127128## Edge Runtime Constraints129130**✅ Available**:131- `fetch`, `Request`, `Response`, `Headers`132- `URL`, `URLSearchParams`133- `TextEncoder`, `TextDecoder`134- `ReadableStream`, `WritableStream`135- `crypto`, `SubtleCrypto`136- Web APIs (atob, btoa, setTimeout, etc.)137138**❌ Not Available**:139- Node.js APIs (`fs`, `path`, `child_process`)140- Native modules141- Some npm packages142- File system access143144## Common Patterns145146### Authentication at Edge147```typescript148import { verify } from '@tsndr/cloudflare-worker-jwt'149150export default {151 async fetch(request: Request, env: Env) {152 const token = request.headers.get('Authorization')?.replace('Bearer ', '')153154 if (!token) {155 return new Response('Unauthorized', { status: 401 })156 }157158 const isValid = await verify(token, env.JWT_SECRET)159 if (!isValid) {160 return new Response('Invalid token', { status: 403 })161 }162163 // Proceed with authenticated request164 return fetch(request)165 }166}167```168169### Rate Limiting170```typescript171export default {172 async fetch(request: Request, env: Env) {173 const ip = request.headers.get('CF-Connecting-IP')174 const key = `ratelimit:${ip}`175176 // Use KV for rate limiting177 const count = await env.KV.get(key)178 const currentCount = count ? parseInt(count) : 0179180 if (currentCount >= 100) {181 return new Response('Rate limit exceeded', { status: 429 })182 }183184 await env.KV.put(key, (currentCount + 1).toString(), {185 expirationTtl: 60 // 1 minute186 })187188 return fetch(request)189 }190}191```192193### Edge Caching194```typescript195async function handleRequest(request: Request) {196 const cache = caches.default197 const cacheKey = new Request(request.url, request)198199 // Try cache first200 let response = await cache.match(cacheKey)201202 if (!response) {203 // Fetch from origin204 response = await fetch(request)205206 // Cache successful responses207 if (response.status === 200) {208 response = new Response(response.body, response)209 response.headers.set('Cache-Control', 'max-age=3600')210 await cache.put(cacheKey, response.clone())211 }212 }213214 return response215}216```217218## Best Practices219220- ✅ Keep bundles small (<1MB)221- ✅ Use streaming for large responses222- ✅ Leverage edge caching (KV, Durable Objects)223- ✅ Handle errors gracefully (edge errors can't be recovered)224- ✅ Test cold starts and warm starts225- ✅ Monitor edge function performance226- ✅ Use environment variables for secrets227- ✅ Implement proper CORS headers228229## Resources230231- [Cloudflare Workers Documentation](https://developers.cloudflare.com/workers/)232- [Vercel Edge Functions](https://vercel.com/docs/functions/edge-functions)233- [Deno Deploy](https://deno.com/deploy/docs)