new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · all subjects

architecture

125 notes in this subject, read out of this brain and free to use. This is page 2 of 3.

Python Workers execute via Pyodide in V8 isolates

Python Workers are executed by Pyodide, which is CPython compiled to WebAssembly. When you write a Python Worker, your code is interpreted directly by Pyodide within a V8 isolate.

Python Worker deployment lifecycle with cold start optimizations

When deploying with uv run pywrangler deploy: (1) Wrangler uploads Python code and packages from pyproject.toml to the Workers API, (2) Cloudflare validates the code, (3) a new V8 isolate is created with Pyodide injected, (4) the Worker entrypoint module and top-level imports are executed and a snapshot of the WebAssembly linear memory is taken at deploy time, and (5) this snapshot is deployed alongside the code to the Cloudflare network. On request, the snapshot is loaded to bootstrap the Worker, avoiding expensive initialization at runtime.

Python Workers runtime engine

Python Workers are executed by Pyodide, which is a port of CPython to WebAssembly. Pyodide behaves identically to CPython (the reference implementation of Python) for the most part, and the majority of the CPython test suite passes when run against Pyodide.

Python Standard Library availability

The full Python Standard Library is available in Python Workers, except for excluded modules (curses, dbm, ensurepip, fcntl, grp, idlelib, lib2to3, msvcrt, pwd, resource, syslog, termios, tkinter, turtle.py, turtledemo, venv, winreg, winsound), non-functional modules due to WebAssembly limitations (multiprocessing, threading), and modules that cannot be imported due to removed termios dependency (pty, tty).

Python Workers in-memory filesystem

Python Workers have access to an ephemeral, in-memory filesystem where you can read and write files using standard Python file I/O (such as open() and pathlib.Path). All data is lost when the Worker isolate is destroyed, and the filesystem is not shared between different isolate instances. This should not be relied upon for persistent storage; use KV, R2, or Durable Objects instead.

Local development uses Miniflare and workerd runtime

Cloudflare Workers can be developed and tested locally on your machine before deployment using Miniflare, a simulator that executes Worker code using the same workerd runtime used in production.

Start local development with wrangler dev or vite dev

Use 'wrangler dev' via the Cloudflare Workers CLI or 'vite dev' via the Cloudflare Vite plugin to start a local development server. Both use Miniflare under the hood.

Default local development behavior

By default, running wrangler dev or vite dev means: Worker code runs on local machine, all resources bound in Wrangler configuration are simulated locally, and the local workerd runtime runs with TZ=UTC so Date and Intl APIs observe UTC regardless of machine timezone.

wrangler dev --remote uploads code to preview environment

Remote development mode via 'wrangler dev --remote' uploads all Worker code to temporary preview environment on Cloudflare infrastructure, with changes automatically uploaded as code is saved. All bindings automatically connect to remote resources; local simulations cannot be configured.

When to use wrangler dev --remote

Use 'wrangler dev --remote' for testing features or behaviors highly specific to Cloudflare's network that cannot be adequately simulated locally or tested via remote bindings. For most development, local development with remote bindings is more efficient.

Remote development not supported in Vite plugin

Remote development mode via 'wrangler dev --remote' is not supported in the Vite plugin. Only the Wrangler CLI offers remote development functionality.

Public beta features available without explicit access

Public alphas and betas in Cloudflare Workers are openly available to everyone, though they may have limitations and caveats due to their early stage of development.

Private beta features require access request

Private alphas and betas require explicit access to be granted. Users must refer to the documentation to join the relevant product waitlist.

Email Workers in public beta

Email Workers is currently in public beta status and is openly available.

Green Compute in public beta

Green Compute is currently in public beta status and is openly available.

TCP Sockets in public beta

TCP Sockets runtime API is currently in public beta status and is openly available.

Temporary accounts for preview and claim workflow

Temporary preview accounts let you deploy and test Workers before authenticating with Cloudflare. You can then claim the account to keep its deployments and supported resources. This enables a preview-and-claim lifecycle for generated applications and AI agent deployments.

REST API endpoints for temporary account provisioning

