Skip to content

Edge Computing and Edge Functions

Intermediate 52 min read Part 10 of 18

Run code near users: edge vs CDN vs region, V8 isolates and Wasm, use cases, edge data stores and their consistency limits, IoT and fog, latency and cost math.

Summary#

Edge computing means running code and keeping data physically close to the user or device: in hundreds of points of presence (PoPs) around the world, in a cell tower, or in a gateway on a factory floor. The alternative is a handful of cloud regions. The motivation is physics. Light in fibre covers about 200 km per millisecond, so a user in Sydney talking to a server in Virginia pays about 160 ms per round trip before any work is done, and a fresh HTTPS connection needs several round trips.

A CDN already caches static bytes at the edge (Content Delivery Networks (CDN)). Edge functions add programmable logic at those same PoPs:

  • verify a token;
  • redirect a short URL;
  • bucket a user into an A/B test;
  • rewrite headers;
  • resize an image;
  • pick a region.

All of this happens in a few milliseconds, without a trip to the origin. Most edge platforms run code in lightweight sandboxes:

  • V8 isolates, as in Cloudflare Workers, Deno Deploy and Vercel Edge Functions;
  • WebAssembly runtimes, as in Fastly Compute;
  • trimmed-down Lambdas, as in Lambda@Edge and CloudFront Functions.

These start in milliseconds or microseconds, and the price is strict limits on CPU time, memory, package size and APIs.

The hard part is data. Code is easy to copy to 300 cities, but state isn't. Edge data stores make explicit consistency trade-offs:

  • eventually consistent KV (fast global reads, writes take seconds to a minute to spread);
  • single-homed strongly consistent objects (Durable Objects);
  • replicated SQLite with a single writer and read replicas.

The edge shines for stateless or read-mostly logic in front of the origin. It hurts when a request needs several round trips to a central database. That pattern is slower at the edge than in-region. IoT and fog computing push the same idea further, to processing near sensors, because bandwidth, privacy and offline operation matter as much as latency there. Use the edge deliberately, with the latency math in hand.

Why It Exists#

Three forces push computation toward the edge.

1. Physics sets a latency floor. Signals in optical fibre travel at about two-thirds of the speed of light in a vacuum, roughly 200,000 km/s. That's 5 µs per km one way, or 1 ms of round-trip time (RTT) per 100 km of fibre. Real routes are longer than great-circle distance and add router hops, so measured RTTs are typically 1.3–2× the theoretical minimum.

RouteGreat-circle distanceTheoretical min RTTTypical real RTT
Same city, user to PoPUnder 50 kmUnder 0.5 ms2–10 ms (access network dominates)
New York to London~5,600 km~56 ms~70–80 ms
San Francisco to Virginia~3,900 km~39 ms~60–75 ms
Sydney to Virginia~15,700 km~157 ms~200–230 ms
Mumbai to Frankfurt~6,300 km~63 ms~110–130 ms

No amount of engineering at the origin beats these numbers. The only way to cut them is to move the work closer. That's the core idea of data locality: performance is best when data and the code using it sit together, near the user.

2. Round trips multiply. A new HTTPS connection needs:

  • a TCP handshake (1 RTT);
  • a TLS 1.3 handshake (1 RTT; TLS 1.2 needed 2);
  • the request itself (1 RTT).

Before the first byte arrives, that's 3 RTTs at minimum, plus DNS. For the Sydney user talking to Virginia, that's about 600–700 ms. If an edge PoP 10 ms away terminates TCP and TLS and holds a warm, pooled connection to the origin, the same request costs 3 × 10 ms at the edge plus 1 × 200 ms to the origin, about 230 ms. If the edge can answer the request itself (a cache hit or edge logic), it costs about 30 ms. That's a 20× improvement, without touching the origin.

3. Origins are expensive and fragile under load. Every request answered at the edge is one the origin never sees. A redirect service, a bot filter or an auth check running at the edge can absorb huge traffic spikes and DDoS floods across hundreds of PoPs, rather than in one region.

Beyond the web, IoT brings different pressures:

  • Bandwidth: a factory with 10,000 sensors at 1 kHz can't ship every raw sample to the cloud.
  • Privacy and sovereignty: video from cameras may legally have to stay on-site.
  • Autonomy: a wind turbine must keep controlling itself when the WAN link is down.
  • Hard real-time control: a robot arm can't wait 80 ms for a cloud decision.

These push processing to gateways and on-premises nodes. That layer is called fog computing.

How It Works#

Edge vs CDN vs region: the layers of a global system#

"Edge" means different things to different vendors, so it helps to name the layers precisely. Moving outward from the centre:

LayerWhere it isTypical countRTT to userWhat runs there
Cloud regionLarge data-centre campus, usually 3+ availability zones~30–40 per major cloud20–250 msEverything: databases, queues, stateful services, batch jobs
Regional edge cache / mid-tierLarge PoPs that aggregate many smaller onesAround a dozen to dozens10–60 msLarger caches, origin shield, Lambda@Edge
Edge PoPCDN data centre in a metro, often inside an Internet exchangeHundreds5–30 msTLS termination, caching, WAF, edge functions, edge KV
Telco and on-prem edgeInside the carrier network (5G MEC) or the customer siteThousands1–10 msLatency-critical apps, AWS Wavelength, Outposts, private 5G
Device and gateway (fog)Phone, car, router, factory gatewayMillions to billionsUnder 1 ms (local)Filtering, aggregation, local control, on-device ML

Each layer trades proximity against capacity, state and generality. A region can run anything and hold your source-of-truth database. A PoP has limited CPU per customer and very limited durable state. A device has almost no shared state but zero network latency.

The terms differ like this:

  • Region is where your system lives. Its source of truth, its writes and its heavy computation sit there. Multi-region designs replicate this layer (Multi-Region and Global Data), but there are still only a few copies, each a full stack.
  • CDN is a globally distributed cache for bytes the origin produced: images, JS, video segments, cacheable API responses. It's mostly passive. It follows the cache rules the origin set (Cache-Control, TTLs, purges) and adds no business logic.
  • Edge computing puts your code in the CDN's PoPs, or further out. It can make decisions per request: compute a response, transform one, route it, or reject it. The CDN becomes a programmable platform.

What happens to a request at the edge#

A typical request through a programmable CDN goes through these steps:

  1. DNS or anycast routing sends the user to a nearby PoP. Many CDNs announce the same IP prefix from every PoP (anycast), so BGP routes each user to the topologically closest one. Others use geo-aware DNS that returns PoP-specific addresses (DNS: The Domain Name System).
  2. The PoP terminates TCP and TLS, so the handshake round trips are short.
  3. Security layers run first: DDoS mitigation, WAF rules, bot scoring and rate limits.
  4. The edge function runs on the request. It may answer directly (redirect, 403, a computed response), rewrite the request (change the URL, add headers, choose an origin), or pass it through.
  5. The cache is checked, using a cache key the function may have customised.
  6. On a miss, the request goes to the origin, often through a regional tier or origin shield that collapses duplicate misses. It travels over a long-lived, already-warm connection, sometimes on the provider's private backbone.
  7. The response may be transformed on the way back (inject headers, rewrite HTML, resize an image), cached, and returned.

The edge function can sit at several of these hooks. AWS made the hooks explicit. Lambda@Edge can be attached to four CloudFront events:

  • viewer request: after CloudFront receives the request, before the cache check;
  • origin request: on a cache miss, before forwarding to the origin;
  • origin response: after the origin answers, before caching;
  • viewer response: before returning to the user, on every response including cache hits.

The placement decides cost and behaviour. Logic on origin-request and origin-response runs only on misses, so it's cheap and can be heavier. Work done there (such as image resizing) is cached, so you pay for it once per variant. Logic on viewer-request and viewer-response runs on every request, so it must be tiny. Auth, A/B bucketing and header normalisation belong there. Most platforms, including Cloudflare Workers and Fastly Compute, use a simpler model: one function sees the request and decides everything, calling the cache and origin explicitly through APIs like fetch() and caches.default.

