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 1 of 3.

Use Workflows for multi-step async work

Workflows are a durable execution engine where each step's return value is persisted and only that step is retried if it fails. Use Workflows when background work has multiple steps that depend on each other. They are the right choice for multi-step processes (charge a card, then create shipment, then send confirmation), long-running tasks that need to pause and resume (wait hours or days for external event or human approval via step.waitForEvent()), and complex conditional logic where later steps depend on earlier results. Workflows can run for hours, days, or weeks.

Use Queues for single-step async work

Queues are a message broker where one Worker sends a message and another Worker processes it later. Use Queues when you need to decouple a producer from a consumer. They are the right choice for fan-out (one event triggers many consumers), buffering and batching (aggregate messages before writing to a downstream service), and simple single-step background jobs (send an email, fire a webhook, write a log). Queues provide at-least-once delivery with configurable retries per message.

Use Durable Objects for WebSockets

Plain Workers can upgrade HTTP connections to WebSockets, but they lack persistent state and hibernation. If the isolate is evicted, the connection is lost because there is no persistent actor to hold it. For reliable, long-lived WebSocket connections, use Durable Objects with the Hibernation API. Durable Objects keep WebSocket connections open even while the object is evicted from memory, and automatically wake up when a message arrives. Use this.ctx.acceptWebSocket() instead of ws.accept() to enable hibernation. Use setWebSocketAutoResponse for ping/pong heartbeats that do not wake the object.

Example: Durable Object WebSocket with hibernation

This example shows how to use Durable Objects with hibernation for reliable WebSocket connections. Use this.ctx.acceptWebSocket() to enable hibernation and setWebSocketAutoResponse for ping/pong heartbeats that do not wake the object: import { DurableObject } from "cloudflare:workers"; export default { async fetch(request: Request, env: Env): Promise<Response> { if (request.headers.get("Upgrade") !== "websocket") { return new Response("Expected WebSocket", { status: 426 }); } const stub = env.CHAT_ROOM.getByName("default-room"); return stub.fetch(request); }, } satisfies ExportedHandler<Env>; export class ChatRoom extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.ctx.setWebSocketAutoResponse( new WebSocketRequestResponsePair("ping", "pong"), ); } async fetch(request: Request): Promise<Response> { const pair = new WebSocketPair(); const [client, server] = Object.values(pair); this.ctx.acceptWebSocket(server); return new Response(null, { status: 101, webSocket: client }); } async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) { for (const conn of this.ctx.getWebSockets()) { conn.send(typeof message === "string" ? message : "binary"); } } async webSocketClose( ws: WebSocket, code: number, reason: string, wasClean: boolean, ) { ws.close(code, reason); } }

Use service bindings for Worker-to-Worker communication

When one Worker needs to call another, use service bindings instead of making an HTTP request to a public URL. Service bindings are zero-cost, bypass the public internet, and support type-safe RPC.

Use Workers Static Assets for new projects

Workers Static Assets is the recommended way to deploy static sites, single-page applications, and full-stack apps on Cloudflare. If you are starting a new project, use Workers instead of Pages. Pages continues to work, but new features and optimizations are focused on Workers. For a purely static site, point assets.directory at your build output (no Worker script needed). For a full-stack app, add a main entry point and an ASSETS binding to serve static files alongside your API.

Example: Use service binding for Worker-to-Worker RPC

This example shows how to use service bindings for type-safe RPC between Workers. The auth Worker exposes a verifyToken method that the api Worker calls directly without network hops: import { WorkerEntrypoint } from "cloudflare:workers"; export class AuthService extends WorkerEntrypoint { async verifyToken( token: string, ): Promise<{ userId: string; valid: boolean }> { return { userId: "user-123", valid: true }; } } export default { async fetch(request: Request, env: Env): Promise<Response> { const token = request.headers.get("Authorization")?.replace("Bearer ", ""); if (!token) { return new Response("Unauthorized", { status: 401 }); } const auth = await env.AUTH_SERVICE.verifyToken(token); if (!auth.valid) { return new Response("Invalid token", { status: 403 }); } return Response.json({ userId: auth.userId }); }, } satisfies ExportedHandler<Env>;

Use Hyperdrive for external database connections

Always use Hyperdrive when connecting to a remote PostgreSQL or MySQL database from a Worker. Hyperdrive maintains a regional connection pool close to your database, eliminating the per-request cost of TCP handshake, TLS negotiation, and connection setup. It also caches query results where possible. Create a new Client on each request. Hyperdrive manages the underlying pool, so client creation is fast. Requires nodejs_compat for database driver support.

