A Worker is not a server
How the Workers execution model differs from a long-running Node process: isolates, module scope, waitUntil and CPU limits, with each bug reproduced locally.
- topic
- cloudflare workers
- date
- read
- 20 min
A Node server is a process you start. It owns its memory, listens on a port, writes to a disk, and keeps running until something stops it. A Cloudflare Worker has none of those. The runtime loads your module into a V8 isolate and calls an exported handler once per event, and how long that isolate lives is the runtime’s decision. Code written with the first model in mind still deploys and still passes a manual test, so the bugs show up later, under real traffic: one user’s data in another user’s response, or an audit log with gaps.
This article reproduces those bugs locally and fixes them. Everything was run with cf 1.0.0-rc.6 (the Cloudflare CLI), @cloudflare/vite-plugin 2.0.0-rc.6 and workerd 1.20261127.1 on Node 24.22.2, with compatibility date 2026-11-23. The project comes from cf init, and each example replaces src/index.ts while the dev server keeps running:
pnpm dlx cf@1.0.0-rc.6 init not-a-server --package-manager pnpm
cd not-a-server
pnpm exec cf dev --port 8793 --host 127.0.0.1One module, many requests
Start with a counter at module scope.
let hits = 0;
export default {
fetch() {
hits += 1;
return new Response(`hits: ${hits}\n`);
},
} satisfies ExportedHandler;curl -s http://127.0.0.1:8793/
curl -s http://127.0.0.1:8793/
curl -s http://127.0.0.1:8793/hits: 1
hits: 2
hits: 3The module was evaluated once, and the same isolate handled all three requests, so hits survived between them. That is the sharing rule in full: module scope belongs to the isolate and is visible to every request the isolate serves, including requests that overlap in time. The request and ctx arguments are created for each invocation.
How long the isolate lives is outside your control. Run touch src/index.ts and ask again:
hits: 1Locally, a changed file makes the dev server evaluate the module again. In production the same reset follows a deploy, an eviction because the host machine is short on resources, or the isolate crossing its 128 MB memory limit. Requests also spread over many isolates on many machines, and the documentation is explicit that there is no guarantee two requests reach the same one. A module-level counter therefore counts what one isolate has seen since it started. State that has to be correct or shared goes in a binding such as KV, D1 or a Durable Object.
The leak: a per-request value at module scope
A wrong counter is a small problem. The same mechanism applied to per-request data puts one user’s value in another user’s response. The usual route to this bug on Workers is convenience: the request and the bindings arrive as handler arguments, and a module-level variable looks like a cheap way to reach them from deeper in the call stack.
let currentUser = "";
async function loadGreeting(delayMs: number): Promise<string> {
// Stands in for a database or API call.
await scheduler.wait(delayMs);
return `Hello, ${currentUser}`;
}
export default {
async fetch(request) {
const url = new URL(request.url);
currentUser = url.searchParams.get("user") ?? "anonymous";
const delayMs = Number(url.searchParams.get("delay") ?? "0");
const greeting = await loadGreeting(delayMs);
return new Response(`${greeting}\n`);
},
} satisfies ExportedHandler;One request at a time, it behaves:
curl -s 'http://127.0.0.1:8793/?user=alice'
curl -s 'http://127.0.0.1:8793/?user=bob'Hello, alice
Hello, bobNow overlap them. Alice’s request spends 500 ms in its pretend database call, and Bob’s request arrives 100 ms in:
curl -s 'http://127.0.0.1:8793/?user=alice&delay=500' &
sleep 0.1
curl -s 'http://127.0.0.1:8793/?user=bob'
waitHello, bob
Hello, bobThe first line is Bob’s response. The second arrives half a second later. It belongs to Alice, and it greets Bob. An isolate runs one event loop on one thread, so while Alice’s handler was suspended at its await, Bob’s handler ran and overwrote currentUser. A Node server with the same global variable has the same bug, and in both places it passes any test that sends one request at a time.
The fix is to keep per-request data in local variables and pass it down:
-let currentUser = "";
-
-async function loadGreeting(delayMs: number): Promise<string> {
+async function loadGreeting(user: string, delayMs: number): Promise<string> {
// Stands in for a database or API call.
await scheduler.wait(delayMs);
- return `Hello, ${currentUser}`;
+ return `Hello, ${user}`;
}
export default {
async fetch(request) {
const url = new URL(request.url);
- currentUser = url.searchParams.get("user") ?? "anonymous";
+ const user = url.searchParams.get("user") ?? "anonymous";
const delayMs = Number(url.searchParams.get("delay") ?? "0");
- const greeting = await loadGreeting(delayMs);
+ const greeting = await loadGreeting(user, delayMs);
return new Response(`${greeting}\n`);
},
} satisfies ExportedHandler;The same two overlapping requests now get their own answers:
Hello, bob
Hello, aliceWhen threading an argument through every call is impractical (a logger that wants the request ID, say), AsyncLocalStorage gives each request its own slot that follows the request across await:
import { AsyncLocalStorage } from "node:async_hooks";
const requestUser = new AsyncLocalStorage<string>();
async function loadGreeting(delayMs: number): Promise<string> {
// Stands in for a database or API call.
await scheduler.wait(delayMs);
return `Hello, ${requestUser.getStore()}`;
}
export default {
async fetch(request) {
const url = new URL(request.url);
const user = url.searchParams.get("user") ?? "anonymous";
const delayMs = Number(url.searchParams.get("delay") ?? "0");
return requestUser.run(user, async () => {
const greeting = await loadGreeting(delayMs);
return new Response(`${greeting}\n`);
});
},
} satisfies ExportedHandler;It gives the same correct output under the overlap test. The storage object lives at module scope, and the value inside it is per request. At this compatibility date the node: import needs no flag at runtime. The type checker does need @types/node installed and "node" added to types in tsconfig.json.
What module scope is good for
Module scope is the right place for a value that is the same for every request and that costs only time to rebuild. Parsed configuration and imported cryptographic keys both qualify. Here the Worker signs request bodies with an HMAC key and imports the key once per isolate. Declare the secret in the configuration (the file itself is the subject of Configuration is code):
import { bindings, defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };
export default defineConfig({
worker: {
name: "not-a-server",
compatibilityDate: "2026-11-23",
entrypoint,
env: {
SIGNING_SECRET: bindings.secret(),
},
},
});Restart the dev server with a value for the secret in its environment:
SIGNING_SECRET=local-development-only pnpm exec cf dev --port 8793 --host 127.0.0.1import { env } from "cloudflare:workers";
const encoder = new TextEncoder();
let keyImports = 0;
let signingKey: Promise<CryptoKey> | undefined;
function getSigningKey(): Promise<CryptoKey> {
if (!signingKey) {
keyImports += 1;
signingKey = crypto.subtle.importKey(
"raw",
encoder.encode(env.SIGNING_SECRET),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
}
return signingKey;
}
export default {
async fetch(request) {
const key = await getSigningKey();
const body = await request.arrayBuffer();
const mac = await crypto.subtle.sign("HMAC", key, body);
const hex = Array.from(new Uint8Array(mac), (byte) => byte.toString(16).padStart(2, "0")).join("");
return new Response(`${hex.slice(0, 16)} (key imports: ${keyImports})\n`);
},
} satisfies ExportedHandler;curl -s -d 'first' http://127.0.0.1:8793/
curl -s -d 'second' http://127.0.0.1:8793/
curl -s -d 'first' http://127.0.0.1:8793/b452aa06e68ad2d2 (key imports: 1)
ce07a1321a38a7ff (key imports: 1)
b452aa06e68ad2d2 (key imports: 1)Three requests, one import. If the isolate is evicted, the next one imports the key again and computes identical signatures, so no response depends on the cache being there. That is the test for any module-level variable: imagine it reset at a random moment and ask whether a response would change.
The cache is filled lazily, inside a request, for a reason. The top level of a module runs before any request exists, and the runtime forbids I/O there. The server habit of fetching configuration at startup looks like this:
const response = await fetch("https://example.com/");
const banner = `fetched at startup: ${response.status}`;
export default {
fetch() {
return new Response(`${banner}\n`);
},
} satisfies ExportedHandler;Under cf dev it works and answers fetched at startup: 200. Build it and run the build output, and the Worker fails to start:
pnpm exec cf build
pnpm exec vp preview --port 8799 --host 127.0.0.1...
service core:user:not-a-server: 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:2:44
...The top-level fetch succeeding under cf dev shows that the dev server evaluates your module on demand, while a request is in progress, so the restriction never applied. vp preview (the Vite+ form of vite preview) runs the build output in the Workers runtime, where the top level is evaluated before any request, and one run of it before deploying catches this class of error. Module scope also has a time budget: the limits page allows 1 second to parse and run top-level code.
Work that outlives the response
In a server process, a promise that was started and never awaited still finishes, because the process stays up. A Worker invocation ends when its response has been delivered, and unfinished work ends with it.
async function recordVisit(path: string): Promise<void> {
// Stands in for a slow call to an analytics or audit service.
await scheduler.wait(200);
console.log(`recorded visit to ${path}`);
}
export default {
async fetch(request, env, ctx) {
const { pathname } = new URL(request.url);
if (pathname === "/floating") {
void recordVisit(pathname);
} else if (pathname === "/wait-until") {
ctx.waitUntil(recordVisit(pathname));
} else if (pathname === "/awaited") {
await recordVisit(pathname);
}
return new Response(`ok ${pathname}\n`);
},
} satisfies ExportedHandler;All three routes answer ok. The timings differ:
curl -s -w '%{time_total}s\n' http://127.0.0.1:8793/floating
curl -s -w '%{time_total}s\n' http://127.0.0.1:8793/wait-until
curl -s -w '%{time_total}s\n' http://127.0.0.1:8793/awaitedok /floating
0.011792s
ok /wait-until
0.007621s
ok /awaited
0.213064sSo does the dev server’s log:
recorded visit to /wait-until
recorded visit to /awaitedThe floating call never logged. Its timer was still pending when the response went out, and the runtime canceled it with no error and no warning. In a variant of this test, a floating task that waited 0 ms was dropped as well. Awaiting the call records the visit and makes the client wait 200 ms for it. ctx.waitUntil gets both properties: the response returns at once and the invocation stays alive until the promise settles.
What waitUntil promises is narrower than “run this in the background”. According to the context API documentation, it extends the invocation for up to 30 seconds after the response is sent or the client disconnects, and that budget is shared by every waitUntil call in the request. Promises still pending at the end are canceled, with no retry and no persistence. It fits cache writes and best-effort telemetry. Work that must happen belongs in a Queue, and work the response depends on should be awaited.
No disk and no port
Two more things a server process takes for granted are absent by design. The node:fs module exists, backed by memory:
import { existsSync, readFileSync, writeFileSync } from "node:fs";
export default {
fetch(request) {
const { pathname } = new URL(request.url);
if (pathname === "/write") {
writeFileSync("/tmp/session.txt", "alice");
return new Response(`wrote: ${readFileSync("/tmp/session.txt", "utf8")}\n`);
}
return new Response(`exists: ${existsSync("/tmp/session.txt")}\n`);
},
} satisfies ExportedHandler;curl -s http://127.0.0.1:8793/write
curl -s http://127.0.0.1:8793/readwrote: alice
exists: falseThe write succeeded, and the file was gone by the next request. The virtual file system gives each request its own /tmp and exposes the bundled modules read-only under /bundle. Everything written counts against the isolate’s memory limit. A session file or an upload spooled to disk has to go to KV or R2.
Sockets follow the same pattern. node:http can create a server and call listen:
import { createServer } from "node:http";
import { httpServerHandler } from "cloudflare:node";
const server = createServer((req, res) => {
res.writeHead(200, { "content-type": "text/plain" });
res.end(`node:http handled ${req.url}\n`);
});
server.listen(8080);
export default httpServerHandler({ port: 8080 });curl -s http://127.0.0.1:8793/hello
curl -sS http://127.0.0.1:8080/hellonode:http handled /hello
curl: (7) Failed to connect to 127.0.0.1 port 8080 after 0 ms: Couldn't connect to serverlisten(8080) returned without error, and nothing is listening on port 8080. The number only tells httpServerHandler which server object receives the requests that arrive through the Worker’s fetch entry point. A Worker never binds a port. The platform accepts connections and hands them to a handler, which is also how the connect() handler for inbound TCP (in public beta) works.
CPU time and wall time
A server is usually sized by how long requests take. Workers meter a different quantity: CPU time, the time your code spends executing, which excludes time spent waiting on the network or on storage. These are the numbers on the limits page as of 2026-11-28:
| Limit | Workers Free | Workers Paid |
|---|---|---|
| CPU time per HTTP request | 10 ms | 30 s by default, up to 5 min |
| Wall time per HTTP request | No limit while the client is connected | No limit while the client is connected |
After the response (waitUntil) |
30 s | 30 s |
| Memory per isolate | 128 MB | 128 MB |
| Module startup | 1 s | 1 s |
| Subrequests per request | 50 | 10,000 |
Cron Triggers and Queue consumers are capped at 15 minutes of wall time. On the paid plan, the CPU limit is raised with limits: { cpuMs } under worker in cloudflare.config.ts.
The difference between the two clocks is visible locally:
export default {
async fetch(request) {
const { pathname } = new URL(request.url);
if (pathname === "/wait") {
// Wall time: two seconds pass, the isolate is idle.
await scheduler.wait(2000);
return new Response("waited\n");
}
if (pathname === "/spin") {
// CPU time: the isolate is busy for the whole loop.
let x = 0;
for (let i = 0; i < 300_000_000; i++) {
x = (x + i * 31) % 1_000_003;
}
return new Response(`spun ${x}\n`);
}
return new Response("ok\n");
},
} satisfies ExportedHandler;Send a trivial request while a slow one is in flight:
curl -s -o /dev/null -w 'wait: %{time_total}s\n' http://127.0.0.1:8793/wait &
sleep 0.2
curl -s -o /dev/null -w 'ok: %{time_total}s\n' http://127.0.0.1:8793/
waitok: 0.017735s
wait: 2.017655sThen the same with /spin:
curl -s -o /dev/null -w 'spin: %{time_total}s\n' http://127.0.0.1:8793/spin &
sleep 0.2
curl -s -o /dev/null -w 'ok: %{time_total}s\n' http://127.0.0.1:8793/
waitspin: 1.400375s
ok: 1.206646sTwo seconds of waiting cost the isolate nothing, and the second request was served in 18 ms. The loop held the isolate’s only thread for 1.4 seconds, and the trivial request sat behind it for 1.2 seconds. That is the resource the CPU limit protects. On the free plan the loop is far past its 10 ms budget, and a Worker that keeps exceeding the limit is terminated with error 1102, Worker exceeded resource limits. The two-second wait fits any plan.
Two caveats apply when testing this. cf dev did not enforce the limit: with limits: { cpuMs: 50 } in the configuration, the loop still ran to completion. And CPU time cannot be measured from inside a deployed Worker, because Date.now() and performance.now() only advance after I/O in production, a Spectre mitigation that local development does not apply. Use a profiler locally, and in production read the CPU time that Workers Logs records for each invocation.