Two REST API endpoints support temporary account provisioning: POST `https://api.cloudflare.com/client/v4/provisioning/previews/challenge` to request a proof-of-work challenge, and POST `https://api.cloudflare.com/client/v4/provisioning/previews` to create a temporary account with the challenge solution.

Proof-of-work challenge response structure

The challenge endpoint returns a JSON object with fields: challengeToken (string), seed (Base64URL-encoded 32-byte value), k (integer for number of segments), and g (integer for hashes per segment). The challenge token and seed are required to solve the proof-of-work challenge.

Solving proof-of-work challenge algorithm

To solve the proof-of-work challenge: (1) Decode seed as Base64URL to get 32 bytes; (2) Compute checkpoint[0] = SHA-256(seed); (3) For each segment from 0 to k-1, compute g sequential SHA-256 hashes from the previous checkpoint and append the result; (4) Concatenate all k+1 checkpoints (each 32 bytes); (5) Encode the concatenated bytes with standard Base64 and send as solution.checkpoints. Before solving, require k and g to be positive integers, reject if seed does not decode to 32 bytes, and reject if k*g exceeds 64,000,000.

Node.js proof-of-work solver implementation

Example function solvePreviewChallenge that takes challengeToken, seed, k, and g, validates parameters, decodes the base64url seed, and computes sequential SHA-256 checkpoint chain, returning an object with challengeToken and solution.checkpoints (base64-encoded concatenated checkpoints). Includes validation that seed is exactly 32 bytes, k and g are positive integers, and k*g does not exceed 64,000,000.

Creating temporary account with proof-of-work solution

POST to `https://api.cloudflare.com/client/v4/provisioning/previews` with JSON body containing: termsOfService (URL), privacyPolicy (URL), acceptTermsOfService (must be string "yes" only after user accepts both policies), challengeToken (from challenge response), and solution object with checkpoints (base64-encoded concatenated SHA-256 checkpoints). User must accept Cloudflare's Terms of Service and Privacy Policy before setting acceptTermsOfService to "yes".

Temporary account creation response structure

Successful temporary account creation returns JSON with account object containing: id (temporary account ID), name (temporary account name), type ("standard"), apiToken (temporary API token for supported operations), tokenId, and expiresAt (expiration timestamp). Also returns claim object containing: token, url (in format `https://dash.cloudflare.com/claim-preview?claimToken=<CLAIM_TOKEN>`), and expiresAt. Before using the response, confirm success is true and verify that account.id, account.apiToken, account.expiresAt, claim.url, and claim.expiresAt are present.

Deploying Worker to temporary account with REST API

Upload and deploy a Worker using the Workers Script Upload API with account.id and account.apiToken. Use PUT to `https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$SCRIPT_NAME` with Authorization header containing the temporary API token. Include metadata with main_module and compatibility_date, and upload the worker script file. Then call GET to `https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/subdomain` to retrieve the workers.dev subdomain. Construct deployment URL as `https://<SCRIPT_NAME>.<SUBDOMAIN>.workers.dev`.

Temporary account claim deadline

Users must complete the account claim within 60 minutes. Opening the claim URL before the deadline is not sufficient; users must sign in to Cloudflare or create an account and complete the dashboard prompts. If the user does not complete the claim, Cloudflare deletes the account and its resources.

Platform architecture for preview and claim with temporary accounts

When using the REST API, the trusted platform backend stores account.apiToken privately while the platform UI has no temporary API token. The backend creates the temporary account, deploys the Worker, and returns only the preview URL and bearer claim URL to the UI. The claim URL is shown only to the intended user. After claiming, the Worker remains in the claimed account. To continue with Wrangler, run `wrangler login`, then deploy without `--temporary`. For later deployments, connect through a normal authenticated flow such as Cloudflare OAuth. Claiming does not grant the platform permanent access to the account.

Fetch API requires DNS records in Cloudflare for CNAME setup zones

When you make a subrequest using fetch() from a Worker in a zone with a Partial (CNAME) setup, the Cloudflare DNS resolver is used. All hostnames that the Worker needs to resolve must have a dedicated DNS entry in Cloudflare's DNS setup. If a hostname is only in your authoritative DNS but not in Cloudflare DNS, the Fetch API call will fail with HTTP status code 530 (1016).