Use bindings for Cloudflare services, not REST APIs

Some Cloudflare services like R2, KV, D1, Queues, and Workflows are available as bindings. Bindings are direct, in-process references that require no network hop, no authentication, and no extra latency. Using the REST API from within a Worker wastes time and adds unnecessary complexity.

Example: Hyperdrive database connection

This example shows how to use Hyperdrive to connect to a PostgreSQL database from a Worker. Create a new Client on each request; Hyperdrive manages the underlying pool so client creation is fast: import { Client } from "pg"; export default { async fetch(request: Request, env: Env): Promise<Response> { const client = new Client({ connectionString: env.HYPERDRIVE.connectionString, }); try { await client.connect(); const result = await client.query("SELECT id, name FROM users LIMIT 10"); return Response.json(result.rows); } catch (e) { console.error( JSON.stringify({ message: "database query failed", error: String(e) }), ); return Response.json({ error: "Database error" }, { status: 500 }); } }, } satisfies ExportedHandler<Env>;

Monorepo benefits for Workers

A monorepo is a single repository containing multiple applications. It provides: simplified dependency management by managing dependencies across all workers and shared packages in one place using tools like pnpm workspaces and syncpack; code sharing and reuse by creating shared packages for common logic, types, and utilities; atomic commits where changes affecting multiple workers or shared libraries are committed together; consistent tooling by applying the same build, test, linting, and formatting configurations across all projects using tools like Turborepo; and easier refactoring of code spanning multiple workers or shared packages.

Monorepo example with ecommerce services

Example monorepo structure: ecommerce-monorepo contains a workers/ directory with product-service, order-service, and notification-service subdirectories. Each service subdirectory contains src/ and wrangler.jsonc. A packages/ directory contains shared code like schema/. Each service gets its own Workers project created in the dashboard. A single Git connection is added to the monorepo in all three Workers projects. The root directory for each Worker is set to its location, for example /workers/product-service/. A monorepo tool like Turborepo can configure different deploy commands for each Worker, for example 'turbo deploy -F product-service'. When a commit is made to ecommerce-monorepo, builds and deploys trigger for each Worker if the change is within its watch paths.

Preview builds use different deploy command

For preview builds (commits to branches other than the production branch), the deploy command is replaced with a preview deploy command (defaults to npx wrangler versions upload), which creates a preview version without promoting it to production.

Workers Builds two-step process

When a commit is pushed to a connected repository, Workers Builds runs a two-step process: first an optional build command that compiles the project (for example, npm run build for frameworks like Next.js or Astro), and second a deploy command that deploys the Worker to Cloudflare (defaults to npx wrangler deploy).

Build notifications template available

A deployable Workers template is available that consumes build events and sends notifications to Slack, Discord, or any webhook endpoint. The template sends notifications for successful builds with preview or live deployment URLs, failed builds with error messages, and cancelled builds. Setup instructions are in the template README at https://github.com/cloudflare/templates/tree/main/workers-builds-notifications-template#readme.

Workers Builds events are subscribable

You can subscribe to Workers Builds events to trigger custom notifications and integrations. These events include build success, failure, and cancellation events.

Workers Builds enables automated deployment on Git push

Cloudflare Workers Builds allows you to connect a Worker to a GitHub or GitLab repository and automatically build and deploy your Worker when pushing a change.

Successful build is uploaded as version and may be auto-promoted

If a build succeeds, it is uploaded as a version. If the build is configured to deploy with wrangler deploy as the deploy command, the uploaded version will be automatically promoted to the Active Deployment.

Cloudflare MCP server for Workers Builds

The Cloudflare MCP server allows AI tools and agents to interact with Workers Builds. The server is located at https://github.com/cloudflare/mcp-server-cloudflare/tree/main/apps/workers-builds.

CI/CD benefits for Workers

Using a CI/CD pipeline to deploy Workers is a best practice because it automates the build and deployment process (removing the need for manual wrangler deploy commands), ensures consistent builds and deployments across your team by using the same source control management system, reduces variability and errors by deploying in a uniform environment, and simplifies managing access to production credentials.

External CI/CD providers for Workers

External CI/CD providers that can be used to deploy Workers include GitHub Actions and GitLab CI/CD.

When to use external CI/CD providers

