The Web-Standard Request and Response Model
No app, no server, no handle. A team ships a small status endpoint. The engineer who wrote it last worked in Express, so the first draft was a route handler on an application object. Workers has no such object, no framework-supplied request, and nothing to write into: the module exports a fetch handler, and the value it returns is the response.
The socket belongs to the edge. In Node.js your process owns a listening socket, and a response handle writes to one client connection. On Workers, Cloudflare terminates TLS and invokes your code with a parsed request; you never call listen, never call end, and never see a raw TCP connection. The handler uses the same Request, Response, Headers, and ReadableStream types a browser does, implemented by the Workers runtime rather than a browser.
Handler and binding. The exported function that receives the request is the handler. A binding is a capability the platform injects through the environment object — a KV namespace or a secret — and it is not an environment variable in the process sense.
Context and subrequest. The context object controls invocation lifetime, including work that continues after the response. Any outbound fetch your Worker makes is a subrequest: every redirect hop counts separately, which matters when you reach the ceiling.
The mental model is a function, not a server. Cloudflare matches a route and invokes the handler inside a V8 isolate, a lightweight JavaScript context that can serve many requests before it is evicted.
Module scope is a cache, not a database
An isolate is reused opportunistically, so module-scope values survive between requests. That survival is a cache, not storage: reuse immutable, request-independent values there and construct clients inside the handler.
An I/O object that escapes into module scope throws when another request touches it, because it belongs to the invocation that created it (Errors and exceptions). A client built at startup with request-scoped credentials can also leak data between requests.
Think of a food truck inside a market. The market owns the pitch, the power, and the queue; the truck owns the recipe and serves one order at a time. You can prep ingredients when the truck opens, but you cannot hand yesterday's customer's plate to today's.
The request is immutable. Add a header or change a URL by constructing a new Request with the original as the base. Cloudflare metadata rides on request.cf: colo, country, and TLS details.
The response is built, then committed. A body can be a string, a Uint8Array, a Blob, or a ReadableStream. Once the runtime sends the status line and headers, only the body stays writable.
Routing is code, not a platform feature. Parse the request URL, branch on path and method, and return a response; middleware wraps that branch with a next handler and can short-circuit. The runtime ships no router, so frameworks such as Hono add one.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
subgraph Client["Client boundary"]
B["Browser or curl
GET /events"]
end
subgraph CF["Cloudflare network"]
E["Edge
TLS termination and route match"]
subgraph ISO["V8 isolate, one invocation"]
M["Module scope
initialized when the isolate starts"]
H["fetch handler
request, env, ctx"]
R["Request context
outbound I/O allowed"]
end
K[("Binding
env.AUDIT")]
end
O["Upstream API"]
X["1101 error page
uncaught exception"]
Y["1102 error page
CPU or memory limit"]
B -->|HTTPS| E
E -->|invoke handler| H
M -.->|initializes once per isolate| H
H -->|read and write| K
H -->|runs inside| R
H -->|subrequest fetch| O
O -->|status and body| H
H -->|"return Response"| E
E -->|"status, headers, body"| B
H -.->|throws| X
H -.->|exceeds a limit| Y
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class E primary;
class B,M,H,O secondary;
class R ok;
class X,Y danger;
Figure 1 follows one request across three boundaries: client to edge, edge to isolate, and isolate to upstream. The dashed arrows are failure exits, not normal flow. The binding and the upstream API are reached from inside the request context; module scope sits outside it.
Figure 2 redraws the same invocation as layers. The dashed rectangle is a boundary, not a network hop: the edge calls into the isolate, and the isolate reaches bindings and the network through the runtime. Module scope is deliberately outside the request context, which is why a fetch() call at the top level of your file fails during startup instead of becoming a lazy request.
Streams and Work That Outlives a Response
A forty-megabyte CSV does not fit in memory. The first version builds the whole file and returns it. Each isolate has 128 MB for the JavaScript heap and WebAssembly together, and the failure is abrupt: the runtime returns error 1102, or logs a memory-limit message when a buffered read crosses the ceiling (Limits).
Streaming changes the contract. Returning a ReadableStream sends the status line and headers first, then forwards each chunk as it is produced, so memory stays roughly constant and the client sees the first rows long before the last one. The tradeoff is that the status is committed: a database failure after the first chunk cannot become a server error, only a stopped body, an in-band error record, or a truncated response.
Work now has three separate lifetimes. The handler's promise ends when it returns, the response body continues until the last chunk or a disconnect, and registered background work runs after that — for at most thirty seconds, shared across every promise passed in (Context). A promise that is neither awaited nor registered may be canceled at invocation end.
| Mechanism | When it runs | Lifetime boundary | Use it for | Failure signature |
|---|---|---|---|---|
| Buffered body | Build the complete body, then construct the Response | Ends when the handler returns | Small JSON, HTML, error pages | Memory grows with payload; 1102 or Memory limit would be exceeded before EOF |
| Streamed body | Return a ReadableStream as the body | Last chunk, client disconnect, or stream error | CSV, SSE, large proxies | Status already committed; a late failure truncates the body |
ctx.waitUntil() | After the Response is returned | 30 seconds after response or disconnect, shared across calls | Audit logs, cache writes, analytics | waitUntil() tasks did not complete within the allowed time |
| Floating promise | Started, but neither awaited nor registered | May be canceled when the invocation ends | Nothing | Silent data loss; no client-visible error |
ctx.passThroughOnException() | When the handler throws before returning | Until the origin responds | Fail open in front of an existing origin | Request body may already be consumed and cannot be replayed |
Fail-open has a blind spot
The last row of the table is a warning disguised as a convenience. ctx.passThroughOnException() protects against an uncaught exception in your code; it does not protect against an origin fetch that throws after it consumed the request body. Catch origin failures and return your own 502 rather than relying on the fallback.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
participant C as Client
participant W as Worker
participant O as Origin
C->>W: GET /export.csv
W->>O: fetch(origin)
O-->>W: 200 and body stream
W-->>C: 200 and headers, committed
loop each chunk
O-->>W: chunk
W-->>C: transformed chunk
end
alt stream completes
W-->>C: final chunk and close
W->>W: waitUntil audit, up to 30 seconds
else client disconnects
C--xW: connection reset
W->>W: request.signal abort, only when enabled
W->>O: cancel the reader
else origin fails mid-body
O--xW: stream error
W-->>C: truncated body
W->>W: outcome exception, status already sent
end
Figure 3 shows why "return a Response" and "finish the work" are different events. The success branch still has a waitUntil tail. The disconnect branch depends on an abort signal that is itself compatibility-gated. The mid-body failure branch has no clean HTTP status left to send.
The stream body is defensive by design. Enqueueing after a client disconnect throws, so the send helper swallows the error, and the catch writes an in-band error event instead of pretending the status can still change. The finally block closes exactly once, and the abort listener is dead code unless the date or flag enables request signals.
Same code, two runtimes
Piping an origin body through a transform stream without awaiting the pipe behaves differently on either side of 2026-11-17. On older dates, a destination error can leave the promise resolved, so the catch never runs and the failure disappears; from that date, the new default cancels the source and rejects the pipe, matching the WHATWG Streams standard (Compatibility flags).
Identical source, different observability. Neither behavior is wrong for its date — the mistake is assuming the runtime you tested is the runtime you deployed.
Compatibility Dates and Runtime API Changes
A compatibility date is a snapshot of runtime behavior, not a language version and not a Node.js version. Cloudflare regularly fixes bugs in APIs, and some fixes are observable: a header parser, a stream error, a module resolution rule. A date lets new Workers opt into the fix while deployed Workers keep the old behavior. A compatibility flag is the individual switch behind one of those changes. Setting a date is equivalent to enabling every flag whose default date has passed.
A date bump is a release
Three operational rules follow. Set the date when the project is created and move it deliberately; the new date takes effect on the next deploy, so a date change is a release, not a local preference. Old dates are supported indefinitely, but current documentation describes current behavior — and omitting the date through the API defaults to 2021-11-02, silently opting out of every fix since then (Compatibility dates).
On 2026-11-17 alone, the documented defaults change stream error propagation, abort signals on incoming requests, and module resolution. One deploy can alter three failure paths your tests never exercised.
Four budgets hide behind the word "timeout", and fan-out is a fifth (values as documented on 2026-11-05).
| Budget | What it measures | Limit | Failure signature |
|---|---|---|---|
| CPU time | Active execution; waiting on fetch, KV, or a database does not count | 10 ms per request on Free; up to 5 minutes on Paid, with a 30-second default raised through limits.cpu_ms | 1102, outcome exceededCpu |
| Wall time | Elapsed time, including waiting | No hard limit for HTTP while the client stays connected; 15 minutes for cron, queues, and alarms; 20 minutes to drain during a runtime update; registered background work adds 30 seconds | Latency, not a limit error |
| Memory | Heap plus WebAssembly, per isolate | 128 MB; in-flight requests finish and a new isolate takes over | 1102, outcome exceededMemory |
| Placement | Where the isolate runs | Near the client by default; Smart Placement may move it near your backend, and hints pin it to a region or host (Placement) | Latency only, not CPU or memory accounting; fetch handlers, not RPC methods |
| Subrequests | Outbound calls, including redirect hops | 50 on Free, 10,000 on Paid, configurable to 10 million | Fan-out fails even at near-zero CPU |
Fan-out punishes loops. A Worker that makes sixty calls on Free fails even when CPU usage is near zero, because every redirect hop counts separately (Limits).
Wall time and CPU time diverge. A handler that sleeps for two seconds burns two seconds of wall time and almost no CPU; a handler that parses JSON in a tight loop for two seconds burns two seconds of CPU and dies immediately on the Free plan. Workers Logs records both numbers: the first explains limit errors, the second explains user-visible latency.
The same discipline applies to a date bump. Read the flags page for every default between your old date and the new one, list the ones that touch streams, request signals, module resolution, or Node compatibility, and write a test for each. If a flag changes behavior you are not ready for, keep the new date and add the corresponding no_* or disable_* flag.
Node.js and Python Support Need Explicit Compatibility Checks
Workers is not Node.js with a different deploy command. It is V8 plus Web APIs plus Cloudflare's own runtime APIs, and the difference is a platform contract rather than a flag.
- Present: fetch, Request and Response, Headers, ReadableStream, crypto.subtle, URL, TextEncoder, WebSocket, timers.
- Absent: a filesystem, a raw TCP server you accept connections on, OS processes, native addons, and a meaningful process exit.
The compatibility layer is opt-in by date. Which flag you need depends on when the Worker was created, and the layer has four grades. Conflating them causes most of the confusion.
- 2026-08-04 and later — both the layer and its v2 surface are on by default.
- 2024-09-23 to 2026-08-03 — add
nodejs_compatyourself. - Before 2024-09-23 — add
nodejs_compat, plusnodejs_compat_v2for the larger surface.
The four grades differ in what actually runs.
- Native: a real implementation in the runtime, such as
node:buffer,node:path,node:crypto, ornode:stream. - Partial: usable, but with documented gaps, such as
node:dns,node:tls,node:os,node:module, andnode:perf_hooks. - Stub: the module imports, but the API does not work.
node:child_process,node:worker_threads,node:v8, andnode:sqliteare examples that become available on specific dates. - Polyfill: Wrangler injects a shim through
unenv. Calling an unimplemented method throws[unenv] <method> is not implemented yet!(Node.js compatibility).
process.version is a trap. By default the layer reports the latest Node.js 22 release; the nodejs_process_version_24 flag, default as of 2026-11-24, reports Node.js 24. Libraries branch on that string, so a date bump can change package behavior without any lockfile change, and the failure may surface deep inside a package you did not touch.
Python runs on Pyodide. That is CPython compiled to WebAssembly inside the same V8 isolate. The python_workers flag gates it, and the pywrangler CLI drives Wrangler for you.
Deploy-time initialization is snapshotted. Cloudflare starts the entrypoint, imports everything at top level, and snapshots the WebAssembly memory so requests skip the expensive work (How Python Workers work). The Python version follows the compatibility date: python_workers_314, default as of 2026-09-08, selects Python 3.14.
Import success is not a compatibility test
The standard library is a documented subset, packages must be pure Python or ship as WebAssembly-compatible wheels, and APIs that assume a writable filesystem, OS processes, or unrestricted threads do not map onto the isolate model.
A pure-Python package may import cleanly and still fail when a code path reaches an unsupported module.
Figure 4 shows the two gates. The Node path branches on date first, then on the flag; the Python path branches on its own flag and then on package availability. In both cases "the import succeeded" only proves the module resolved, not that the method you call is implemented.
The practical test is a startup check, not a code review. Import every Node or Python module your Worker uses at the top of a test file, call one representative method from each, and run it under the exact compatibility date and flags you deploy. wrangler dev will catch unresolved modules at bundle time; only execution catches stubs and polyfills. When you upgrade a dependency, re-run that check, because the package may have added an import that your previous version never touched.
Implement a Streaming Worker With Predictable Errors
A short scaffold and three checks. The exercise builds the event stream from the widget above and tests its three exit paths: normal completion, client disconnect, and an in-band failure. It runs locally; deployment is optional and fits the Free plan.
Implement a Streaming Worker With Predictable Errors
Status: design-only. No Wrangler command, curl call, or deployed request was run for this draft; the observations below are predictions from the handler's control flow.
Prerequisites. A Cloudflare account, Node.js 20 or later, npm, and a terminal. Confirm the intended account before deploying. Local development needs no paid plan, the Free plan is enough if you deploy, and a disposable project name keeps the lab isolated.
Inputs. The streaming handler from the widget above, a compatibility date of 2026-11-02, and the enable_request_signal flag. No KV namespace, secret, or custom domain is required.
- Scaffold the project with the first command, choosing Hello World, Worker only, and TypeScript.
- Set the date, the flag, and the observability block in
wrangler.jsonc. - Replace the source, generate types, and start the dev server.
- Run the three checks below, then restore the handler and the flag.
| Check | What you change | Expected observation |
|---|---|---|
| Normal completion | Nothing | text/event-stream, three tick events about 200 ms apart, a final done event, then one audit line in the Wrangler terminal about two seconds after the request began |
| A — client disconnect | curl -N --max-time 0.4 .../events | curl exits 28, client_disconnected is logged, and no 1101 page appears |
| B — flag missing | Remove the flag, restart, repeat A | No disconnect log; the handler may stop silently. This is the gate, not a handler bug |
| C — memory ceiling | Return new Uint8Array(200 * 1024 * 1024), deploy | 1102 with outcome exceededMemory when deployed, because limits are enforced on the network |
| Optional — deployed | Deploy, request the workers.dev URL, inspect Workers Logs | cpuTime, wallTime, and the invocation outcome; a tight loop of about 50 ms of work forces 1102 with outcome exceededCpu on Free |
Cost dimensions. Local runs consume no Workers quota. A deployed Free-plan Worker includes 100,000 requests per day and 10 ms of CPU per invocation, so a handful of curl calls is negligible; the daily counter resets at midnight UTC. No paid feature is used.
Cleanup. Stop the dev server with Ctrl-C. If you deployed, run npx wrangler delete and remove the local state directory. No DNS record, secret, or storage namespace was created.
The two disconnect checks are the core of the exercise. Check A proves your cleanup path runs; check B proves the same code silently loses that path when the runtime gate is absent. Neither needs a paid plan, and neither depends on network timing beyond a sub-second curl timeout.
Limits are enforced on the network
Local wrangler dev will not reproduce a memory or CPU ceiling. Checks C and the optional deployed pass only produce 1102 on Cloudflare's network; local workerd is for behavior and bindings, not for validating limit thresholds.
Verify Cancellation and Error Paths Against the Pinned Runtime
Verification date: 2026-11-05. Basis: official Cloudflare documentation reviewed that day. Execution status: design-only — no Wrangler command, curl call, or deployed request was run, so the criteria below are documented expectations. Record your own Wrangler and Node.js versions, compatibility date, and plan before treating a result as evidence.
Pass evidence. A correct run against the pinned date and flag should show:
GET /eventsreturns200withcontent-type: text/event-stream; charset=utf-8andcache-control: no-store.- Frames arrive incrementally under
curl -N; the client does not wait for the full body before displaying the firsttick. - The audit log appears after the final frame, within the 30-second
waitUntilbudget. - A client disconnect produces
client_disconnectedorstream_cancelled, and no1101error page. - Removing
enable_request_signalremoves the disconnect log without changing the events produced before the disconnect.
Fail signatures. These are diagnostic:
1102withWorker exceeded resource limitsmeans CPU or memory, and the outcome field distinguishesexceededCpufromexceededMemory.1101withThe script will never generate a responsemeans a promise never settled, often awaitUntil-less async branch.Memory limit would be exceeded before EOFmeans a buffered read crossed 128 MB; stream or chunk the body.waitUntil() tasks did not complete within the allowed time after invocation end and have been cancelledmeans the 30-second tail expired; move durable work to Queues.[unenv] ... is not implemented yet!means a Node polyfill was called, not a native API.Cannot perform I/O on behalf of a different requestmeans an I/O object escaped into module scope or another invocation.- No abort log on disconnect means the date or flag does not enable
request.signal.
Self-check. Answer before reading the explanations.
- Does returning a
Responseend the invocation? No. The handler's promise is settled, but the invocation stays active while the response body is still streaming.waitUntil()extends it for up to 30 seconds after the response or disconnect. Only then is the invocation complete. - Does a newer compatibility date make code faster or safer automatically? No. It opts into behavior changes, including bug fixes that alter observable failure paths. It can change stream error propagation,
request.signal, and module resolution in a single deploy, so it needs its own test pass and a rollback plan. - Why does
process.versionmatter if the Worker is not Node.js? Because libraries branch on it. The compatibility layer reports Node.js 22 by default and Node.js 24 undernodejs_process_version_24, so the same package can take a different code path after a date bump without any lockfile change. - Why can't
wrangler devprove the CPU limit? Resource limits are enforced on Cloudflare's network, not in local development. Local workerd is for behavior and bindings, not for validating1102thresholds.
Unresolved limitations. This draft did not execute the exercise, so no latency, throughput, memory, or cost measurement is claimed. Local workerd approximates the deployed runtime but does not reproduce production placement, network conditions, or limit enforcement.
Two gates stay date-dependent. The abort-signal default changes on 2026-11-17: a Worker pinned before that date needs the flag, and a Worker moved past it gets the behavior without one. Python Workers were reviewed from documentation only. Plan limits, included quotas, and prices change, so re-check them at writing time.
Authoritative references.
- Cloudflare Workers
- How Workers works
- Limits
- Compatibility dates
- Compatibility flags
- Request
- Response
- Streams
- Context (ctx)
- Errors and exceptions
- Node.js compatibility
- Python Workers
- How Python Workers work
- Placement
- Wrangler configuration
Next in the Series
In Host Static Sites and Full-Stack Apps With Workers, we'll explore Choose static assets, SPA routing, SSR, and a Pages migration path.