Workers cannot fetch directly to IP addresses

For Workers subrequests, requests can only be made to URLs, not to IP addresses directly. To fetch an IP address, create an A or AAAA DNS record in your zone pointing to that IP address, and then fetch using the hostname. For example, create an A record with name `server` and value `192.0.2.1` in zone `example.com`, then fetch `http://server.example.com` instead of `http://192.0.2.1`.

D1 and Queues built on Durable Objects

D1 and Queues are built on Durable Objects.

Multiple storage products integration

Applications can build on multiple storage and database products. For example, using Workers KV for session data, R2 for large file storage and media assets, and Hyperdrive to connect to a hosted Postgres or MySQL database.

Workers for Platforms overview

Workers for Platforms allows you to deploy custom code on behalf of your users or let your users directly deploy their own code to your platform while you manage the infrastructure.

Workers for Platforms documentation location

Workers for Platforms documentation is located at /cloudflare-for-platforms/workers-for-platforms/

Workers runtime uses V8 engine

The Cloudflare Workers runtime uses the V8 engine, which is the same engine used by Chromium and Node.js. The Workers runtime implements many of the standard APIs available in most modern browsers.

Workers run on Cloudflare's global network

Cloudflare Workers functions run on Cloudflare's global network, which is a growing global network of thousands of machines distributed across hundreds of locations. Each machine hosts an instance of the Workers runtime, and each runtime is capable of running thousands of user-defined applications.

What are Isolates

V8 orchestrates isolates, which are lightweight contexts that provide your code with variables it can access and a safe environment to be executed within. An isolate can be considered a sandbox for your function to run in. A given isolate has its own scope.

Isolates are not necessarily long-lived

An isolate may be spun down and evicted for a number of reasons: resource limitations on the machine, a suspicious script attempting to break out of the isolate sandbox, or individual resource limits. Because of this, it is generally advised not to store mutable state in your global scope unless you have accounted for this contingency.

Single-threaded event loop handles concurrent requests

A single Workers instance may handle multiple requests including concurrent requests in a single-threaded event loop. This means that other requests may or may not be processed during awaiting any async tasks such as fetch if other requests come in while processing a request.

Isolates evicted when hitting limits or resource constraints

Isolates are resilient and continuously available for the duration of a request, but in rare instances isolates may be evicted. When a Worker hits official limits or when resources are exceptionally tight on the machine the request is running on, the runtime will selectively evict isolates after their events are properly resolved.

Workers reference documentation structure

The Workers reference documentation is located at the reference section and contains conceptual and technical reference material for Cloudflare Workers architecture and behavior. It serves as the primary reference resource for understanding how Workers functions.

Workers placement relative to cache

Cloudflare Workers run before the cache but can also be utilized to modify assets once they are returned from the cache. Modifying assets returned from cache allows for the ability to sign or personalize responses while also reducing load on an origin and reducing latency to the end user by serving assets from a nearby location.

Direct TCP sockets outbound with connect API

Cloudflare Workers can create outbound TCP connections using the connect() API.

Direct TCP sockets inbound support status

Support for handling inbound TCP connections on Cloudflare Workers is coming soon.

SMTP with Email Workers

Cloudflare Workers can use Email Workers to process and forward email without having to manage TCP connections to SMTP email servers.

Supported protocols on Cloudflare Workers

Cloudflare Workers support the following protocols: HTTP/HTTPS, Direct TCP sockets, WebSockets, HTTP/3 (QUIC), and SMTP. HTTP/HTTPS can be used for both inbound and outbound communication. TCP sockets support outbound connections with inbound coming soon. WebSockets support inbound connections. HTTP/3 supports inbound requests. SMTP is supported through Email Workers for both inbound and outbound email processing.

ES modules Worker runs faster than Service Worker

Workers written using ES modules can reuse the same execution context across multiple requests, whereas Service Worker format requires creating a new JavaScript execution context for every request, adding overhead and time.

