# Edge-First

**Also known as:** Edge computing · Edge functions  
**Category:** System Architecture (Macro)  
**Complexity:** 3/5  
**Fit:** global audiences  
**Guide:** https://layra4.dev/architectures/system/edge-first

*Answer each request near the user, and send home only what must be central.*

Edge-first means running code at a CDN's points of presence, the hundreds of data centres that already cache your static files, and not only in one central region. Cloudflare Workers, Fastly Compute, Vercel and Netlify edge functions, and Lambda@Edge work this way. A request from Sydney is handled in Sydney: checked, routed, personalised and often answered without crossing an ocean.

The win is latency. A round trip from Sydney to the US East Coast takes about 200 ms, and a page that needs several round trips pays it each time. The catch is data. The edge holds copies, not the truth, so reads there can be stale, and every write still travels to the origin. Edge-first works when you decide, per request, what can be answered locally and what must go home.

> **In one sentence.** Put stateless, read-mostly work at edge locations near users and keep writes and strongly consistent data at one origin; the edge is only fast when the data it needs is there too.

## Origin (2017)

CDNs have cached static files since Akamai in the late 1990s, and Edge Side Includes (2001) let them assemble pages from parts. General code at the edge arrived with Lambda@Edge (2017) and Cloudflare Workers (2017–2018). Replicated key-value stores and databases for the edge followed.

## How it works

### Edge functions

Small request handlers deployed to every point of presence. They see a request before the cache and the origin do. Many run in lightweight isolates, not containers, so they start in milliseconds but offer a restricted runtime.

- One deploy runs in every location, not in one region
- Web-standard APIs (fetch, Request, Response), often not full Node.js
- Tight limits on CPU time, memory and bundle size

### Edge vs origin

The edge suits work that needs no central truth: checking a signed token, picking a variant, redirecting by country, serving cached or replicated reads. The origin keeps writes, transactions and anything that must see the latest data.

- Edge: token checks, redirects, A/B variants, headers, cached reads
- Origin: writes, payments, stock levels, reads right after a write
- When in doubt, start at the origin and move one path out once it proves safe

### Data locality

Code near the user helps only if its data is near too. Cache origin responses at the edge, replicate read-mostly data such as config, flags or a catalogue to an edge store, or put read replicas in a few regions.

- A function that calls a distant database adds latency instead of removing it
- Several queries in a row from the edge to the origin is the worst case
- Replicated edge data is eventually consistent

> edge in Sydney → database in Virginia: 3 queries × ~200 ms = ~600 ms

### Cold starts and runtime limits

Isolate-based runtimes start in a few milliseconds; container-based ones can take hundreds. All of them cap CPU time, memory and code size per request, and some restrict native modules or raw database connections.

- Keep the bundle small
- Reach databases through HTTP drivers or a pooling proxy
- Long or heavy work belongs at the origin or behind a queue

### The consistency cost

Each location reads its own copy of edge data, which is updated some time after the origin changes, from seconds to about a minute. A user who writes and then reads at the edge before the copy catches up sees old data.

- Send a user's reads to the origin for a few seconds after they write
- Purge or version cached keys when the source changes
- Never let two locations write the same key and expect one answer

## Design rules

### Keep the edge stateless and read-only

Edge code verifies, routes, transforms and reads copies. Every write goes to the origin, where one database decides.

### Move the data with the code, or leave the code at home

Before moving a handler, list what it reads. If that data cannot be cached or replicated near users, keep the handler at the origin. One round trip from the client to the origin beats several from the edge.

### Check tokens at the edge, authorise at the origin

A token's signature and expiry need only a public key, so they fit the edge. Decisions that depend on current data, such as a revoked session or a changed role, still belong at the origin.

### Expect every location to be slightly different

Deploys, cache contents and replicated data reach locations at different times. Version your data and keep old and new edge code compatible during a rollout.

## Examples

### An edge handler that answers what it can and forwards the rest

```typescript
// Deployed to every edge location; it sees each request before the cache and the origin.
// verifyJwt needs only a public key. edgeKv is a read-only copy replicated from the origin.
const ORIGIN = "https://origin.example.com";

export default {
  async fetch(req: Request): Promise<Response> {
    const url = new URL(req.url);
    const toOrigin = () => fetch(new Request(ORIGIN + url.pathname + url.search, req));

    // 1. Writes always go home: one database at the origin decides.
    if (req.method !== "GET") return toOrigin();

    // 2. Signature and expiry can be checked here. A revoked session is the origin's call.
    const user = await verifyJwt(req.headers.get("authorization"), PUBLIC_KEY);
    if (!user) return new Response("unauthorized", { status: 401 });

    // 3. Someone who wrote in the last few seconds reads from the origin, not a stale copy.
    if (Number(readCookie(req, "last_write") ?? 0) > Date.now() - 5_000) return toOrigin();

    // 4. Read-mostly data from the edge store: a few ms away, up to a minute old.
    const product = await edgeKv.get("product:" + url.pathname.split("/").pop());
    if (product) {
      return new Response(product, {
        headers: { "content-type": "application/json", "cache-control": "private, max-age=30" },
      });
    }

    // 5. Not replicated: make one trip to the origin, never several from here.
    return toOrigin();
  },
};
```

Steps 1, 3 and 5 send the request home; steps 2 and 4 are what the edge answers alone. The origin sets the last_write cookie on every write, and that cookie is the whole read-your-writes mechanism.

## When to use

- Users are spread across continents and round trips to one region dominate latency
- Much of each request is stateless: token checks, redirects, variants, headers
- Read-mostly data can be cached or replicated: catalogues, content, config, flags

## When not to use

- Most users are in one region near your servers, so the gain is a few milliseconds
- Requests are mostly writes or need the latest data, so they all go to the origin anyway
- Handlers need heavy CPU, long runs or native libraries the edge runtime does not allow

## Benefits

- Lower latency for distant users, often 100 ms or more saved per round trip
- Bad requests (no token, blocked country, bots) stop before they reach the origin
- The origin carries less load as more reads are answered at the edge

## Costs

- Reads at the edge can be stale, and read-your-writes must be built
- A second runtime, with tighter limits and fewer libraries
- Harder debugging: the same code runs in hundreds of places with different caches

## Pitfalls

- Moving a handler to the edge while it still makes three queries in a row to a database in one region, so it gets slower.
- Opening a new database connection per edge request, so a traffic spike uses up the database's connections.
- Personalising a response and caching it as public, so one user's page is served to others.
- Keeping counters or other writes in an eventually consistent edge store, and losing updates when two locations write at once.

## Related patterns

- [Content Delivery Network](https://layra4.dev/architectures/core-building-blocks/cdn) — the network of locations the edge code runs in
- [Serverless](https://layra4.dev/architectures/system/serverless) — the same per-request function model, in one region
- [Statelessness](https://layra4.dev/architectures/key-design-principles/statelessness) — why any location can serve any request
- [Database Replication](https://layra4.dev/architectures/data-storage/database-replication) — how read data gets close to users, with lag
- [Caching Strategies](https://layra4.dev/architectures/data-storage/caching-strategies) — what to cache at the edge and how to invalidate it

## Further reading

- *High Performance Browser Networking* — Ilya Grigorik (2013) — Why distance and round trips, not bandwidth, set the speed of the web.
- *Designing Data-Intensive Applications, ch. 5* — Martin Kleppmann (2017) — Replication lag and read-your-writes, the problems every edge copy inherits.