Edge function runtimes: isolates, Wasm and micro-VMs#

Running customer code in hundreds of PoPs means each PoP must host code from thousands or millions of customers on a limited set of machines. Most of those scripts are idle at any moment, yet any of them must respond within milliseconds. Regional serverless (AWS Lambda, Cloud Run) solves isolation with containers or Firecracker micro-VMs (Serverless and Functions-as-a-Service). Firecracker micro-VMs boot in about 125 ms with under 5 MiB of monitor overhead each (Agache et al., "Firecracker: Lightweight Virtualization for Serverless Applications", NSDI 2020). Add a guest kernel and a language runtime, and each warm instance holds tens of MB. That's fine for a region but too heavy to keep millions of instances warm in every PoP. The edge needs something lighter.

V8 isolates. V8 is the JavaScript engine in Chrome and Node.js. An isolate is an independent V8 heap with its own objects and garbage collector, running inside a shared process. Browsers use isolates to separate tabs and iframes. Cloudflare Workers (launched in 2017) used them to separate customers. One OS process hosts many isolates, and creating one takes a few milliseconds and a few MB of memory, compared with hundreds of milliseconds and tens to hundreds of MB for a container with a language runtime. Cloudflare's engineers described the reasoning in Kenton Varda's 2018 post "Cloud Computing without Containers". Because isolates are so cheap, a PoP can keep thousands loaded and evict idle ones. Cloudflare also starts loading a Worker during the TLS handshake, as soon as the SNI hostname is known, so the startup is usually hidden from the user. The same model powers Deno Deploy, Vercel Edge Functions, Netlify Edge Functions (built on Deno) and Akamai EdgeWorkers.