Use external CI/CD providers if you have a self-hosted instance of GitHub or GitLab (which is not supported in Workers Builds' Git integration) or if you are using a Git provider that is not GitHub or GitLab.

Choose Workers Builds for integrated CI/CD

Workers Builds is Cloudflare's native CI/CD system that allows you to integrate with GitHub or GitLab to automatically deploy changes with each new push to a selected branch. Choose Workers Builds if you want a fully integrated solution within Cloudflare's ecosystem that requires minimal setup and configuration for GitHub or GitLab users.

D1 is Cloudflare's native serverless database

Cloudflare D1 is a native serverless database product. It is one of the database binding options available to Cloudflare Workers.

Hyperdrive for accelerating database queries

Hyperdrive is a Cloudflare Workers feature that allows you to accelerate queries made to existing databases. It is positioned as a database acceleration tool for use with Workers.

Database integrations available for Cloudflare Workers

Cloudflare Workers supports database integrations and connectors for Worker projects. Documentation covers various database options available to developers building on Workers.

Use Hyperdrive and Smart Placement to reduce query latency from regional databases

When a Worker connects to a regional database, you can reduce query latency by using Hyperdrive and Smart Placement, both included in any Workers plan. Hyperdrive pools database connections globally across Cloudflare's network. Smart Placement monitors your application to run Workers closest to your backend infrastructure when this reduces invocation latency.

Connect to third-party databases via connection strings and secrets

Third-party databases such as Supabase, Turso, and PlanetScale can be connected to Workers by configuring connection strings and credentials as secrets in your Worker.

Connect to multiple databases with separate secrets

You can connect to multiple databases by configuring separate sets of secrets for each database connection. Use descriptive secret names to distinguish between different database connections, such as DATABASE_URL_PROD and DATABASE_URL_STAGING.

D1 connection methods

D1 can be accessed via a Workers binding that integrates with Prisma and Drizzle ORMs, or via the REST API. The Workers binding uses the Workers binding API at /d1/worker-api/.

D1 database overview

D1 is Cloudflare's own SQL-based, serverless database optimized for global access from Workers. It can scale out with multiple smaller databases (10GB each), such as per-user, per-tenant, or per-entity databases. D1 pricing is based on query and storage costs.

Database types supported by Cloudflare Workers

Cloudflare Workers can connect to and query data in SQL and NoSQL databases. Supported types include Cloudflare's D1 (serverless SQL database), traditional hosted relational databases like Postgres and MySQL via Hyperdrive, and serverless databases including Supabase, MongoDB Atlas, PlanetScale, and Prisma.

Supabase connection methods

Supabase can be connected via Hyperdrive, or using native PostgreSQL drivers (node-postgres or Postgres.js) or the @supabase/supabase-js API client library.

Prisma deployment on Cloudflare Workers

Prisma can be used to connect to databases from Cloudflare Workers via the prisma library using API via client library connection method.

Neon connection methods

Neon can be connected via Hyperdrive, or using native PostgreSQL drivers (node-postgres or Postgres.js) or the @neondatabase/serverless API client library.

PlanetScale connection methods

PlanetScale can be connected via Hyperdrive (MySQL or PostgreSQL variants), or using native drivers (mysql2, mysql, node-postgres, or Postgres.js) or the @planetscale/database API client library.

Serverless database drivers reference

PlanetScale: Hyperdrive (MySQL or PostgreSQL) or @planetscale/database library. Supabase: Hyperdrive or @supabase/supabase-js library. Prisma: prisma library with API via client library. Neon: Hyperdrive or @neondatabase/serverless library. Hasura: GraphQL API via fetch(). Upstash Redis: @upstash/redis library. TiDB Cloud: @tidbcloud/serverless library.

MySQL connection drivers for Workers

MySQL can be connected to using mysql2 or mysql drivers. Connection is via TCP Socket through a database driver. Hyperdrive can be used optionally for optimal performance and is recommended.

PostgreSQL connection drivers for Workers

PostgreSQL can be connected to using node-postgres or Postgres.js drivers. Connection is via TCP Socket through a database driver. Hyperdrive can be used optionally for optimal performance and is recommended.

Serverless database connection options

Serverless databases may provide direct connection to the underlying database using native database drivers with Hyperdrive for connection pooling, or provide HTTP-based proxies and serverless drivers that reduce roundtrips needed to establish secure connections. Both approaches can provide connection pooling for traditional SQL databases.

Hyperdrive recommended for TCP socket connections

Connecting to SQL databases with TCP sockets requires multiple roundtrips to establish a secure connection before a query is made. Since a connection must be re-established on every Worker invocation, this adds unnecessary latency. Using Hyperdrive is optional but recommended for optimal performance.

Hyperdrive benefits for database connections

Hyperdrive solves the latency problem of establishing new connections on every Worker invocation by pooling database connections globally. It eliminates unnecessary roundtrips and speeds up database access. When using Hyperdrive, the connection pool is managed across all Cloudflare regions and optimized for usage from Workers.

Traditional SQL databases connection protocol

Traditional databases like PostgreSQL and MySQL use TCP sockets as the de-facto standard protocol for client connectivity. SQL drivers communicate via TCP sockets to connect to the database. These drivers are widely compatible with ORM libraries and query builders.

MCP server registerTool for ChatGPT invocation

Register tools with server.registerTool() specifying a tool name, title, annotations with readOnlyHint, and _meta object with openai/outputTemplate, openai/toolInvocation/invoking, and openai/toolInvocation/invoked properties.

ChatGPT App enables bidirectional communication with ChatGPT

A ChatGPT App built on Cloudflare Workers can render rich interactive UI widgets directly in ChatGPT conversations, maintain real-time multi-user state using Durable Objects, enable bidirectional communication between your app and ChatGPT, and build multiplayer experiences that run entirely within ChatGPT.

MCP server registerResource for UI widgets

Register a UI resource with server.registerResource() specifying a URI, MIME type 'text/html+skybridge', and handler that returns HTML content. This allows ChatGPT to render interactive UI widgets.

ChessGame Durable Object extends Agent class

Create a ChatGPT App game engine by extending the Agent class from the agents SDK. Define initialState with the game board state, players tracking, and status. Each Agent instance enables isolated state per game, real-time synchronization across players, and persistent storage that survives worker restarts.

ChatGPT App uses Model Context Protocol (MCP)

A ChatGPT App uses the Model Context Protocol (MCP) to expose tools and UI resources that ChatGPT can invoke on your behalf.

AI Gateway for OpenAI analytics, caching, and rate limiting

Cloudflare's AI Gateway can be used to proxy OpenAI requests for additional features including analytics, caching, and rate limiting.

WebSocket event-based message system

WebSockets utilize an event-based system for receiving and sending messages, similar to the Workers runtime model of responding to events.

Use Durable Objects for multiple WebSocket coordination

If your application needs to coordinate among multiple WebSocket connections, such as a chat room or game match, use Durable Objects to provide a single-point-of-coordination. Clients should send messages to a single Durable Object instance, and prefer using the Durable Objects' extended WebSockets API.

WebSocket compression support

Cloudflare Workers supports WebSocket compression. Refer to WebSocket Compression configuration for more information.

Getting started documentation structure

The Getting Started section is a navigation hub for setting up your environment and building your first Cloudflare Worker. It has a sidebar order of 2 within its group, and the group index is hidden.

WebAssembly support in Workers

Workers supports WebAssembly (Wasm), a binary format that enables writing Workers in programming languages beyond those with first-class support. Languages that can compile to WebAssembly for use on Workers include C, C++, Kotlin, Go, and more.

Workers polyglot platform language support

Cloudflare Workers is a polyglot platform that provides first-class support for multiple programming languages. The specific languages with first-class support are listed in the documentation's directory. Workers also supports WebAssembly, a binary format that many languages can compile to, including C, C++, Kotlin, Go and others.

Supported languages in Cloudflare Workers

Cloudflare Workers supports multiple programming languages including JavaScript, TypeScript, Python, Rust, and WebAssembly. Framework guides are available for React, Vue, Svelte, Next, Astro, React Router, and more.

Workers use cases

Cloudflare Workers can be used for front-end applications with static assets deployed to CDN and cache, back-end applications with APIs and data stores using Smart Placement, serverless AI inference with LLMs and image generation, background jobs with cron triggers and Queues, and observability and monitoring.

Cloudflare Workers serverless platform overview

Cloudflare Workers is a serverless platform for building, deploying, and scaling applications across Cloudflare's global network with a single command. It requires no infrastructure to manage and no complex configuration.

Where to find runtime APIs documentation

Specific JavaScript APIs available in Workers are documented in the Runtime APIs section. Web standard APIs are documented separately in the JavaScript and web standard APIs section.

Workers platform supports JavaScript standards and web platform APIs

The Workers platform is designed to be JavaScript standards compliant and web-interoperable. It supports JavaScript standards as defined by TC39 (ECMAScript) and uses web platform APIs wherever possible, allowing code to be reused across client and server, as well as across WinterCG JavaScript runtimes.

Give your agent this brain