PABCD Initiative Documentation Hub pabcd_initiative codexclaw cli-jaw

Edge & Serverless — Edge Computing Patterns

Source: dev-devops/references/edge-serverless.md

Edge & Serverless — Edge Computing Patterns

Last reviewed: 2026-06-16

Applies to: Cloudflare Workers, Vercel Edge Functions, AWS Lambda@Edge

When to read: Edge/serverless deployment tasks

Canonical owner: dev-devops

---

§1 Edge Request Shaping

What Belongs at the Edge

✅ Edge-appropriate❌ Keep at origin
Auth token validation (JWT verify)Auth token issuance (login flow)
Rate limiting / throttlingComplex business logic
Geo-routing / A-B testingDatabase writes
Response caching / transformationTransactions
Bot detection / WAF rulesLong-running processes
Request header enrichmentML inference (unless edge-optimized)
Static asset servingStateful sessions

Decision Tree

Request arrives at edge →
├── Static asset? → Serve from CDN cache
├── Auth check needed?
│   ├── JWT verify (stateless) → Edge
│   └── Session lookup (stateful) → Origin
├── Rate limit? → Edge (distributed counter)
├── Geo-specific routing? → Edge
└── Business logic → Origin

---

§2 Global API Front Door

Architecture

User → Edge PoP (nearest) → Auth/rate-limit/cache → Origin region
         │
         ├── Cache HIT → respond immediately
         ├── Auth FAIL → 401 at edge (no origin load)
         └── PASS → forward to origin with enriched headers

Request Enrichment Headers

HeaderSourcePurpose
X-CountryEdge geo-IPGeo-routing, compliance
X-Device-TypeUser-Agent parsingResponsive content
X-Request-IDEdge-generated UUIDDistributed tracing
X-Edge-PoPEdge locationDebugging latency
CF-Connecting-IPCloudflareReal client IP

---

§3 Auth at Edge

JWT Verification Pattern

// Cloudflare Workers — JWT verify at edge
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const token = request.headers.get("Authorization")?.replace("Bearer ", "");
    if (!token) {
      return new Response("Unauthorized", { status: 401 });
    }

    try {
      const payload = await verifyJWT(token, env.JWT_PUBLIC_KEY);

      // Enrich headers for origin
      const enriched = new Request(request, {
        headers: new Headers({
          ...Object.fromEntries(request.headers),
          "X-User-ID": payload.sub,
          "X-User-Role": payload.role,
        }),
      });

      return fetch(enriched);
    } catch {
      return new Response("Invalid token", { status: 401 });
    }
  },
};

Rules

RuleDetail
Stateless onlyJWT verify, API key check — no session DB calls
Fail closedInvalid/missing token → 401 at edge
Clock skewAllow 30s tolerance for exp / nbf claims
Key rotationSupport multiple public keys (JWKS)

---

§4 Edge AI Triage

When to Run AI at Edge

✅ Edge AI❌ Origin AI
Classification (<10ms, small model)LLM inference (large models)
Content moderation (text/image)Training / fine-tuning
Semantic cache lookupRAG with vector DB
Request priority scoringComplex chain-of-thought

Pattern: Semantic Cache at Edge

Request → Edge →
  1. Hash prompt → check KV cache
  2. Cache HIT → return cached response (sub-5ms)
  3. Cache MISS → forward to origin LLM → cache response → return

---

§5 Platform Patterns

Cloudflare Workers

FeatureDetail
RuntimeV8 isolates (not Node.js)
Limits10ms CPU (free), 30s (paid); 128MB memory
StorageKV (global), R2 (objects), D1 (SQLite), Durable Objects (state)
Deploywrangler deploy

Vercel Edge Functions

FeatureDetail
RuntimeEdge Runtime (Web APIs subset)
FrameworkNext.js export const runtime = "edge"
Limits30s execution, 4MB response
Use caseMiddleware, API routes, ISR

AWS Lambda@Edge / CloudFront Functions

TypeLimitUse Case
CloudFront Functions1ms, 10KBHeader manipulation, redirects
Lambda@Edge30s (origin), 5s (viewer)Auth, dynamic routing

---

§6 Anti-Patterns

BannedSymptomFix
Database calls from edgeHigh latency, connection pool exhaustionCache at edge, query at origin
Heavy computation at edgeCPU timeout (10ms limit on CF free)Offload to origin or queue
Stateful sessions at edgeInconsistent state across PoPsStateless JWT or edge KV
No fallback for edge failuresUsers see 500 from edge crashFail-open to origin
Hardcoded edge configCan't update without redeployEdge KV / feature flags