The costs of the isolate model:

  • Only JavaScript or TypeScript, or Wasm. No arbitrary binaries and no native extensions.
  • Not full Node.js. The APIs are web-standard (fetch, Request and Response, Web Crypto, streams). Node built-ins have only partial compatibility layers, so libraries that use fs, raw TCP sockets or native modules may not work.
  • Weaker isolation than VMs. Isolates share a process, so the platform must defend against Spectre-class side channels. Mitigations include removing high-resolution timers (the clock doesn't advance during execution), disallowing shared-memory multithreading, and moving suspicious workloads into separate processes.
  • Tight resource caps, described below.

WebAssembly (Wasm). Wasm is a portable, sandboxed binary instruction format, introduced by Haas et al. in "Bringing the Web up to Speed with WebAssembly" (PLDI 2017). Code compiled from Rust, Go, C/C++, AssemblyScript and others runs in a linear-memory sandbox. The module can only touch its own memory array and the host functions it's explicitly given. Ahead-of-time compiled Wasm modules can be instantiated in microseconds. Fastly Compute uses this to create a fresh instance for every request: no state leaks between requests, and no warm-instance pool is needed. WASI (the WebAssembly System Interface) standardises access to files, clocks, sockets and so on, and the component model standardises how modules compose. Wasm brings language choice and strong sandboxing. Its costs are a less mature ecosystem, larger binaries for some languages, and limited threading.

Trimmed regional functions. Lambda@Edge runs Node.js or Python Lambda functions in CloudFront's regional edge caches (around a dozen locations), not in every PoP. It has more power (more memory and time on origin-side triggers, and network access) but higher latency and cold starts like Lambda. CloudFront Functions (2021) is a separate, much lighter JavaScript runtime that runs in every CloudFront edge location, only on viewer-request and viewer-response. It has sub-millisecond execution budgets, no network access and a tiny package size limit. It's designed for header manipulation, URL rewrites, redirects and simple token checks at very high volume.

Edge containers and VMs. Some platforms run full containers or micro-VMs in many cities. Fly.io runs Firecracker micro-VMs in dozens of regions, and the carrier platforms run standard compute in telco data centres. These give full generality (any language, long-lived processes, local disks) at "metro" rather than "every PoP" density. They're closer to many small regions than to a CDN.

RuntimeWhere it runsStart timeLanguagesTypical limitsBest for
Cloudflare Workers, Deno Deploy, Vercel EdgeEvery PoP, hundreds of cities~0–5 ms (isolate)JS/TS, Wasm~128 MB memory; CPU time capped per request; script-size capGeneral edge logic, APIs, HTML rewriting
Fastly ComputeEvery PoPMicroseconds (Wasm instance)Rust, Go, JS, others via WasmMemory and CPU caps per requestPer-request isolation, high-performance edge logic
CloudFront FunctionsEvery CloudFront edge locationSub-msJS (restricted)~1 ms compute, no network, 10 KB codeHeader and URL rewrites, redirects, simple auth
Lambda@EdgeRegional edge cachesLambda-like cold starts (~100 ms+)Node.js, PythonViewer triggers ~5 s and small packages; origin triggers ~30 sHeavier transforms on cache misses, origin selection
Fly.io, edge containers, telco MECMetro or region-level sitesSeconds (VM or container)AnythingNormal VM limitsStateful apps near users, full runtimes, game servers

Limits change frequently. Treat these as orders of magnitude and check the provider's current documentation before you design around them.

Use cases that fit the edge#

The best edge workloads share three properties:

  • they need little or no fresh, strongly consistent state;
  • they run on the hot path of many requests;
  • they're cheap in CPU: microseconds to a few milliseconds.

The classic ones follow.

1. Authentication and authorisation checks. Verifying a signed token needs only the public key and the clock. No database is involved. An edge function can:

  • validate a JWT: check the signature, exp, aud and iss;
  • reject invalid requests with 401 before they cost the origin anything;
  • forward the verified identity as a trusted header (for example X-User-Id) over an authenticated channel to the origin.

The signing keys (a JWKS document) are fetched once and cached at the edge for minutes to hours. Revocation is the weak spot, since a stateless check can't know a token was revoked a second ago. Mitigations:

  • short token lifetimes (5–15 minutes) plus refresh tokens checked at the origin;
  • a small revocation list replicated through edge KV, accepting its propagation delay;
  • routing sensitive operations (payments, password changes) to the origin for a full check.

The edge is the first gate, not the only one (Authentication and Authorization). Signed URLs and signed cookies for private content (paid video, private downloads) are the same idea: an HMAC or signature over path plus expiry, verified at the PoP.

2. Redirects and URL rewriting. A URL shortener is the textbook example. Reads outnumber writes by orders of magnitude, and a redirect is a pure lookup from short code to long URL. A plain CDN can cache the 301 or 302 response from the origin for popular codes. An edge function goes further: it looks up the mapping in edge KV and returns the redirect without ever reaching the origin, even for codes that aren't in the cache yet. That holds as long as the KV store has replicated the mapping. The latency for a user anywhere drops to the PoP RTT, about 10–30 ms instead of 100–300 ms.

The trade-offs are real:

  • Freshness. A changed or deleted link may still redirect from some PoPs until KV propagation or cache TTLs expire. That matters for malicious links that must be taken down, so design an explicit purge path.
  • Cost. Edge compute plus CDN egress at high volume may cost more than a few origin servers.
  • Limits. Execution time, memory and library constraints force a minimal redirect path.
  • Operations. Debugging and monitoring logic spread across hundreds of PoPs is harder than tailing logs on a few servers.

Whether it's worth it depends on price sensitivity, how much redirect latency matters to the product, and the traffic shape. Mass-market link shorteners and marketing redirects tend to say yes. Internal tools say no.

Notice the fallback to the origin when KV hasn't caught up. Without it, a link created a few seconds ago would 404 in faraway PoPs, the classic edge read-your-writes bug. Also notice that the click is recorded asynchronously (batched logs or a queue), so analytics never slows the redirect.

3. A/B testing and feature flags. Experiments need a sticky, unbiased assignment of each user to a variant. At the edge:

  1. Read a stable identifier: a first-party cookie, or a new random ID set in the response if none exists.
  2. Compute bucket = hash(experiment_id + user_id) mod 100.
  3. Compare it against the rollout percentages from config, which is replicated via edge KV or bundled at deploy time.
  4. Route to variant A or B, or fetch a different cached page variant (add the variant to the cache key), and set a header so analytics can attribute the response.

Doing this at the edge avoids flicker, where client-side scripts swap content after the page renders. It also keeps both variants cacheable, because the cache key includes the variant instead of busting the cache per user. Stable hashing means no lookup table is needed: the same user always lands in the same bucket in every PoP. Exposure logging is shipped asynchronously.

4. Personalisation and localisation. The CDN knows the client's approximate geolocation (country, region, city), as well as ASN, device type and Accept-Language. Edge functions use these to:

  • pick a language or currency;
  • show region-specific prices, legal banners or cookie-consent variants;
  • choose a store catalogue.

Light personalisation works best: a few variants, each cacheable, selected per request. Heavy personalisation (a feed ranked for one user) needs per-user data from the origin. One pattern is to cache the shared shell at the edge and stream in personalised fragments. Edge Side Includes (ESI, a W3C note from 2001 by Akamai and others) did this with markup tags. Modern edge functions do it with streaming HTML rewriting, such as Cloudflare's HTMLRewriter. Geolocation from IP is approximate (VPNs, mobile carriers, corporate proxies), so never base legal or security decisions on it alone.

5. Geo-routing and traffic steering. Edge logic decides which origin serves a request:

  • the nearest healthy region;
  • the region that holds this user's data (data residency, for example EU users to eu-west);
  • a canary origin for 1% of traffic;
  • a fallback origin when the primary returns errors (origin failover).

This routing is more flexible than DNS-based steering. It works per request rather than per resolver, reacts instantly instead of waiting for DNS TTLs, and can use headers, cookies and paths. It complements global load balancing (Load Balancing). Regional partitioning, where riders in Miami only ever need drivers in Miami, maps naturally onto edge routing: the edge reads the user's city or tenant and sends the request to the regional cell that owns it.

6. Image and media transformation. Phones, tablets and desktops want different sizes and formats (AVIF, WebP, JPEG). Generating every variant upfront wastes storage and compute on variants nobody requests. On-demand transforms at the edge work like this:

  1. The request names the variant, for example /img/cat.jpg?w=640&fmt=avif, or the function negotiates the format from the Accept header.
  2. On a cache miss, the edge (or a regional transform tier) fetches the original from object storage, resizes and encodes it, and caches the result.
  3. Later requests for the same variant are cache hits.

Because transforms run only on misses and the results are cached, the compute cost is per variant, not per view. Normalise and limit the allowed parameters (for example, widths from a fixed set: 320, 640, 960, 1280, 1920). Otherwise attackers can generate unlimited variants, which is a cache-busting and compute denial-of-wallet attack. Commercial options include Cloudflare Images, Fastly Image Optimizer, Akamai Image and Video Manager, and imgix. On AWS, a common pattern is CloudFront plus Lambda@Edge or a regional Lambda behind it, resizing from S3.

7. Security at the edge. WAF rules, bot detection, rate limiting, request normalisation, header sanitisation and DDoS absorption all belong at the edge. That way bad traffic dies at the PoP nearest the attacker and never reaches your region. Edge rate limiting is approximate, because counters are per PoP or loosely synchronised. That's usually acceptable for abuse protection. Precise quotas (billing limits) still need a central counter (Rate Limiting and Throttling).

8. API acceleration and edge caching of dynamic data. Many "dynamic" API responses are cacheable for seconds: a product page, a leaderboard snapshot, search results for a popular query, a dashboard panel. Caching for even 1–5 seconds with request coalescing turns 10,000 concurrent identical requests into one origin request. Time-bucketed data helps here. Consider a metrics dashboard querying weeks of data. Every completed hour or day bucket is immutable, so the edge can cache it for a long time. Only the current, still-changing bucket needs a short TTL. Splitting queries along bucket boundaries makes most of a long-range dashboard query a cache hit.

9. Server-side rendering and edge middleware. Frameworks (Next.js middleware, Remix, SvelteKit, Astro, Nuxt) can run routing, redirects, auth gates and even rendering at the edge. Middleware (redirect unauthenticated users, rewrite locales, pick experiment variants) is a great fit. Full SSR at the edge is only a win if the data it needs is also at the edge, or is a single fast fetch. Otherwise it runs into the waterfall problem described below.

Edge data stores and their consistency limits#

Copying code to 300 PoPs is easy, because code is immutable between deploys. Copying state is where the CAP theorem bites. Distance makes coordination slow: any write that must be agreed on by replicas on several continents costs at least one intercontinental RTT, 70–250 ms. Edge stores pick a point on the PACELC trade-off (if partitioned, choose availability or consistency; else choose latency or consistency) and make it explicit (Consistency Models). There are four common shapes.

1. Eventually consistent global KV. Examples are Cloudflare Workers KV, Fastly KV Store and Config Store, Vercel Edge Config, and Akamai EdgeKV.

  • Reads: fast at every PoP from a local cache or replica, typically single-digit to tens of milliseconds, and sub-millisecond for hot keys.
  • Writes: go to a central store and propagate asynchronously to PoPs. Cloudflare documents that changes may take up to about 60 seconds or more to be visible in other locations, because each PoP caches values with a TTL.
  • Write rate: limited for a single key. Workers KV allows about one write per second per key, so KV is not a counter or a queue.
  • Guarantees: no read-your-writes across PoPs, no transactions, no compare-and-set across locations. Last writer wins.

Best for: configuration, feature flags, redirect maps, allow and deny lists, translations, A/B config, static-ish lookups. That's read-heavy data where seconds-to-a-minute staleness is acceptable.

2. Single-homed strongly consistent objects. The example is Cloudflare Durable Objects. Each object has a globally unique ID, and exactly one live instance exists in the world at a time. It's created near the first request (location hints are available), and it runs single-threaded, processing requests one at a time with transactional storage attached. Storage is now SQLite-backed per object. Because there's one owner, the object gives strong consistency and serialisability for its own state without distributed consensus on the hot path. It's ideal for:

  • a chat room, a collaborative document session or a game lobby;
  • a per-user rate limiter or a per-tenant counter;
  • a WebSocket hub, or a lock or coordinator for one entity.

The limits:

  • Latency is location-dependent. Users far from the object's home pay the full RTT to it, just as with a region. The object is "near someone", not near everyone.
  • Throughput per object is bounded. One thread handles roughly hundreds to low thousands of simple requests per second, so you must shard hot entities into many objects.
  • Cross-object transactions don't exist. You compose objects with sagas or by designing so that each transaction touches one object.

This is the actor model, and single-writer partitioning, delivered as a service.

3. Replicated SQLite: single primary, many read replicas. Examples:

  • Cloudflare D1, with global read replication;
  • Turso (libSQL), with replicas and embedded replicas inside the app process;
  • LiteFS on Fly.io, which replicates SQLite pages from a primary node;
  • similar read-replica setups for Postgres near the edge (Neon read replicas, PlanetScale regions).

Writes go to one primary region, and replicas apply the change log asynchronously. Reads at a replica are fast but may be stale, by milliseconds to seconds. The usual fix is session consistency. The client carries a bookmark (a log position, LSN or commit token) from its last write. A replica serves the read only if it has applied at least that position. Otherwise it waits or forwards the read to the primary. That gives read-your-writes and monotonic reads per session without global coordination (Database Replication). The downside: writes from far users pay the RTT to the primary, and the system is only as available for writes as the primary region.

4. Globally distributed databases accessed from the edge. Examples are DynamoDB global tables, Spanner, CockroachDB and YugabyteDB multi-region, Cosmos DB, and Fauna-style systems. These give multi-region replication with either multi-master eventual consistency (DynamoDB global tables, Cosmos DB in some modes, with last-writer-wins) or consensus-based strong consistency (Spanner, CockroachDB). Strongly consistent writes still pay a cross-region quorum RTT, which is a property of physics, not of the vendor. Edge functions usually talk to them over HTTP-friendly drivers, because isolates often can't open raw TCP connections. Connection pooling proxies (Prisma Accelerate, PgBouncer-style HTTP gateways, Cloudflare Hyperdrive) exist because creating a fresh database connection from every PoP per request would add many RTTs and exhaust connections.

The guiding principle: keep invariants where the transaction is. If an operation must atomically check and update several pieces of state, do it in one ACID store and one place, and let the edge route to it. Examples: decrement inventory and create an order; move money; reserve a seat.

Splitting such state across stores or locations creates the failure modes that a two-store design with a distributed lock suffers from. Picture orders in one database and inventory in another, coordinated by a lock:

  • A crash between steps leaves inconsistency. The order was created but inventory wasn't decremented, so another user can buy the promised stock. You now need sweepers to detect and reverse half-done work.
  • Lock ordering can deadlock. User 1 holds the lock on item A and wants B, while user 2 holds B and wants A.
  • Locks across distance are slow and fragile. A lock held from Sydney on a coordinator in Virginia costs two or more long RTTs per acquisition, and lease expiry under network delays risks two holders (Distributed Locks).

A single Postgres transaction at SERIALIZABLE isolation, with both tables in one database, avoids all of this. It costs coupling (inventory and orders scale together) and the loss of a specialised store for each. In an edge architecture the same logic applies even more strongly. Put transactional state in one regional ACID database (or a single-homed object, if the invariant is per entity), and use the edge for everything around it: auth, validation, routing, caching the read side, and rendering.

The latency math of edge vs region#

Edge functions are not automatically faster. What matters is how many round trips the request makes, and to where. Model a request as:

T_total ≈ T_user→compute × (handshake RTTs + 1)
        + Σ over sequential data calls (RTT_compute→data + service time)
        + compute time

Take a user in Sydney with the data in Virginia. User to Sydney PoP is 10 ms RTT, Sydney to Virginia is 200 ms RTT, and the user to Virginia direct is 210 ms. Assume a warm connection everywhere except user to compute, a 3-RTT handshake, and 5 ms of service time per query.

DesignUser-side costData callsTotal
A. Run in Virginia, 1 DB query3 × 210 = 630 ms (2 handshake RTTs plus the request)1 × (1 ms + 5 ms), DB is local~640 ms
B. Edge terminates TLS, proxies to Virginia3 × 10 = 30 ms1 × (200 ms + 5 ms)~235 ms
C. Edge function makes 1 query to the Virginia DB30 ms1 × 205 ms~235 ms
D. Edge function makes 4 sequential queries to the Virginia DB30 ms4 × 205 = 820 ms~850 ms, worse than A
E. Edge proxies once to a Virginia function that makes 4 local queries30 ms200 ms + 4 × 6 ms~255 ms
F. Edge answers from cache or edge KV30 ms0–5 ms~35 ms

Five lessons fall out of the table:

  1. TLS termination at the edge alone (B) gives most of the win for dynamic traffic, with no code at the edge at all. This is why every serious global service puts a CDN or edge proxy in front.
  2. Moving code to the edge while the data stays central (C, D) helps only if the code makes one data call or none. Every additional sequential call costs a full long-haul RTT. Chatty code belongs next to its data (E). Cloudflare's "Smart Placement" and similar features exist precisely to run a Worker near its backend when it makes many backend calls.
  3. The big win (F) comes from answering at the edge: cache hits, edge KV, stateless logic.
  4. Parallelise unavoidable calls. If an edge function needs three independent pieces of origin data, fetching them concurrently costs one RTT, not three.
  5. Tail latency matters more than the median. Per-PoP cache hit ratios vary a lot. Small PoPs see fewer requests per key, so they miss more. Tiered caching and origin shields fix this by letting a regional tier absorb misses from many PoPs.

Real-world p50 numbers back this up. Edge-served responses typically come back in 10–50 ms worldwide. Origin-served dynamic responses for distant users run 150–400 ms.

IoT and fog computing#

For connected devices, the "edge" is the device itself and the gateway next to it. The motivation broadens from latency to bandwidth, autonomy, privacy and cost. Fog computing names the layer between devices and the cloud: gateways, on-premises servers, base stations and micro data centres. The term was introduced by Bonomi, Milito, Zhu and Addepalli in "Fog Computing and Its Role in the Internet of Things" (MCC workshop at SIGCOMM 2012). A related earlier idea is the cloudlet: a small data centre one wireless hop from mobile devices, proposed by Satyanarayanan, Bahl, Cáceres and Davies in "The Case for VM-Based Cloudlets in Mobile Computing" (IEEE Pervasive Computing, 2009). The telecom industry standardised Multi-access Edge Computing (MEC) through ETSI, which places compute inside the mobile network. AWS Wavelength is a commercial example that puts AWS compute inside 5G carrier networks.

A typical hierarchy:

What runs at each level, and why:

  • Data reduction. Consider 1,000 vibration sensors at 1 kHz with 4-byte samples. That's 4 MB/s, or about 345 GB/day. Sending per-second aggregates (min, max, mean, RMS and a few FFT bands) cuts it to roughly 100× less. Sending only anomalies plus hourly summaries cuts it by much more. Over cellular or satellite links billed per GB, that difference decides whether the product is viable. Video is the extreme case. Running object detection on-site and uploading only events and short clips turns a 4 Mbps-per-camera stream into a few kbps of metadata.
  • Local control and autonomy. Control loops (stop the conveyor if a person enters the zone, adjust a turbine's pitch) need deterministic millisecond responses and must keep working through WAN outages. The cloud sets policy and targets. The fog executes them.
  • Store-and-forward. Gateways buffer data on local disk during outages and replay it when connectivity returns. Delivery must then be idempotent, keyed by device ID plus sequence number (Idempotency and Safe Retries). The ingestion side must handle late, out-of-order data with event-time processing.
  • Protocol translation and security. Industrial devices speak Modbus, OPC UA, BACnet or CAN bus, and many can't do TLS. The gateway terminates those protocols locally and speaks authenticated TLS (MQTT or HTTPS) to the cloud. Device identity uses per-device X.509 certificates, ideally in a secure element or TPM.
  • Privacy and sovereignty. Health data, factory process data and camera footage may be legally or contractually required to stay on-site. Processing them locally and exporting only aggregates or anonymised events satisfies the requirement.

MQTT (OASIS standard; v3.1.1 in 2014 and v5 in 2019) is the dominant device-to-cloud messaging protocol. It's a lightweight publish/subscribe protocol over TCP with topic hierarchies, small headers (a fixed header of 2 bytes), persistent sessions, and three QoS levels:

  • QoS 0: at most once;
  • QoS 1: at least once;
  • QoS 2: exactly once between client and broker, via a four-part handshake.

It also offers retained messages, which give the last known value to new subscribers, and a Last Will message, which announces device disconnects. These map directly onto Delivery Guarantees: At-Most, At-Least and Exactly-Once. Brokers include Mosquitto, EMQX, HiveMQ and VerneMQ, plus cloud IoT hubs such as AWS IoT Core, Azure IoT Hub, and HiveMQ or EMQX Cloud.

Edge runtimes for fog nodes:

  • AWS IoT Greengrass and Azure IoT Edge run containers or functions on gateways, managed from the cloud.
  • K3s and KubeEdge bring lightweight Kubernetes to edge sites.
  • Balena manages device fleets.
  • TensorFlow Lite, ONNX Runtime and NVIDIA Jetson-class hardware handle on-device inference.

Fleet management (provisioning, configuration, staged OTA updates with rollback, and health monitoring of thousands of sites) is usually harder than the data path. Treat each site as cattle: an immutable image, declarative config and automatic rollback when health checks fail after an update.

Cost and limits#

Edge platforms price differently from regional compute, and their limits shape what you can build.

Pricing models. The figures below are list prices at the time of writing; verify them before relying on them.

  • Cloudflare Workers (paid): a monthly base fee that includes about 10 million requests, then roughly $0.30 per additional million requests, plus a charge for CPU time (not wall-clock time) of about $0.02 per million CPU-milliseconds. Time spent waiting on fetch() is free, which suits I/O-bound proxies.
  • Lambda@Edge: about $0.60 per million requests plus duration in GB-seconds, which is roughly 3× the per-request price of regional Lambda. CloudFront data transfer is billed separately.
  • CloudFront Functions: about $0.10 per million invocations. It's cheap because it's so limited.
  • Fastly Compute: priced on requests plus compute duration, with contract tiers common for large customers.
  • Edge KV: reads are cheap (cents to tens of cents per million), while writes are 10× or more pricier, plus storage. Durable Objects bill per request plus duration while active, plus storage.

Worked example: a redirect service. Assume 5 billion redirects per month (about 1,900/s on average, with peaks of 20,000/s).

OptionRough monthly cost (compute and requests only)Notes
Cloudflare Workers + KV, 100% at the edge5,000 M × $0.30/M ≈ $1,500, plus KV reads ≈ $2,500 at $0.50/M, ≈ $4,000Most KV reads are hot-cached, so the real figure is often lower; no origin needed for hits
CloudFront cache with 90% hit rate + origin fleetRequest fees ≈ $0.0075–0.01 per 10k HTTPS → ≈ $4,000–5,000, plus a small origin for 10% missesSimple; latency on misses ~100–250 ms
Lambda@Edge on viewer request for every hit5,000 M × $0.60/M = $3,000, plus duration ≈ $1,000+Higher latency than isolates; usually the wrong hook for this
Regional only: 3 regions × a few instancesHundreds to low thousands of dollarsCheapest compute; worst latency for far users

The lesson: edge compute is cheap per request but scales with traffic, and at billions of requests it's a real line item. Compare it with the value of the latency improvement and the origin capacity it saves. Egress (bytes out) often dwarfs compute either way.

Common limits, as orders of magnitude; check current docs:

  • CPU time per request: milliseconds to tens of seconds depending on plan and platform. The free tier of Workers allows 10 ms of CPU, and paid plans allow much more. CloudFront Functions allows about 1 ms. These are CPU budgets, not wall-clock budgets, except on Lambda@Edge, which bills and limits wall-clock.
  • Memory: about 128 MB per isolate on Workers, and 128 MB on viewer-side Lambda@Edge. Large models, big JSON parses and image processing hit this first.
  • Code size: single-digit MB compressed for isolates, tiny for CloudFront Functions (10 KB) and small for viewer-side Lambda@Edge (1 MB). You can't bundle heavy SDKs.
  • Subrequests: each request is capped on the number of outgoing fetch() calls (tens to about a thousand depending on plan).
  • APIs: no filesystem, limited or no raw TCP, no native modules, no long-lived background threads. Work after the response must be registered (for example waitUntil()) and is time-bounded.
  • Duration and connections: long-running jobs don't belong at the edge. WebSockets are supported on some platforms, but are better hosted by single-homed objects that own the connection state.

When to Use It#

Reach for edge computing when:

  • Users are globally distributed and latency is product-critical: commerce, media, gaming, ad tech, SaaS with a global audience. As a rule, if a meaningful share of users is more than 100 ms RTT from your nearest region, and the operation can be served without central state, the edge removes that cost.
  • The logic is stateless or read-mostly and runs on most requests: auth checks, redirects, rewrites, header normalisation, A/B bucketing, geo-routing, bot filtering, signed-URL validation.
  • You want to shield the origin: absorb spikes, filter abuse, coalesce requests and cache dynamic responses for seconds.
  • Responses can be transformed and cached per variant: image resizing, format negotiation, HTML rewriting, localisation.
  • Per-entity coordination fits the single-object model: chat rooms, collaborative sessions, per-user limits, WebSocket fan-out for one room. That's the Durable Objects style.
  • For IoT: bandwidth costs, intermittent connectivity, millisecond control loops, or data that must stay on-site.

Pick something else instead when:

  • Your users are concentrated in one geography. A single region (or two for DR) close to them gets you within 10–30 ms already. A plain CDN for static assets is enough.
  • Every request needs fresh, transactional data from a central database: checkout, bookings, ledgers. Use a regional service, and put only TLS termination, caching and a WAF at the edge.
  • The work is CPU- or memory-heavy: video transcoding, ML inference with big models, large report generation. Regional compute, GPUs or batch systems fit better. Edge GPU offerings exist, but they're specialised and more expensive.
  • You need the full language ecosystem: native libraries, specific runtimes, long-running processes. Use regional containers, or a metro-level platform like Fly.io.

When NOT to Use It#

  • Chatty data access from the edge. If the function makes several sequential calls to a far-away database, it's slower than running next to the database. Move the code to the data, or move the data to the edge.
  • Strong global invariants: inventory counts, unique usernames, balances, seat reservations. An eventually consistent edge store will oversell or duplicate, and a global lock is slow and fragile. Keep these in one ACID store.
  • Secrets or sensitive data the edge provider shouldn't hold, or that compliance requires to stay in specific jurisdictions. Edge code runs in many countries, so check data residency rules before caching or processing personal data in every PoP.
  • Low-traffic or internal apps. The operational complexity (another deploy target, distributed logs, platform limits) isn't paid back.
  • When debugging and observability matter more than milliseconds, early in a product's life. Start regional, measure, and move hot paths to the edge later.

How to Implement It#

  1. Measure first. Collect real-user monitoring (RUM) data: TTFB and latency by country, the share of users per region, and cache hit ratios. Identify which requests are latency-sensitive and which are cacheable.
  2. Put a CDN or edge proxy in front of everything. TLS termination, HTTP/2 and HTTP/3, a WAF and caching for static assets. This is the cheapest big win, and it needs no code.
  3. Classify request paths:
    • static (cache long, with fingerprinted URLs);
    • cacheable dynamic (cache for seconds with coalescing, or stale-while-revalidate);
    • edge-computable (stateless logic or KV lookups);
    • origin-only (transactions, personalised writes).
  4. Move edge-computable logic into edge functions: auth verification with cached JWKS, redirects, A/B bucketing, geo or tenant routing, header normalisation. Keep each function small, with no heavy dependencies.
  5. Choose edge state deliberately. Use KV for read-mostly config, with an origin fallback on misses. Use single-homed objects for per-entity coordination. Use replicated SQLite or Postgres replicas with session bookmarks for read-heavy relational data. Keep transactions in the region.
  6. Design cache keys and invalidation. Normalise query parameters, add the variant dimensions (locale, experiment bucket, device class) and nothing else. Use surrogate keys or cache tags for targeted purges, and set an explicit purge path for takedowns.
  7. Protect against abuse: whitelist the transform parameters, rate-limit per IP or token at the edge, and cap subrequests.
  8. Observability:
    • structured logs shipped asynchronously (log push to object storage or a SIEM);
    • metrics broken down per PoP and per colo;
    • distributed trace propagation (W3C traceparent) from the edge to the origin;
    • synthetic checks from many regions.
  9. Deploy safely. Edge deploys reach every PoP within seconds, so a bug is instantly global. Use gradual rollouts (percentage-based deployments), versioned scripts and instant rollback, and test with local emulators (Wrangler, Fastly's Viceroy) plus staging zones (CI/CD and Deployment Strategies).
  10. Re-measure. Compare p50, p95 and p99 latency per region and the origin offload, and check the edge bill against the expected value.

An edge function (Cloudflare Workers style) that verifies a JWT, assigns an A/B bucket, resolves a short link from KV with an origin fallback, and logs asynchronously:

export default {
  async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(req.url);
    const code = url.pathname.slice(1);
    if (!/^[A-Za-z0-9]{4,12}$/.test(code)) return new Response("Not found", { status: 404 });
 
    // 1. Optional auth for private links: verify JWT with cached public keys
    const user = await verifyJwt(req.headers.get("Authorization"), env.JWKS_URL); // null if absent or invalid
 
    // 2. Sticky A/B bucket from a hash of the user or visitor id
    const vid = user?.sub ?? getCookie(req, "vid") ?? crypto.randomUUID();
    const bucket = (await hash32(`redirect-exp-7:${vid}`)) % 100 < 10 ? "B" : "A";
 
    // 3. Edge KV first, then origin fallback for not-yet-replicated codes
    let target = await env.LINKS.get(code, { cacheTtl: 300 });
    if (!target) {
      const r = await fetch(`${env.ORIGIN}/resolve/${code}`, { headers: { "x-edge": "1" } });
      if (r.status === 404) return new Response("Not found", { status: 404 });
      target = await r.text();
    }
 
    // 4. Respond now; record the click after the response is sent
    ctx.waitUntil(env.CLICKS.send({ code, vid, bucket, country: req.cf?.country, ts: Date.now() }));
    const res = Response.redirect(target, 302);
    const out = new Response(null, res);
    out.headers.set("Set-Cookie", `vid=${vid}; Max-Age=31536000; Path=/; Secure; HttpOnly`);
    out.headers.set("X-Exp-Bucket", bucket);
    return out;
  },
};

The function needs no database connection and makes at most one origin call, on a KV miss. The click goes to a queue after the response is sent, so analytics never adds latency.

TechnologyFits when
Cloudflare Workers + KV, Durable Objects, D1, R2, QueuesFull edge platform: isolates in 300+ cities, per-entity strong state, SQLite read replicas, zero-egress object storage
Fastly Compute, KV Store, Config StoreWasm-based per-request isolation, multi-language, strong caching and purge control
AWS CloudFront FunctionsVery cheap, sub-ms header and URL logic in every CloudFront location
AWS Lambda@EdgeHeavier logic on cache misses (origin hooks), access to AWS services, Node or Python
Vercel Edge Functions and Middleware, Netlify Edge FunctionsFramework-integrated middleware (Next.js and others): redirects, auth gates, rewrites
Deno DeployIsolate-based TypeScript platform, globally distributed, web-standard APIs
Akamai EdgeWorkers and EdgeKVEnterprise CDN footprint, JS at the edge, large media and commerce customers
Fly.io (Firecracker VMs) + LiteFS, TursoFull apps and databases close to users in many regions
AWS Wavelength, Local Zones, Outposts; Azure Edge ZonesSingle-digit-ms access from 5G or metros, or on-prem AWS for data residency
AWS IoT Greengrass, Azure IoT Edge, K3s, KubeEdgeFog and gateway compute managed from the cloud
MQTT brokers: EMQX, HiveMQ, Mosquitto; AWS IoT Core, Azure IoT HubDevice messaging with QoS levels, retained messages, Last Will

Trade-offs#

OptionProsConsPick when
CDN only, static and cacheableSimple, cheap, huge offloadNo per-request logic; dynamic requests go to the originMost sites; the first step always
Edge functions, statelessLowest latency for logic; origin shielding; instant global deploysPlatform limits; vendor lock-in; harder debugging; per-request costAuth, redirects, A/B, routing, rewrites
Edge plus eventually consistent KVFast reads everywhereStale reads for ~seconds to a minute; low per-key write rates; no transactionsConfig, flags, redirect maps, deny lists
Single-homed objects, Durable Objects styleStrong consistency per entity; easy coordination; WebSocket hubsLatency to the object's home; per-object throughput cap; no cross-object transactionsChat rooms, docs, games, per-user limiters
Replicated SQLite or Postgres read replicas near usersLocal fast reads with SQL; read-your-writes via bookmarksWrites pay the RTT to the primary; replica lag; primary is a single write regionRead-heavy apps with modest writes
Multi-region full stacksFull generality; regional failoverExpensive; data replication and conflict handlingLarge global apps needing low latency for writes too
Fog and gateway processingBandwidth savings; autonomy offline; privacyFleet management; hardware ops; security of physical sitesIoT, factories, retail stores, vehicles

Common Pitfalls#

  • The edge-to-origin waterfall: sequential origin or database calls from the edge. Use one call, run the calls in parallel, or move the code to the data.
  • Read-your-writes bugs with eventually consistent KV: a user creates something and the next request, served by another PoP, can't see it. Fall back to the origin on a miss, or use session bookmarks.
  • Using KV as a database: counters, queues or frequently updated keys hit per-key write limits and last-writer-wins races.
  • Cache-key explosion: including raw query strings, user IDs or unbounded transform parameters in cache keys destroys hit rates and invites denial-of-wallet attacks.
  • Personalised responses accidentally cached and shown to other users. Mark responses private or vary the key correctly. Never cache responses with Set-Cookie for shared use.
  • Treating IP geolocation as truth for legal or security decisions.
  • Revocation blind spots with stateless JWT checks at the edge. Use short lifetimes and origin checks for sensitive actions.
  • Global blast radius: an edge deploy reaches every PoP in seconds. Use gradual rollout and fast rollback, and keep the origin able to serve if edge logic is disabled.
  • Opening a database connection per request from the edge. Use HTTP-based drivers or pooling proxies.
  • Ignoring data residency: processing or caching personal data in PoPs located in jurisdictions it shouldn't leave.
  • IoT without idempotent replay: store-and-forward after outages duplicates data unless messages carry a device ID plus sequence number.

Real-World Examples#

  • Akamai pioneered the commercial CDN and its distributed edge platform, described in "Globally Distributed Content Delivery" (Dilley et al., IEEE Internet Computing, 2002). Akamai and partners proposed Edge Side Includes (ESI) to assemble pages at the edge from cacheable fragments. That was an early form of edge computing.
  • Cloudflare Workers (launched in 2017) brought V8 isolates to CDN PoPs, later adding Workers KV, Durable Objects, D1, R2 and Queues. Cloudflare's network spans more than 300 cities.
  • Fastly Compute runs WebAssembly modules, one fresh instance per request, built on the Bytecode Alliance's Wasmtime runtime.
  • AWS offers two edge tiers on CloudFront: CloudFront Functions in every edge location for lightweight viewer logic, and Lambda@Edge in regional edge caches for heavier logic. AWS Wavelength places compute inside 5G networks, launched with Verizon.
  • Netflix Open Connect places Netflix's own cache appliances inside ISP networks and at Internet exchanges, so most video bytes travel only a short distance. That's edge content placement at massive scale.
  • Meta and Google edge networks. Meta's "Edge Fabric" (Schlinker et al., SIGCOMM 2017) and Google's "Espresso" (Yap et al., SIGCOMM 2017) describe how their PoPs terminate user connections close to users and steer egress traffic across peering links. They show that terminating connections at the edge and backhauling over a private backbone is how hyperscalers cut user latency.
  • Chick-fil-A has publicly described running small Kubernetes clusters in each restaurant for on-site IoT and kitchen workloads. It's a well-known example of retail fog computing: local autonomy, with cloud-managed fleets.
  • Edge incidents show the blast radius. In July 2019, a single WAF regular-expression rule with catastrophic backtracking drove CPU to 100% across Cloudflare's network, causing a global outage of about half an hour. In June 2021, a customer configuration change triggered a latent bug in Fastly's software, causing widespread errors across many major websites for under an hour. Global, instant deploys need gradual rollouts and kill switches.

Case studies that use this pattern#

In the Interview#

Common follow-ups:

  • "Why not run the whole app at the edge?" Because the data isn't there. An edge function making several sequential calls to a central database is slower than running in-region. Either cache or replicate the read path to the edge, or keep chatty code next to the data.
  • "A user creates a short link and immediately shares it, and a friend in another continent gets a 404. Why, and how do you fix it?" The KV write hasn't propagated to that PoP. Fall back to the origin on a KV miss, and optionally push new mappings to hot regions or warm the cache.
  • "How do you invalidate edge caches when a link is taken down for abuse?" Use an explicit purge by URL or cache tag (which most CDNs propagate within seconds), plus a KV delete, plus a short TTL for redirect responses, so the maximum staleness is bounded.
  • "How would you do rate limiting at the edge?" Count per PoP (or with a single-homed counter object per key) for abuse protection, accepting approximate global limits. Enforce billing-grade quotas centrally.
  • "For IoT, what runs on the gateway?" Protocol translation, filtering and aggregation, local control loops, ML inference, store-and-forward buffering with idempotent replay, and secure device identity. Ship aggregates and events, not raw streams.
Deep Dive: Inside Edge Runtimes: Isolates, Wasm Sandboxes and Multi-Tenant SchedulingShow

An edge PoP is a hyper-dense multi-tenant computer. It may host code from a million customers, any of which can receive a request at any moment, on a few hundred to a few thousand servers per site. The runtime design follows from three goals: near-zero cold start, tiny per-tenant overhead, and safe isolation between mutually distrustful tenants.

Why process-per-tenant doesn't work. A Node.js process idles at around 30–50 MB of RSS and takes 50–300 ms to start and load code. Keeping a million tenants warm per PoP would need tens of TB of RAM. Spinning them up on demand would add hundreds of milliseconds to the first request for every tenant that went cold. Containers make this worse, and micro-VMs (designed for regional FaaS) improve it but are still about 100 ms to boot. So isolation has to move inside a process.

How a V8 isolate gives isolation. Each isolate has its own heap, its own garbage collector state and its own global object. JavaScript code can't name memory outside its heap, because the language has no pointers, and V8's JIT enforces bounds and type checks. A runtime process holds many isolates and a thread pool. A request for tenant X is dispatched to X's isolate, which runs to completion or until it awaits I/O. Then the thread moves on to another isolate. Isolates are created by deserialising a snapshot of an initialised V8 heap, then compiling or loading the tenant's script, which takes milliseconds. Unused isolates are evicted under memory pressure, using LRU-like policies.

Resource control works like this:

  • CPU: the runtime measures CPU time per request and terminates scripts that exceed their budget. V8 supports interrupting a running script.
  • Memory: heap limits are enforced per isolate.
  • Wall-clock: I/O waits are unbounded or loosely bounded, but subrequest counts are capped.

Defending against side channels. Isolates share an address space, so a language-level escape (a V8 bug) or a microarchitectural side channel (Spectre) could leak another tenant's data. Defences are layered:

  • prompt patching of V8, with the platform tracking Chrome's security releases;
  • removing precise timers: Date.now() and performance.now() don't advance during synchronous execution, which makes timing attacks much harder to measure;
  • disallowing SharedArrayBuffer and multi-threading, which could build high-resolution timers;
  • OS-level sandboxing of the runtime process (seccomp, namespaces), so even a full V8 escape lands in a jail with no secrets;
  • dynamic process isolation: moving tenants whose behaviour looks like an attack into separate processes;
  • grouping tenants into processes by trust level.

The isolation is strong but not hardware-backed. That's why some regulated workloads still prefer VM-isolated compute.

How Wasm sandboxes work. A Wasm module can access only its own linear memory, a contiguous byte array, plus imported host functions. Every load and store is an offset into that array. On 64-bit hosts, runtimes reserve a large virtual region (for example 4 GiB plus guard pages for 32-bit Wasm) so that out-of-bounds accesses hit unmapped pages and trap. That makes bounds checks almost free. Control flow is structured (no arbitrary jumps), function calls go through typed tables, and the module can't inspect its own stack. Wasm is therefore memory-safe with respect to the host, even if the source language (C, C++) isn't memory-safe internally. A buffer overflow can corrupt the module's own memory, but not escape it.

Ahead-of-time compilation (Cranelift in Wasmtime) turns modules into native code at deploy time. Instantiation then just maps memory and initialises globals, which takes tens of microseconds. That's cheap enough to create a new instance per request and throw it away afterwards, which gives:

  • no cross-request state leakage (no globals left over from the last user);
  • no need for warm pools;
  • fault containment: a panic kills only one request.

The cost is that per-request initialisation work (parsing config, building tables) is repeated every time. Pre-initialisation tools such as Wizer snapshot an already-initialised module so that this work happens at build time.

Scheduling and fairness. In a multi-tenant PoP, one tenant's CPU-heavy script mustn't starve others. Runtimes enforce per-request CPU limits, cap concurrent requests per isolate or per tenant, and spread tenants across machines and processes. Heavy tenants get more instances. Within a metro, a request may be load-balanced to any machine. The runtime tries to route repeat requests for the same tenant to machines where its code is already loaded, which is cache affinity, so cold starts stay rare even with millions of tenants.

The cost comparison. With isolates, the marginal memory of an idle tenant is roughly its compiled code plus a small heap: a few MB, or zero if evicted. A request on a loaded isolate costs microseconds of dispatch overhead. That's why edge platforms can price at about $0.30 per million requests while running code in every PoP. That density would be impossible with a process or VM per tenant. The trade is the constrained programming model: web APIs only, CPU budgets, no native code, and memory caps.

Deep Dive: Consistency Engineering at the Edge: Bounded Staleness, Sessions and Single OwnersShow

Edge architectures have to state precisely how stale a read can be and who owns each write. Three techniques cover almost every design.

1. Bounding staleness for cached and KV data. Suppose the origin updates a value at time t₀. A PoP that cached the old value at time t_c with TTL T will serve it until t_c + T. Eventually consistent KV adds a propagation delay P before the new value even reaches the PoP's backing store. The worst-case staleness seen by a user is:

max_staleness ≈ P + T
  P = replication / propagation delay of the edge store (seconds to ~60 s)
  T = local cache TTL at the PoP (e.g. cacheTtl = 300 s)
→ with T = 300 s, a deleted link could still redirect for up to ~6 minutes

There are three levers:

  • Shorten T for keys that must change quickly. This costs more central reads and lower hit ratios.
  • Push invalidations (purge by key or tag) on writes, so effective staleness becomes the purge propagation time, usually seconds. Keep T long as a fallback in case a purge is lost.
  • Version the keys: write config:v42, then flip a tiny pointer key. Readers that see the new pointer read immutable data that never goes stale.

stale-while-revalidate (RFC 5861) lets the edge serve a stale copy while fetching a fresh one in the background. Latency stays flat, and staleness is bounded by the revalidation window. stale-if-error lets the edge keep serving the cached copy when the origin is down, which is graceful degradation for free (Designing for High Availability).

2. Session guarantees with bookmarks. Strong global consistency is expensive, but users mostly need four session guarantees, formalised by Terry et al. in "Session Guarantees for Weakly Consistent Replicated Data" (PDIS 1994):

  • read-your-writes;
  • monotonic reads;
  • writes-follow-reads;
  • monotonic writes.

With a single-primary replicated database, read-your-writes and monotonic reads need only a log position token:

The client keeps the maximum position it has seen, and sends it with every request. Any replica at or beyond that position can serve it. This gives per-user consistency at local-read latency for almost all requests. Only reads immediately after a write, at a lagging replica, pay extra. Cloudflare D1's Sessions API, Turso's replica sync and Postgres LSN-based routing implement variants of this. Other sessions may still see older data. That's acceptable for most apps, though not for invariants that span users.

3. Single owners for invariants. When an invariant spans requests from many users, someone must serialise the updates. Examples: no more than 100 tickets for this event; one winner per auction; the document's operation order. The options:

  • A regional ACID database. Latency for far users is the RTT to that region, typically 100–250 ms for a write. That's acceptable for checkout-like flows.
  • A single-homed object per entity (Durable Objects style). The object lives where its users mostly are. A Paris-centric chat room is fast for Parisians, and a global room is equally fair or unfair for everyone. Per-entity throughput is bounded by one thread, so a 1-million-attendee event must split into sub-objects. For example, shard inventory into 100 sub-pools of 1,000 tickets, each with its own object, and accept slight unfairness at the end.
  • Commutative and mergeable state (CRDTs) for counters, sets and collaborative text. Replicas at every PoP accept writes locally and merge later, with no owner needed (Conflict Resolution, OT and CRDTs). CRDTs can't enforce upper bounds such as "no oversell", because two replicas can each sell the last ticket. Those need an owner or escrow: pre-allocate a budget of units to each region, so each region can sell its share locally and rebalance asynchronously.

Why global strong consistency is slow, in numbers. A Paxos or Raft write with replicas in Virginia, Frankfurt and Singapore needs a majority ack. The leader waits for the faster of the two followers. Virginia–Frankfurt is about 90 ms RTT and Virginia–Singapore about 220 ms, so with a Virginia leader a commit takes about 90 ms plus disk time. A client in Sydney adds about 200 ms to reach the leader. Total: about 300 ms per strongly consistent write. Spanner-style systems put the leader for each split near its writers to cut this, but physics bounds every design (Consensus: Raft and Paxos). This is why edge architectures push writes toward one owner close to the writers, and serve reads from replicas or caches close to the readers.

Deep Dive: Anycast, Tiered Caching and the Economics of Edge PlacementShow

Anycast routing. Most large CDNs and edge platforms announce the same IP prefixes from every PoP via BGP. Each ISP's routers pick the "closest" announcement by BGP path selection, which reflects AS-path length and the operators' local policy, not pure geography. A user's packets therefore land at a nearby PoP without any DNS tricks.

Anycast's benefits:

  • automatic failover: withdraw the announcement and traffic shifts to the next PoP in seconds to minutes;
  • natural DDoS dilution: attack traffic is spread across all PoPs;
  • simple client config: one IP address works everywhere.

Its downsides:

  • Path selection can be suboptimal. A user can land at a farther PoP because of peering policy.
  • Route changes mid-connection can move a TCP flow to a different PoP, which doesn't have the connection state. In practice, routes are stable enough for typical short HTTP connections, and long-lived flows (WebSockets, large downloads) may need extra engineering.

The alternative is geo-DNS: authoritative DNS returns a PoP-specific IP based on the resolver's location, or on the client subnet via EDNS Client Subnet. It allows finer control, but it depends on resolver location and DNS TTLs. Many providers combine the two.

Tiered caching and hit-ratio math. Assume object popularity follows a Zipf distribution (the i-th most popular object gets a share of requests proportional to 1/iˢ, with s about 0.6–1.0 for web content). A PoP that can hold the top C objects of a catalogue of N gets a hit ratio of roughly:

hit_ratio(C) ≈ H(C, s) / H(N, s),  where H(n, s) = Σ_{i=1..n} 1 / i^s
For s = 1 (harmonic): H(n, 1) ≈ ln(n) + 0.577
N = 100 M objects, C = 1 M objects at the PoP:
  hit ≈ (ln 1e6 + 0.577) / (ln 1e8 + 0.577) ≈ 14.4 / 19.0 ≈ 76%
Regional tier with C = 20 M objects absorbing misses from many PoPs:
  overall ≈ (ln 2e7 + 0.577) / 19.0 ≈ 17.4 / 19.0 ≈ 92%

Small PoPs also suffer from low request counts. A long-tail object requested once a day per PoP has always expired by its next request. A tiered cache (PoP → regional tier → origin shield) aggregates the misses from many PoPs, so long-tail objects stay warm in the middle tier. The origin sees requests only for objects that miss everywhere, often under 5% of the total. Request coalescing at each tier means a sudden burst for one new object (a viral video, a newly published page) creates one origin fetch per tier, not thousands. That's thundering-herd protection (Caching Fundamentals).

Placement economics: when does an edge function pay for itself? Think of it as value against cost per request:

value_per_request ≈ Δlatency × (business value per ms) + origin_cost_saved
cost_per_request  ≈ edge_request_fee + edge_cpu_fee + extra_egress − origin_egress_avoided

The business value of latency is product-specific. Published e-commerce studies have long reported that conversion drops measurably as page load time grows, but the exact figures vary by site and era, so measure your own with A/B tests. Origin savings, on the other hand, are easy to estimate. Every request answered at the edge avoids origin compute and database load, and often reduces cross-region data transfer.

A concrete heuristic: at about $0.30–0.60 per million requests, the edge cost is $0.0000003–0.0000006 per request. If a request served at the edge saves even 10 ms for a user 200 ms away, and you have any reason to value that, the edge function is nearly free. The expensive cases are:

  • heavy CPU at the edge (image transforms on every request instead of cached variants);
  • high edge KV write volumes;
  • egress-heavy responses, where bandwidth pricing dominates regardless of compute.

Choosing the layer. A practical placement order is:

  1. Cache everything cacheable at the edge.
  2. Move stateless decisions (auth, routing, A/B, redirects) to edge functions.
  3. Move read-mostly data to edge KV or replicas, with an origin fallback.
  4. Give per-entity real-time state a single home near its users.
  5. Keep transactions and heavy computation in the region.
  6. For devices, push filtering and control to the fog.

Each step only happens when measurements show the previous layer isn't enough. That ordering keeps the system as simple as the latency requirements allow, which is exactly the trade-off interviewers want to hear you reason about (Latency, Throughput and Performance vs Scalability).

Key Takeaways#

  • Physics sets the floor. Fibre costs about 1 ms RTT per 100 km, and a fresh HTTPS connection costs about 3 RTTs. Serving from a PoP 10 ms away instead of a region 200 ms away is the biggest latency lever for global users.
  • CDN, edge and region are different layers. CDNs cache bytes, edge functions run your logic in PoPs, and regions hold the source of truth and heavy computation.
  • Edge runtimes trade generality for density. V8 isolates and Wasm instances start in milliseconds or microseconds and cost very little per tenant, in exchange for CPU, memory, size and API limits.
  • Best edge use cases are stateless or read-mostly: auth checks, redirects, A/B bucketing, personalisation variants, geo-routing, image transforms on cache misses, bot and abuse filtering.
  • Edge state has explicit limits. KV is eventually consistent (seconds to about a minute) with low per-key write rates. Single-homed objects are strong per entity but are only as close as their home. Replicated SQLite gives local reads, with writes going to one primary and session bookmarks for read-your-writes.
  • Keep invariants in one place. Transactions spanning several records belong in one ACID database or one owner object. The edge routes to it.
  • Beware the waterfall. Sequential calls from the edge to a far-away database are slower than in-region code, so move chatty code to the data.
  • IoT and fog process data near devices for bandwidth, autonomy, privacy and real-time control, using MQTT, store-and-forward with idempotent replay, and cloud-managed fleets.
  • Costs and risks: per-request pricing grows with traffic, and global deploys reach every PoP in seconds, so roll out gradually and keep the origin able to work without the edge.