Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Edge Workers
HLD

Edge Workers

Programming the edge — the execution model, APIs, and real patterns from routing to personalization.

The Programming Model

 edge worker = your handler invoked per request at a POP:

 fetch event flow:
   request ──► [worker code] ──► response
                  │ can:
                  ├─ respond directly (no origin!)
                  ├─ modify then proxy to origin
                  ├─ call KV/cache/storage APIs
                  └─ fan out to multiple backends

 deployment: git push → global rollout in seconds.
 versioning/rollback built into platform. no fleets to manage.

Pattern 1: Smart Gateway

 the most common production shape:

 async fetch(req):
   token = req.headers.Authorization
   claims = await verify_jwt(token)        // JWKS cached at edge
   if (!claims) return 401                 // bad requests never
                                           // cross the ocean
   if (isCacheable(req)) 
       return serveFromEdgeCache(req)      // hits never leave POP
   
   req.headers.set('X-User-Id', claims.sub)
   return fetch(origin, req)               // enriched forward

Pattern 2: Edge Composition for Mobile

 mobile screens need data from 4 services; phone latency is precious:

 [phone] ─1 request──► [edge aggregator]
                          ├─fetch(users svc)─┐
                          ├─fetch(orders)────┼─ parallel from POP
                          ├─fetch(promos)────┘   (low internal RTT)
                          └─merge → one compact payload
 
 phone makes ONE request over the slow last mile;
 edge makes three fast ones. payload shaping per device class too:
 strip fields mobile doesn't render → bandwidth savings compound.

Pattern 3: Personalization Without Origin Hits

 shared page cached; personal fragments injected at edge:

 let page = await cache.match(sharedUrl)      // cached HTML
 if (user) {
     const prefs = await env.KV.get(user.id)  // edge-local read ~ms
     page = injectBanner(page, prefs)          // string surgery
 }
 return page

 result: personalized responses served ENTIRELY from POP —
 the composition pattern (dynamic caching lesson) with
 compute attached.

The API Surface (Platform-Agnostic Concepts)

APIRole
fetch()Proxy to origins/services
Cache APIProgrammatic edge cache control
KV storeReplicated eventually-consistent state
Durable objects / actorsStrongly-consistent single-owner state
QueuesAsync work handoff to regions
Secrets/envConfig and credentials
 mental model: standard web platform APIs + storage primitives,
 designed around the constraint set (stateless-ish, short-lived,
 networked state).

Operational Discipline

 - CPU budgets: profile hot paths; ms-level limits are real
 - observability: logs/metrics via platform pipelines;
   correlation IDs injected at edge propagate downstream
 - testing: same unit tests locally + staging POP behavior
 - rollbacks: instant (platform-native) — use them fearlessly
 - rate limiting/shedding AT the worker protects origins,
   same as any gateway tier

Interview Framing

“Where would you actually run code at the edge?” scored answers give CONCRETE patterns: JWT-gating gateway, mobile aggregation fan-out, cache+inject personalization — each with the latency/offload rationale. Then the boundary sentence: heavy stateful or long-compute stays regional. Patterns beat platitudes here.

My Private Notes

Notes are auto-saved locally to this device.