Guide

Once a CDN has servers in hundreds of cities, it's natural to run code on them. That is edge compute. Edge code works best when it can answer a request locally, or replace several trips to your origin with one. The same network also protects your origin, so the edge is your first line of defense.

Concept

The edge is the CDN's servers in each PoP. An origin round trip is a trip from the edge all the way to your main region, which costs about the same as the distance you measured earlier. A WAF, or web application firewall, inspects requests and blocks known attack patterns.

The big idea

Think of a building's front-desk guard. The guard checks IDs at the door, so bad visitors never reach the offices. The guard is useful only for questions the desk can answer. If every visitor needs the back-office records, the desk just adds a trip.

Edge compute is the same. Put checks and simple logic at the edge. Keep anything that needs a distant database where the database is.

Platforms include Cloudflare Workers, Fastly Compute, CloudFront Functions and Lambda@Edge. They differ in runtime and cold-start cost. CloudFront Functions are tiny and fast, and Lambda@Edge runs full functions with longer cold starts.

Walking through it

Good fits for the edge:

  • Redirects, rewrites and header changes.
  • Checking a JWT signature, and rejecting unauthenticated requests before they reach the origin.
  • A/B test buckets and feature flags, read from an edge key-value store.
  • Geolocation-based routing and data-residency checks.
  • Image resizing and format choice, such as serving AVIF to browsers that support it.

Here is a Worker sketch that rejects bad tokens and assigns a cache-friendly A/B bucket. The helpers verifyJwt, userIdFrom and hash are assumed.

TypeScript
// Sketch: verifyJwt, userIdFrom and hash are assumed helpers.
export default {
  async fetch(request: Request): Promise<Response> {
    const token = request.headers.get("Authorization")?.replace("Bearer ", "")
    if (!token || !(await verifyJwt(token))) {
      return new Response("unauthorized", { status: 401 })
    }
    const userId = await userIdFrom(token)
    const bucket = (await hash(userId)) % 100 < 10 ? "b" : "a" // 10% get variant b
    const url = new URL(request.url)
    url.searchParams.set("variant", bucket) // two variants in the cache key, not millions
    return fetch(new Request(url, request))
  },
}

Bad fits are work that needs several round trips to one region. If the edge in Sydney makes three sequential queries to a Postgres database in Virginia, that's about 600 ms, not less. Edge databases help, but they come with the trade-offs of any replicated store: fast reads, and writes that may be slow or eventually consistent.

On the security side, the edge helps in three ways.

  • DDoS absorption. Anycast spreads an attack across every PoP, so a flood of terabits per second becomes manageable at each site. Layer 7 floods are handled with rate limits and request fingerprinting.
  • WAF rules block SQL injection, cross-site scripting and known exploit patterns before they reach your code.
  • Bot management separates people from scrapers and credential-stuffing tools. It matters most for ticket booking, where bots hoard inventory.

Origin cloaking keeps all of this honest. If attackers can reach your origin's IP directly, they skip the edge entirely. Limit the origin to accept traffic only from the CDN: a firewall allow-list of the CDN's IP ranges, a secret header, mutual TLS, or a tunnel with no public IP.

Common mistakes

  • Multi-query edge functions. Each round trip to a distant database adds its full latency.
  • Leaving the origin reachable. Your WAF and rate limits do nothing if attackers can bypass them.
  • Putting private data in edge storage without thinking. Edge copies are spread across many cities.

Check yourself

  1. Why is three sequential queries to Virginia from Sydney a bad edge design? Each query is a round trip of about 200 ms, so the request grows by about 600 ms.
  2. What does origin cloaking prevent? Attackers reaching the origin's IP directly and skipping the CDN's protections.

Key takeaways

  • Edge code is great for checks and simple logic answered close to users.
  • Work that needs a distant database belongs at the origin.
  • The edge absorbs DDoS traffic, filters attacks with a WAF and scores bots.
  • Lock the origin so it accepts traffic only from the CDN.

Further learning

Next, return to the CDN overview to see how this page connects to caching, routing and cost.