Skip to content

Edge functions — when to push code to the POP

When to run code at the CDN edge vs in the origin — request rewriting, A/B routing, auth, and the gotchas around cold start, state, and observability.

Edge functions — Cloudflare Workers, AWS Lambda@Edge, Fastly Compute@Edge, Akamai EdgeWorkers — let you run code in the CDN POP, before the request reaches origin or after the response leaves it. The pitch is “low latency, infinite scale, no servers.” The reality is “useful for specific patterns, dangerous when used as a substitute for an application tier.” This article is the decision framework we apply when a client asks “should this run at the edge?”

How to verify

Inspect what is currently running at the edge, the latency profile, and the deployment cadence. The CDN’s dashboard tells you most of it.

# Cloudflare Workers
curl -s https://api.cloudflare.com/client/v4/accounts/${ACCT}/workers/scripts \
  -H "Authorization: Bearer ${TOKEN}" | jq '.result[].id'

# Edge function response headers usually announce themselves
curl -sI https://app.example.com/ | grep -iE 'cf-worker|x-amz-cf-id|x-served-by|x-fastly-fn'

# Locally test latency from edge POPs
curl -w 'connect:%{time_connect}  ttfb:%{time_starttransfer}  total:%{time_total}\n' \
     -o /dev/null https://app.example.com/

If no edge function is running and you are considering one, the question is not “can we” — it is “what problem does it solve that origin cannot.”

What’s happening

Edge functions are small JavaScript or WebAssembly programs the CDN executes per request. They sit at the cache boundary: they can read the incoming request, modify it, decide whether to consult the cache, generate a response themselves, or call origin and modify the response. The runtimes are isolated (V8 isolates, Wasm modules) and start cold in single-digit milliseconds — much faster than a Lambda cold start.

What they buy you:

  • Request rewriting and routing at single-digit ms latency (no origin round-trip).
  • Authentication / token validation before the request consumes origin capacity.
  • A/B routing and feature-flag evaluation against the user’s geo or cookies.
  • Header injection (security headers, observability tags) without touching the application.
  • Lightweight API responses (JSON from KV, small computation) served from the POP.

What they do not buy you:

  • A database. Edge KV stores (Workers KV, DynamoDB Global Tables) have eventual consistency on the order of seconds. They are not transactional.
  • Stateful sessions. Each request can land on any POP.
  • Heavy compute. CPU budgets are tight (Workers: 50 ms CPU on free, hundreds on paid).
  • Easy debugging. You are deploying to a hundred POPs simultaneously and the logs land in the CDN’s pipeline, not yours.

The decision

  1. Run at the edge when: the task is read-only, can be done in milliseconds, and would otherwise cost an origin round-trip. Rewrites, redirects, header manipulation, geo-routing.

  2. Run at origin when: the task needs a database transaction, deep authorization with a directory service, or any compute over 50 ms.

  3. Pick a clean split. Edge function handles the “edge concerns” — auth check, route to right backend pool, set a header. Origin handles the application logic. No business logic in the edge function beyond “is this user allowed to proceed.”

  4. Deploy with the same rigor as origin code. A bad edge function rollout takes down every POP at once.

    # Cloudflare Wrangler workflow
    wrangler dev                              # local emulation
    wrangler deploy --env staging             # staging environment first
    wrangler tail --env staging               # watch live logs
    wrangler deploy --env production          # then prod
    wrangler rollback --version <prev>        # if it goes wrong
  5. Wire observability the same way as origin. Edge function logs to the CDN’s log pipeline; ship to your SIEM via the CDN’s log push.

    // Cloudflare Workers example
    export default {
      async fetch(request, env, ctx) {
        const start = Date.now();
        const url = new URL(request.url);
        if (url.pathname.startsWith('/api/auth/')) {
          return new Response('Not at edge', { status: 404 });
        }
        const country = request.cf?.country || 'XX';
        const newRequest = new Request(request);
        newRequest.headers.set('X-Edge-Country', country);
        newRequest.headers.set('X-Edge-Latency', String(Date.now() - start));
        return fetch(newRequest);
      }
    }

Common pitfalls

  • Treating the edge KV as a primary database; you will discover during an incident that “eventually consistent” means “ten seconds during a regional partition.”
  • Putting business validation logic at the edge — every change requires a multi-POP deploy; bug fixes ship slower than at origin.
  • Writing edge functions without local emulation; a typo deploys to every POP and you find out via support tickets.
  • Forgetting that the edge function executes per request, not per cache hit — caching the upstream response is the runtime’s job; the function still runs every time.
  • Relying on console.log for debugging in production; logs are sampled and the volume costs money.

We help clients pick the right altitude for each concern. The edge function is a tool, not a tier. Stack Harbor’s managed operations practice is to keep the edge code small, well-tested, and treated like any other deploy target — versioned, observable, and rollback-ready.