valfz

Workers from first principles

What a Worker is

How Cloudflare runs your code in V8 isolates, what that means for state and startup, and which limits to design around.

lesson
01 of 08
read
8 min

A Worker is a JavaScript module that Cloudflare loads into a V8 isolate and calls once per event, usually an HTTP request. You do not start a process, open a port or keep anything alive. That changes how long your variables live and what your code may do at startup, and it puts hard limits on the work one request can do. This lesson explains the model and demonstrates each consequence with a few lines of code.

Isolates instead of processes

A Node.js service is an operating system process. It boots a runtime, loads your code, binds a socket and runs until something stops it. Running more copies means paying the runtime’s startup time and memory again for each one.

The Workers runtime, workerd, is one process that hosts many isolates. An isolate is a V8 heap with its own global scope. It holds one Worker’s code and data, and it cannot read another isolate’s memory. The JavaScript engine is started once and shared, so creating an isolate costs far less than creating a process. That is what lets Cloudflare load your Worker on demand in whichever data center a request arrives at, instead of keeping a copy running everywhere. How Workers works is Cloudflare’s own description of the design.

What you get in exchange is a sandbox with a short list of capabilities. There is no port to listen on and no local disk that outlives the isolate, and nothing promises that the isolate serving this request will serve the next one.

The life of a request

  1. A request for your hostname reaches a Cloudflare data center.
  2. The runtime looks for an isolate on that machine with your Worker loaded. If there is none, it creates one and evaluates the top level of your module. This startup phase must finish within one second.
  3. The runtime calls your fetch handler with the request and awaits the Response.
  4. Once the response has been sent, promises registered with ctx.waitUntil() may keep running for up to 30 seconds.
  5. The isolate stays in memory and receives later requests, several at a time if they overlap, until the runtime evicts it.

Eviction is routine and silent. The documentation names resource pressure on the machine and a Worker exceeding its own limits as causes. Write every handler as if it might be the first call this isolate has seen.

A throwaway Worker for experiments

The snippets below are short enough to follow by reading. To run them, create a scratch project and start its dev server (lesson 2 explains what the first command generates):

pnpm dlx cf@1.0.0-rc.6 init hello --package-manager pnpm
cd hello
pnpm exec cf dev --port 8791

Paste each snippet over the contents of src/index.ts. The dev server reloads the module when you save.

Module scope outlives a request

src/index.ts
let hits = 0;
let isolateId: string | undefined;

export default {
	fetch() {
		isolateId ??= crypto.randomUUID();
		hits += 1;
		return Response.json({ isolateId, hits });
	},
} satisfies ExportedHandler;

Run curl http://localhost:8791/ three times:

{"isolateId":"bf54878f-7638-4303-b033-542c5253c818","hits":1}
{"isolateId":"bf54878f-7638-4303-b033-542c5253c818","hits":2}
{"isolateId":"bf54878f-7638-4303-b033-542c5253c818","hits":3}

hits survives between requests because the module was evaluated once and the isolate kept its globals. Save the file again and the dev server evaluates the module from the top, which is also what a new isolate does in production:

{"isolateId":"26a5983b-959f-4ae0-a983-339632205f18","hits":1}

In production many isolates run at once across data centers, and each has its own hits. The counter tells you how many requests one isolate happened to see. Module scope is a cache whose lifetime you do not control. It is a good home for values that are expensive to build and harmless to lose, such as a compiled pattern or a parsed lookup table, and the wrong place for anything you would call data.

Requests interleave

An isolate runs one thread, but it does not finish one request before starting the next. Every await is a point where another request’s code can run. In this handler scheduler.wait(100), the runtime’s promise-based sleep, stands in for a slow database call:

src/index.ts
let currentPath = "";

export default {
	async fetch(request) {
		currentPath = new URL(request.url).pathname;
		await scheduler.wait(100);
		return new Response(`you asked for ${currentPath}\n`);
	},
} satisfies ExportedHandler;

Send two requests at the same time:

curl http://localhost:8791/alice & curl http://localhost:8791/bob; wait
you asked for /alice
you asked for /alice

Both handlers wrote the same variable, both waited, and both read whichever value was written last. Replace the path with a user ID and this is one user receiving another user’s response. Data that belongs to a request stays in local variables and function arguments.

What module scope may not do

Moving the random ID to the top level looks like a harmless cleanup:

src/index.ts
let hits = 0;
const isolateId = crypto.randomUUID();

export default {
	fetch() {
		hits += 1;
		return Response.json({ isolateId, hits });
	},
} satisfies ExportedHandler;

cf dev serves it without complaint. In a second terminal, build the Worker and run the built output instead:

pnpm exec cf build
pnpm exec vp preview --port 8794
...
service core:user:hello: Uncaught Error: Disallowed operation called within global scope. Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope. To fix this error, perform this operation within a handler. https://developers.cloudflare.com/workers/runtime-apis/handlers/
  at file:///bundle/index.js:3:24
...

The runtime evaluates module scope before any request exists, and during that phase it refuses network I/O, timers and random numbers. The dev server hides this because it loads your module lazily, inside the first request. vp preview belongs to Vite+, the toolchain cf dev delegates to. It runs the built bundle the way production does, which makes it the local check to trust for startup behavior.

The clock is stopped during startup as well: in the built Worker, Date.now() at module scope returns 0. Inside a handler it returns the time of the last I/O and, in production, does not advance while your code computes. That is a defense against timing side channels, described in the security model. The local runtime lets the clock run during computation, so a Date.now() stopwatch around a loop reports a real duration on your machine and zero in production.

The fix for the snippet is the lazy form from the first example: isolateId ??= crypto.randomUUID() inside the handler.

Limits that shape the design

These numbers come from the limits page as of November 2026.

Limit Workers Free Workers Paid
CPU time per request 10 ms 30 s by default, up to 5 min
Memory per isolate 128 MB 128 MB
Startup time 1 s 1 s
Subrequests per request 50 10,000 by default
Requests 100,000 per day no daily limit
Work after the response (waitUntil) 30 s 30 s

CPU time counts only the time your code is executing. Waiting on fetch(), a KV read or a database query does not count, and an HTTP request has no wall-clock limit while the client stays connected. A handler that spends two seconds awaiting slow APIs uses almost no CPU time. A handler that resizes an image in plain JavaScript is unlikely to fit in 10 ms. The same page puts the average Worker at about 2.2 ms of CPU per request. When a Worker exceeds its CPU or memory limit, the client receives Cloudflare error 1102.

Memory is counted per isolate, across every request it is serving at that moment. That is one more reason not to accumulate data in module scope, and the reason the documentation recommends streaming large bodies instead of buffering them.

Lesson 2 creates the project used for the rest of the course and walks through every file cf init generates.

Exercises

  1. Put const loadedAt = Date.now(); at module scope and return { loadedAt, now: Date.now() } from the handler. Predict both values under cf dev and under vp preview, then check. A correct run shows two real timestamps under cf dev and "loadedAt":0 under the preview.
  2. Fix the interleaving bug without removing the 100 ms wait. The result is correct when the concurrent curl command prints one line for /alice and one line for /bob on every run.
  3. Use module scope for what it is good at. Build a Map with 10,000 entries on the first request, keep it in a module-level variable, and return { "cached": false } from the request that built it and { "cached": true } from later ones. Check that saving the file resets the answer to false once.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are