references/rules.md
# Durable Objects Rules & Best Practices
Choose one object per entity that needs coordinated state. Keep essential data in durable storage; in-memory state must be reconstructible. Prefer SQLite for new classes, and inspect the backend of existing classes before selecting APIs. For idle WebSocket servers, prefer hibernation and plan for state restoration.
Fetch the relevant current documentation before implementing or reviewing changes.
| Task | Documentation |
|------|---------------|
| Choose object boundaries, deterministic routing, parent-child relationships, or initialization | [Rules of Durable Objects](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/index.md) |
| Choose SQLite or maintain an existing KV-backed class | [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/index.md); [Legacy KV storage API](https://developers.cloudflare.com/durable-objects/api/legacy-kv-storage-api/index.md) |
| Review storage gates, external I/O races, transactions, or schema initialization | [Rules of Durable Objects](https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/index.md); [SQLite storage API](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/index.md); [Durable Object State](https://developers.cloudflare.com/durable-objects/api/state/index.md) |
| Configure class lifecycle changes | [Class exports](https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/index.md); [Legacy class migrations](https://developers.cloudflare.com/durable-objects/reference/durable-object-class-migrations-legacy/index.md) |
| Set placement hints or jurisdiction constraints | [Data location](https://developers.cloudflare.com/durable-objects/reference/data-location/index.md) |
| Create stubs, invoke RPC, or use HTTP handlers | [Invoke methods](https://developers.cloudflare.com/durable-objects/best-practices/create-durable-object-stubs-and-send-requests/index.md); [Namespace API](https://developers.cloudflare.com/durable-objects/api/namespace/index.md) |
| Schedule per-object work and handle retries | [Alarms](https://developers.cloudflare.com/durable-objects/api/alarms/index.md) |
| Restore WebSocket connection state after hibernation | [Use WebSockets](https://developers.cloudflare.com/durable-objects/best-practices/websockets/index.md) |
| Handle exceptions, restarts, and shutdowns | [Error handling](https://developers.cloudflare.com/durable-objects/best-practices/error-handling/index.md); [Object lifecycle](https://developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/index.md) |
For verification, use [Testing Durable Objects](testing.md). Keep API signatures, configuration, limits, and implementation examples in the linked docs.
references/skill-feedback.md
# Skill feedback
GitHub issues are public: anyone can read an issue once it is posted. Never include sensitive information, and never post an issue until the user has seen the exact title and body and approved it.
Use this when the user reports that the `durable-objects` skill gave incorrect or outdated guidance, is missing information, or could be improved. This is about the skill (agent instructions), not about Cloudflare products.
## What not to include
The issue is drafted from the conversation, so remove the following before drafting and describe the problem in general terms instead:
- Credentials, API tokens, secrets, and passwords
- Account IDs, zone IDs, and other resource identifiers
- Customer or personal data, such as names, email addresses, and IP addresses
- Internal hostnames and URLs
- Private code, configuration, and logs
## Steps
1. **Ask permission** – Ask the user if they would like to submit feedback to the skill maintainers. If they decline, move on.
2. **Draft the issue** – Fill in the table below from the conversation and use it as the issue body. Always identify which specific file and section caused the problem. Leave out everything listed in [What not to include](#what-not-to-include).
3. **Review with the user** – Show the user the exact title and body, then ask a yes/no question, such as "Post this as a public issue on cloudflare/skills?" Submit only after the user answers yes. If they ask for changes, apply them and ask again. If they answer no, do not post. Agreeing to send feedback in step 1 is not approval of the text.
4. **Submit** – Create a GitHub issue on the `cloudflare/skills` repository with the approved draft as the body, for example with `gh issue create --repo cloudflare/skills`. The title must follow this format: `skill-feedback: durable-objects: <summary of the problem>`.
5. **Share the result** – Share the issue URL with the user after submission. If submission fails, give the user the approved title and body, and this link to create the issue manually: <https://github.com/cloudflare/skills/issues/new>
## Issue body
| Field | Value |
|-------|-------|
| Type | `bug` (incorrect guidance), `outdated`, `missing`, or `improvement` |
| Skill | `durable-objects` |
| Source | File and section, e.g. `SKILL.md` > "Section name" or `references/<file>.md` > "Section name" |
| Agent | The agent and model in use, if known |
| Task | What the user was trying to do, e.g. "deploy a preview" |
| Expected | What should have happened, e.g. "Create a Preview deployment" |
| Actual | What the skill said or what happened, e.g. "Unknown option: --preview" |
| Impact | The effect on the user, e.g. "Time spent finding the correct syntax" |
| Suggested fix | How the skill should change; leave blank if unsure |
references/testing.md
# Testing Durable Objects
Use Cloudflare’s Vitest integration to exercise Durable Objects in the Workers runtime. Before changing an existing suite, inspect its installed Vitest/Cloudflare packages, configuration, and test scripts. Follow the matching API or migration guide; adding a test does not by itself require migrating the suite.
Fetch the relevant current documentation before writing setup or test code:
| Task | Documentation |
|------|---------------|
| Install compatible packages, configure Vitest and Wrangler, generate test types, run tests | [Write your first test](https://developers.cloudflare.com/workers/testing/vitest-integration/write-your-first-test/index.md) |
| Migrate an existing pool-based suite | [Migrate to Vitest plugin](https://developers.cloudflare.com/workers/testing/vitest-integration/migration-guides/migrate-to-vitest-plugin/index.md) |
| Configure bindings, runtime options, or multiple Workers | [Vitest configuration](https://developers.cloudflare.com/workers/testing/vitest-integration/configuration/index.md) |
| Test RPC, Worker HTTP routes, instance separation, SQLite storage, and alarms | [Testing Durable Objects](https://developers.cloudflare.com/durable-objects/examples/testing-with-durable-objects/index.md) |
| Inspect internals, enumerate instances, or trigger scheduled alarms with test helpers | [Test APIs](https://developers.cloudflare.com/workers/testing/vitest-integration/test-apis/index.md) |
| Choose state cleanup and concurrency behavior | [Isolation and concurrency](https://developers.cloudflare.com/workers/testing/vitest-integration/isolation-and-concurrency/index.md) |
Choose tests around the behavior being changed:
- Use RPC tests for object behavior and HTTP integration tests for Worker routing and response contracts.
- Verify that one object retains state across calls and different object identities remain independent. Inspect SQLite state when persistence itself is the contract under test; repeated calls alone do not prove recovery after restart.
- For alarms, verify the scheduled work’s effects and any rescheduling or cancellation, using the documented helper to avoid waiting for wall-clock time.
- Check the installed integration’s isolation model before reusing object names. Use separate identities or explicit cleanup where state is shared between tests.
Keep package versions, imports, configuration, helper signatures, and runnable examples in the linked documentation rather than copying them into this reference.
references/workers.md
# Cloudflare Workers Best Practices
High-level guidance for Workers that invoke Durable Objects.
## Wrangler Configuration
### wrangler.jsonc (Recommended)
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2024-12-01",
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [
{ "name": "CHAT_ROOM", "class_name": "ChatRoom" },
{ "name": "USER_SESSION", "class_name": "UserSession" }
]
},
"migrations": [
{ "tag": "v1", "new_sqlite_classes": ["ChatRoom", "UserSession"] }
],
// Environment variables
"vars": {
"ENVIRONMENT": "production"
},
// KV namespaces
"kv_namespaces": [
{ "binding": "CONFIG", "id": "abc123" }
],
// R2 buckets
"r2_buckets": [
{ "binding": "UPLOADS", "bucket_name": "my-uploads" }
],
// D1 databases
"d1_databases": [
{ "binding": "DB", "database_id": "xyz789" }
]
}
```
### wrangler.toml (Alternative)
```toml
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-12-01"
compatibility_flags = ["nodejs_compat"]
[[durable_objects.bindings]]
name = "CHAT_ROOM"
class_name = "ChatRoom"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["ChatRoom"]
[vars]
ENVIRONMENT = "production"
```
## TypeScript Types
### Environment Interface
```typescript
// src/types.ts
import { ChatRoom } from "./durable-objects/chat-room";
import { UserSession } from "./durable-objects/user-session";
export interface Env {
// Durable Objects
CHAT_ROOM: DurableObjectNamespace<ChatRoom>;
USER_SESSION: DurableObjectNamespace<UserSession>;
// KV
CONFIG: KVNamespace;
// R2
UPLOADS: R2Bucket;
// D1
DB: D1Database;
// Environment variables
ENVIRONMENT: string;
API_KEY: string; // From secrets
}
```
### Export Durable Object Classes
```typescript
// src/index.ts
export { ChatRoom } from "./durable-objects/chat-room";
export { UserSession } from "./durable-objects/user-session";
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
// Worker handler
},
};
```
## Worker Handler Pattern
```typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
try {
// Route to appropriate handler
if (url.pathname.startsWith("/api/rooms")) {
return handleRooms(request, env);
}
if (url.pathname.startsWith("/api/users")) {
return handleUsers(request, env);
}
return new Response("Not Found", { status: 404 });
} catch (error) {
console.error("Request failed:", error);
return new Response("Internal Server Error", { status: 500 });
}
},
};
async function handleRooms(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const roomId = url.searchParams.get("room");
if (!roomId) {
return Response.json({ error: "Missing room parameter" }, { status: 400 });
}
const stub = env.CHAT_ROOM.getByName(roomId);
if (request.method === "POST") {
const body = await request.json<{ userId: string; message: string }>();
const result = await stub.sendMessage(body.userId, body.message);
return Response.json(result);
}
const messages = await stub.getMessages();
return Response.json(messages);
}
```
## Request Validation
```typescript
import { z } from "zod";
const SendMessageSchema = z.object({
userId: z.string().min(1),
message: z.string().min(1).max(1000),
});
async function handleSendMessage(request: Request, env: Env): Promise<Response> {
const body = await request.json();
const result = SendMessageSchema.safeParse(body);
if (!result.success) {
return Response.json(
{ error: "Validation failed", details: result.error.issues },
{ status: 400 }
);
}
const stub = env.CHAT_ROOM.getByName(result.data.userId);
const message = await stub.sendMessage(result.data.userId, result.data.message);
return Response.json(message);
}
```
## Observability & Logging
Use [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/index.md) for structured application logs and pass objects to `console.log()` so their fields can be queried.
### Workers Traces
Use [Workers Traces](https://developers.cloudflare.com/workers/observability/traces/index.md) for automatic instrumentation of handlers, binding operations, and RPC calls. Enable `observability.traces.enabled` and choose `observability.traces.head_sampling_rate` explicitly for the workload or investigation. Enabling logs alone does not enable traces.
### Local Debugging
Start the project's dev server with `cf dev` where supported, or its Wrangler or Vite command. [Local Explorer](https://developers.cloudflare.com/workers/local-development/local-explorer/index.md) captures local traces and logs. See its docs for supported versions.
Use the Local Explorer API URL printed at startup:
- `GET /cdn-cgi/local/explorer/api` returns the OpenAPI spec.
- `POST /cdn-cgi/local/explorer/api/local/observability/query` queries traces and logs with SQL. Use the spec for request and response formats.
### Timing Limits
In production, `Date.now()` and `performance.now()` only advance after I/O, so they cannot time synchronous SQL or CPU work. Local timers advance during execution. See [performance and timers](https://developers.cloudflare.com/workers/runtime-apis/performance/index.md).
Non-I/O spans can report `0 ms` even when the operation takes longer. See [trace limitations](https://developers.cloudflare.com/workers/observability/traces/known-limitations/index.md) before using span durations.
## Error Handling
### Graceful DO Errors
```typescript
async function callDO(stub: DurableObjectStub<ChatRoom>, method: string): Promise<Response> {
try {
const result = await stub.getMessages();
return Response.json(result);
} catch (error) {
if (error instanceof Error) {
// DO threw an error
console.error({ message: "DO operation failed", error: error.message });
return Response.json(
{ error: "Service temporarily unavailable" },
{ status: 503 }
);
}
throw error;
}
}
```
### Timeout Handling
```typescript
async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error("Timeout")), ms)
);
return Promise.race([promise, timeout]);
}
// Usage
const result = await withTimeout(stub.processData(data), 5000);
```
## CORS Handling
```typescript
function corsHeaders(): HeadersInit {
return {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (request.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders() });
}
const response = await handleRooms(request, env);
// Add CORS headers to response
const newHeaders = new Headers(response.headers);
Object.entries(corsHeaders()).forEach(([k, v]) => newHeaders.set(k, v));
return new Response(response.body, {
status: response.status,
headers: newHeaders,
});
},
};
```
## Secrets Management
Set secrets via wrangler CLI (not in config files):
```bash
wrangler secret put API_KEY
wrangler secret put DATABASE_URL
```
Access in code:
```typescript
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const apiKey = env.API_KEY; // From secret
// ...
},
};
```
## Development Commands
```bash
# Local development
wrangler dev
# Deploy
wrangler deploy
# Tail logs
wrangler tail
# List DOs
wrangler d1 execute DB --command "SELECT * FROM _cf_DO"
```
SKILL.md
---
name: durable-objects
description: Build, debug, or review Cloudflare Durable Objects code for persistent state and coordination.
---
# Durable Objects
Build stateful, coordinated applications on Cloudflare's edge using Durable Objects.
## Retrieval Sources
Your knowledge of Durable Objects APIs and configuration may be outdated. **Prefer retrieval over pre-training** for any Durable Objects task.
| Resource | URL |
|----------|-----|
| Docs | https://developers.cloudflare.com/durable-objects/index.md |
| API Reference | https://developers.cloudflare.com/durable-objects/api/index.md |
| Best Practices | https://developers.cloudflare.com/durable-objects/best-practices/index.md |
| Examples | https://developers.cloudflare.com/durable-objects/examples/index.md |
| Roles and permissions | https://developers.cloudflare.com/workers/authorization/durable-objects/index.md |
Fetch the relevant doc page when implementing features.
## When to Use
- Creating new Durable Object classes for stateful coordination
- Implementing RPC methods, alarms, or WebSocket handlers
- Reviewing existing DO code for best practices
- Configuring wrangler.jsonc/toml for DO bindings and migrations
- Writing tests with Cloudflare’s Vitest integration
- Designing sharding strategies and parent-child relationships
## Reference Documentation
- `./references/rules.md` - Core rules, storage, concurrency, RPC, alarms
- [Testing reference](./references/testing.md) - Current Vitest documentation, migration choices, and test selection
- [Workers reference](./references/workers.md) - Workers handlers, types, configuration, tracing, and local debugging
Search: `blockConcurrencyWhile`, `idFromName`, `getByName`, `setAlarm`, `sql.exec`
## Core Principles
### Use Durable Objects For
| Need | Example |
|------|---------|
| Coordination | Chat rooms, multiplayer games, collaborative docs |
| Strong consistency | Inventory, booking systems, turn-based games |
| Per-entity storage | Multi-tenant SaaS, per-user data |
| Persistent connections | WebSockets, real-time notifications |
| Scheduled work per entity | Subscription renewals, game timeouts |
### Do NOT Use For
- Stateless request handling (use plain Workers)
- Maximum global distribution needs
- High fan-out independent requests
## Quick Reference
### Wrangler Configuration
```jsonc
// wrangler.jsonc
{
"durable_objects": {
"bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }]
}
```
### Basic Durable Object Pattern
```typescript
import { DurableObject } from "cloudflare:workers";
export interface Env {
MY_DO: DurableObjectNamespace<MyDurableObject>;
}
export class MyDurableObject extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
ctx.blockConcurrencyWhile(async () => {
this.ctx.storage.sql.exec(`
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
data TEXT NOT NULL
)
`);
});
}
async addItem(data: string): Promise<number> {
const result = this.ctx.storage.sql.exec<{ id: number }>(
"INSERT INTO items (data) VALUES (?) RETURNING id",
data
);
return result.one().id;
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const stub = env.MY_DO.getByName("my-instance");
const id = await stub.addItem("hello");
return Response.json({ id });
},
};
```
## Critical Rules
1. **Model around coordination atoms** - One DO per chat room/game/user, not one global DO
2. **Use `getByName()` for deterministic routing** - Same input = same DO instance
3. **Use SQLite storage** - Configure `new_sqlite_classes` in migrations
4. **Initialize in constructor** - Use `blockConcurrencyWhile()` for schema setup only
5. **Use RPC methods** - Not fetch() handler (compatibility date >= 2024-04-03)
6. **Persist first, cache second** - Always write to storage before updating in-memory state
7. **One alarm per DO** - `setAlarm()` replaces any existing alarm
## Authorization
Durable Objects do not have separate roles or permissions; access follows the Worker that implements them. Retrieve the current [Durable Objects authorization guidance](https://developers.cloudflare.com/workers/authorization/durable-objects/index.md) before granting observability or Data Studio access, and scope the Workers role to the intended Worker or Workers product.
## Anti-Patterns (NEVER)
- Single global DO handling all requests (bottleneck)
- Using `blockConcurrencyWhile()` on every request (kills throughput)
- Storing critical state only in memory (lost on eviction/crash)
- Using `await` between related storage writes (breaks atomicity)
- Holding `blockConcurrencyWhile()` across `fetch()` or external I/O
## Stub Creation
```typescript
// Deterministic - preferred for most cases
const stub = env.MY_DO.getByName("room-123");
// From existing ID string
const id = env.MY_DO.idFromString(storedIdString);
const stub = env.MY_DO.get(id);
// New unique ID - store mapping externally
const id = env.MY_DO.newUniqueId();
const stub = env.MY_DO.get(id);
```
## Storage Operations
```typescript
// SQL (synchronous, recommended)
this.ctx.storage.sql.exec("INSERT INTO t (c) VALUES (?)", value);
const rows = this.ctx.storage.sql.exec<Row>("SELECT * FROM t").toArray();
// KV (async)
await this.ctx.storage.put("key", value);
const val = await this.ctx.storage.get<Type>("key");
```
## Alarms
```typescript
// Schedule (replaces existing)
await this.ctx.storage.setAlarm(Date.now() + 60_000);
// Handler
async alarm(): Promise<void> {
// Process scheduled work
// Optionally reschedule: await this.ctx.storage.setAlarm(...)
}
// Cancel
await this.ctx.storage.deleteAlarm();
```
## Testing
Read the [testing reference](./references/testing.md) before configuring a suite or writing Durable Object tests. It routes to current setup, APIs, and examples and identifies the behavior to cover.
## Skill feedback
If the user reports that this skill gave incorrect or outdated guidance, or is missing information, read [references/skill-feedback.md](references/skill-feedback.md).