Durable Objects requires ES modules

Implementing Durable Objects requires Workers that use ES modules format.

ES modules Workers can be published to npm

You can easily publish Workers using ES modules to npm, allowing you to import and reuse Workers within your codebase.

Service Worker syntax migration to ES modules: basic structure

Service Worker syntax uses addEventListener('fetch', event => {...}). ES modules format replaces this with an object definition that must be the file's default export (via export default) with a fetch method: export default { fetch(request) { ... } }.

Cron Trigger migration: Service Worker to ES modules

Service Worker format uses addEventListener('scheduled', (event) => { ... }). ES modules format replaces this with a scheduled() method in the exported object: export default { async scheduled(event, env, ctx) { ... } }.

Service Worker syntax is deprecated

Service Workers are deprecated but still supported. New features may not be supported for Service Workers. ES modules format is recommended.

Full-stack application deployment model

When deploying a project with static assets, Cloudflare deploys both Worker code and static assets in a single operation as a tightly integrated unit running across Cloudflare's network, combining static file hosting, custom logic, and global caching.

Workers has more features than Pages

Workers has a broader set of features compared to Cloudflare Pages, including Durable Objects, Cron Triggers, and more comprehensive Observability capabilities.

Workers vs Pages feature compatibility matrix

Workers supports: Cloudflare Vite plugin, Gradual Deployments, Remote Development, Quick Editor in Dashboard, serving assets on a path, Workers Logs, Logpush, Tail Workers, Source Maps, Cron Triggers, Email Workers, Image Resizing, Queue Consumers, Rate Limiting, and non-root routes. Workers does not support custom domains outside Cloudflare zones. Pages does not support many of these features. Early Hints support in Workers is unsupported without workaround. Durable Objects on Pages requires separate Worker setup. File-based Routing on Workers uses frameworks as workaround. Pages Plugins on Workers use framework plugins or code.

Full-stack application definition and architecture

Full-stack applications are web applications that span both client and server. The build process produces HTML files, client-side resources (JavaScript bundles, CSS stylesheets, images, fonts, etc.), and a Worker script. Data is typically fetched by the Worker script at request-time and the initial page response is usually server-side rendered (SSR). After the initial response, the client is hydrated and a SPA-like experience follows.

Workers serve responses from global network

When a Worker receives a fetch event, it returns the constructed response to the client from Cloudflare's global network instead of continuing to an origin server. This allows Workers to respond quickly by constructing responses directly on the Cloudflare global network.

Auxiliary Workers support config option

Auxiliary Workers also support the config option, enabling multi-Worker architectures without config files. Define auxiliary Workers without config files using config inside the auxiliaryWorkers array.

Auxiliary Workers can inherit entry Worker config

Auxiliary Workers receive the resolved entry Worker config in the second parameter to the config function. This allows auxiliary Workers to inherit configuration from the entry Worker by accessing entryWorkerConfig.

Auxiliary Workers with config option example

Example of defining auxiliary Workers with config option: ```ts import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [ cloudflare({ config: { name: "entry-worker", main: "./src/entry.ts", compatibility_date: "2025-01-01", services: [{ binding: "API", service: "api-worker" }], }, auxiliaryWorkers: [ { config: { name: "api-worker", main: "./src/api.ts", compatibility_date: "2025-01-01", }, }, ], }), ], }); ```

Auxiliary Worker config inheritance example

Example of auxiliary Worker inheriting configuration from entry Worker: ```ts import { defineConfig } from "vite"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [ cloudflare({ auxiliaryWorkers: [ { config: (_, { entryWorkerConfig }) => ({ name: "auxiliary-worker", main: "./src/auxiliary-worker.ts", compatibility_date: entryWorkerConfig.compatibility_date, compatibility_flags: entryWorkerConfig.compatibility_flags, }), }, ], }), ], }); ```

V8 isolates provide primary isolation mechanism

V8 isolates prevent code from accessing memory outside the isolate, even within the same process. Cloudflare runs many isolates within a single process, allowing thousands of tenants on every machine with rapid context switching between guests thousands of times per second.

Give your agent this brain