Wasm on the Edge (Cloudflare Workers)

Cloudflare Workers run JavaScript and Wasm in V8 isolates in many cities, with cold starts almost always hidden (isolates load during the TLS handshake…

Guests in London and in Frankfurt both open Mist Homestay's price page. If the calculator lives on one central server, their requests have a long way to travel first. At the edge, your code runs on small servers spread across many cities, close to visitors. Cloudflare Workers run JavaScript, and the Wasm that JavaScript imports, in Cloudflare's data centres using V8 isolates, the same engine as Chrome.

So Mrs. Sri's price calculator is left at a travel agent's counter in every city, and guests do not have to phone the homestay for a price. Each agent has a small booth in a building shared with other agents, and the building's rules are strict: tools must arrive ready-made from home, not be assembled at the counter, and each guest may only be served for so many minutes. The counter is an edge data centre, the booth is an isolate, the ready-made tool is a Wasm module that ships inside the bundle, and the serving minutes are the CPU time limit.

The edge and isolates

The plan limits according to Cloudflare's limits page (updated 8 October 2026, read 11 October 2026):

Limit Workers Free Workers Paid
CPU time per request 10 ms 30 seconds by default, raisable to 5 minutes
Memory per isolate 128 MB 128 MB
Worker size 64 MiB 64 MiB
Startup (running the global scope) 1 second 1 second
Subrequests per request 50 10,000

Worker size counts the uncompressed bundle; the old limits based on compressed size no longer apply. CPU time is processor time actually used, not time spent waiting on a fetch.

Wasm modules in a Worker: imported, not compiled

Workers forbid creating code from data at runtime: eval, new Function, WebAssembly.compile, WebAssembly.compileStreaming, WebAssembly.instantiateStreaming, and WebAssembly.instantiate with a buffer. The Wasm module has to ship in the bundle. wrangler uploads the .wasm file with the Worker, and the Workers runtime compiles it, not your code:

import wasmModule from './misty-edge.wasm'; // the Workers runtime hands over an already compiled WebAssembly.Module
const wasm = new WebAssembly.Instance(wasmModule, {}).exports; // once per isolate, reused by every request

This is a Worker that tries the Playground's way, run with wrangler dev (wrangler 4.149.0) on the laptop:

$ curl -i "http://127.0.0.1:8797/?nights=2"
HTTP/1.1 500 Internal Server Error
Content-Length: 96
Content-Type: application/json

{"error":"CompileError: WebAssembly.instantiate(): Wasm code generation disallowed by embedder"}

The Playground way does not run in a Worker. The same error comes out for WebAssembly.compile(bytes) and new WebAssembly.Module(bytes), and new Function fails with EvalError: Code generation from strings disallowed for this context. new WebAssembly.Instance(wasmModule) and WebAssembly.instantiate(wasmModule) with an imported module are still allowed.

The price and thumbnail endpoint

misty-edge.wasm is a small no_std Rust crate, 942 bytes: stayPrice from the wasm-pack lesson, and thumbnail with area averaging from the image-processing lesson.

/// Total stay: nights × price per night.
#[unsafe(export_name = "stayPrice")]
pub extern "C" fn stay_price(nights: i32, price_per_night: i32) -> i32 {
    nights * price_per_night
}
// thumbnail(src, sw, sh, dst, dw, dh): the same as resize_area in photolab.wasm

The core of the Worker (src/index.js), with a wrangler.jsonc holding "main": "src/index.js" and "compatibility_date": "2026-10-01":

const worker = {
  async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === '/price') {
      const room = ROOMS[url.searchParams.get('room')];
      const nights = Number(url.searchParams.get('nights'));
      if (!room) return Response.json({ error: 'unknown room' }, { status: 404 });
      if (!Number.isInteger(nights) || nights < 1 || nights > 30) return Response.json({ error: 'nights must be 1 to 30' }, { status: 400 });
      return Response.json({ room: room[0], nights, pricePerNight: room[1], total: wasm.stayPrice(nights, room[1]) });
    }
    if (url.pathname === '/thumbnail') {
      const w = Number(url.searchParams.get('w') || 200);
      if (![100, 200, 400].includes(w)) return Response.json({ error: 'w must be 100, 200 or 400' }, { status: 400 });
      const h = Math.round((w * H) / W);
      if (!photoReady) {
        wasm.memory.grow(Math.ceil((DST + 400 * 267 * 4 - SRC) / 65536)); // enough for the largest thumbnail
        new Uint8Array(wasm.memory.buffer).set(terraceRoomPhoto(), SRC);
        photoReady = true;
      }
      wasm.thumbnail(SRC, W, H, DST, w, h);
      const body = await png(new Uint8Array(wasm.memory.buffer, DST, w * h * 4), w, h);
      return new Response(body, { headers: { 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=86400' } });
    }
    return Response.json({ error: 'not found' }, { status: 404 });
  },
};

export default worker;

Its real output from wrangler dev:

$ curl -i "http://127.0.0.1:8799/price?room=terrace&nights=2"
HTTP/1.1 200 OK
Content-Length: 68
Content-Type: application/json

{"room":"Terrace Room","nights":2,"pricePerNight":3500,"total":7000}
$ curl -s -o t200.png -w "w=200 %{http_code} %{content_type} %{size_download} bytes %{time_total}s\n" "http://127.0.0.1:8799/thumbnail?w=200"
w=200 200 image/png 2510 bytes 0.050581s

The wrangler log for three thumbnail requests in a row: GET /thumbnail 200 OK (48ms), then (7ms), then (8ms). The first request draws the 3,840,000-byte photo and grows the memory; the later ones only resize and encode the PNG. The 400-wide thumbnail is 4,721 bytes, the 100-wide one 1,330 bytes. The PNG's size depends on the deflate implementation: the same code gives 2,510 bytes in Chromium 147 too, 2,594 bytes in WebKit 26.4 and 2,477 bytes in Firefox 146, all the same picture.

📌 workers-rs

A Worker can also be written entirely in Rust with the worker crate and the worker-build build tool (used in this lesson: 0.8.7, as of October 2026): a Rust function with the #[event(fetch)] attribute becomes its handler, and wasm-bindgen generates the JavaScript in between. A new project is created with cargo generate cloudflare/workers-rs. For this lesson's endpoint, a JavaScript Worker with one small Wasm module is enough.

📌 Other edge runtimes

Deploy

wrangler deploy uploads the Worker together with its .wasm module to Cloudflare, after wrangler login. This lesson only ran wrangler dev on the laptop: workerd, the same runtime as production, but local. One difference matters: locally, the CPU limit is not enforced. A 120 ms CPU loop in wrangler dev finished normally, while the Free plan's limit is 10 ms.

⚠️ Mistakes that make a Worker fail or hit a limit

TL;DR: Cloudflare Workers run JavaScript and Wasm in V8 isolates in many cities, with cold starts almost always hidden (isolates load during the TLS handshake, 99.99% of requests are warm). A Wasm module is imported from a .wasm file (a WebAssembly.Module already compiled by the Workers runtime), with new WebAssembly.Instance(wasmModule, {}) once in the global scope; compiling from bytes at runtime is refused: Wasm code generation disallowed by embedder. The Mist Homestay endpoint: /price?room=terrace&nights=2 returns {"total":7000} (cents) from stayPrice, /thumbnail?w=200 returns a 2,510-byte PNG from thumbnail (area average), 48 ms on the first request then 7 to 8 ms. Plan limits (October 2026): CPU 10 ms (Free) and 30 seconds up to 5 minutes (Paid), 128 MB memory, 64 MiB Worker, 1 second startup. Run it locally with wrangler dev, deploy with wrangler deploy. Other runtimes: Fastly Compute (Wasmtime), Deno (.wasm imports since 2.1), Vercel (?module, now recommending Node.js), Fermyon Spin (Akamai).

⚡ Isolates, not containers

Meaning: Cloudflare Workers run JavaScript and Wasm in V8 isolates, many isolates in one process, in data centres close to visitors. Wasm fits here: it starts fast, runs in the same sandbox as its JavaScript, and can be written in Rust, C, C++ or Go.

⚡ Import the module, don't compile it yourself

Write:

import wasmModule from './misty-edge.wasm'; // the Workers runtime hands over an already compiled WebAssembly.Module
const wasm = new WebAssembly.Instance(wasmModule, {}).exports; // once per isolate, reused by every request
Guess first: does WebAssembly.instantiate(bytes) from a Uint8Array, the Playground's way, run in a Worker?

It does not: CompileError: WebAssembly.instantiate(): Wasm code generation disallowed by embedder. Workers forbid creating code from data at runtime, so the .wasm has to ship in the bundle.

Meaning: wrangler uploads the .wasm file with the Worker, and the Workers runtime compiles it.

⚡ Do it once per isolate

Meaning: The instance, the SRC and DST addresses and the photo in memory are set up once in the global scope, then reused by every request. Compute the addresses again on every request and the memory keeps growing until it hits the isolate's 128 MB limit.

⚡ A CPU limit your laptop doesn't show

Meaning: On the Free plan, the CPU limit is 10 ms per request. wrangler dev on the laptop does not enforce it: a 120 ms CPU loop still finishes normally. Check the dashboard after wrangler deploy.

What you will learn