← CloudflareCONTENT HISTORY

Update to Cloudflare

Snapshot Oct 1, 2026 · 00:02 UTC · version 1.0.1

Collection source: not recorded for this historical snapshot.

WHAT CHANGED · RULE-BASED ANALYSIS

First saved snapshot

No earlier snapshot is available to establish a change.

Compare saved observations

Download comparison JSON
Full technical diff · 0 changed fields
Full snapshot data
{
  "name": "durable-objects",
  "description": "Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC methods, SQLite storage, alarms, WebSockets, or reviewing DO code for best practices. Covers Workers integration, wrangler config, and testing with Vitest. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.",
  "included_files": [
    {
      "relative_path": "references/rules.md",
      "size_in_bytes": 8483
    },
    {
      "relative_path": "references/testing.md",
      "size_in_bytes": 6541
    },
    {
      "relative_path": "references/workers.md",
      "size_in_bytes": 7543
    }
  ],
  "skill_md_contents": "---\nname: durable-objects\ndescription: Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC methods, SQLite storage, alarms, WebSockets, or reviewing DO code for best practices. Covers Workers integration, wrangler config, and testing with Vitest. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.\n---\n\n# Durable Objects\n\nBuild stateful, coordinated applications on Cloudflare's edge using Durable Objects.\n\n## Retrieval Sources\n\nYour knowledge of Durable Objects APIs and configuration may be outdated. **Prefer retrieval over pre-training** for any Durable Objects task.\n\n| Resource | URL |\n|----------|-----|\n| Docs | https://developers.cloudflare.com/durable-objects/ |\n| API Reference | https://developers.cloudflare.com/durable-objects/api/ |\n| Best Practices | https://developers.cloudflare.com/durable-objects/best-practices/ |\n| Examples | https://developers.cloudflare.com/durable-objects/examples/ |\n\nFetch the relevant doc page when implementing features.\n\n## When to Use\n\n- Creating new Durable Object classes for stateful coordination\n- Implementing RPC methods, alarms, or WebSocket handlers\n- Reviewing existing DO code for best practices\n- Configuring wrangler.jsonc/toml for DO bindings and migrations\n- Writing tests with `@cloudflare/vitest-pool-workers`\n- Designing sharding strategies and parent-child relationships\n\n## Reference Documentation\n\n- `./references/rules.md` - Core rules, storage, concurrency, RPC, alarms\n- `./references/testing.md` - Vitest setup, unit/integration tests, alarm testing\n- `./references/workers.md` - Workers handlers, types, wrangler config, observability\n\nSearch: `blockConcurrencyWhile`, `idFromName`, `getByName`, `setAlarm`, `sql.exec`\n\n## Core Principles\n\n### Use Durable Objects For\n\n| Need | Example |\n|------|---------|\n| Coordination | Chat rooms, multiplayer games, collaborative docs |\n| Strong consistency | Inventory, booking systems, turn-based games |\n| Per-entity storage | Multi-tenant SaaS, per-user data |\n| Persistent connections | WebSockets, real-time notifications |\n| Scheduled work per entity | Subscription renewals, game timeouts |\n\n### Do NOT Use For\n\n- Stateless request handling (use plain Workers)\n- Maximum global distribution needs\n- High fan-out independent requests\n\n## Quick Reference\n\n### Wrangler Configuration\n\n```jsonc\n// wrangler.jsonc\n{\n  \"durable_objects\": {\n    \"bindings\": [{ \"name\": \"MY_DO\", \"class_name\": \"MyDurableObject\" }]\n  },\n  \"migrations\": [{ \"tag\": \"v1\", \"new_sqlite_classes\": [\"MyDurableObject\"] }]\n}\n```\n\n### Basic Durable Object Pattern\n\n```typescript\nimport { DurableObject } from \"cloudflare:workers\";\n\nexport interface Env {\n  MY_DO: DurableObjectNamespace<MyDurableObject>;\n}\n\nexport class MyDurableObject extends DurableObject<Env> {\n  constructor(ctx: DurableObjectState, env: Env) {\n    super(ctx, env);\n    ctx.blockConcurrencyWhile(async () => {\n      this.ctx.storage.sql.exec(`\n        CREATE TABLE IF NOT EXISTS items (\n          id INTEGER PRIMARY KEY AUTOINCREMENT,\n          data TEXT NOT NULL\n        )\n      `);\n    });\n  }\n\n  async addItem(data: string): Promise<number> {\n    const result = this.ctx.storage.sql.exec<{ id: number }>(\n      \"INSERT INTO items (data) VALUES (?) RETURNING id\",\n      data\n    );\n    return result.one().id;\n  }\n}\n\nexport default {\n  async fetch(request: Request, env: Env): Promise<Response> {\n    const stub = env.MY_DO.getByName(\"my-instance\");\n    const id = await stub.addItem(\"hello\");\n    return Response.json({ id });\n  },\n};\n```\n\n## Critical Rules\n\n1. **Model around coordination atoms** - One DO per chat room/game/user, not one global DO\n2. **Use `getByName()` for deterministic routing** - Same input = same DO instance\n3. **Use SQLite storage** - Configure `new_sqlite_classes` in migrations\n4. **Initialize in constructor** - Use `blockConcurrencyWhile()` for schema setup only\n5. **Use RPC methods** - Not fetch() handler (compatibility date >= 2024-04-03)\n6. **Persist first, cache second** - Always write to storage before updating in-memory state\n7. **One alarm per DO** - `setAlarm()` replaces any existing alarm\n\n## Anti-Patterns (NEVER)\n\n- Single global DO handling all requests (bottleneck)\n- Using `blockConcurrencyWhile()` on every request (kills throughput)\n- Storing critical state only in memory (lost on eviction/crash)\n- Using `await` between related storage writes (breaks atomicity)\n- Holding `blockConcurrencyWhile()` across `fetch()` or external I/O\n\n## Stub Creation\n\n```typescript\n// Deterministic - preferred for most cases\nconst stub = env.MY_DO.getByName(\"room-123\");\n\n// From existing ID string\nconst id = env.MY_DO.idFromString(storedIdString);\nconst stub = env.MY_DO.get(id);\n\n// New unique ID - store mapping externally\nconst id = env.MY_DO.newUniqueId();\nconst stub = env.MY_DO.get(id);\n```\n\n## Storage Operations\n\n```typescript\n// SQL (synchronous, recommended)\nthis.ctx.storage.sql.exec(\"INSERT INTO t (c) VALUES (?)\", value);\nconst rows = this.ctx.storage.sql.exec<Row>(\"SELECT * FROM t\").toArray();\n\n// KV (async)\nawait this.ctx.storage.put(\"key\", value);\nconst val = await this.ctx.storage.get<Type>(\"key\");\n```\n\n## Alarms\n\n```typescript\n// Schedule (replaces existing)\nawait this.ctx.storage.setAlarm(Date.now() + 60_000);\n\n// Handler\nasync alarm(): Promise<void> {\n  // Process scheduled work\n  // Optionally reschedule: await this.ctx.storage.setAlarm(...)\n}\n\n// Cancel\nawait this.ctx.storage.deleteAlarm();\n```\n\n## Testing Quick Start\n\n```typescript\nimport { env } from \"cloudflare:test\";\nimport { describe, it, expect } from \"vitest\";\n\ndescribe(\"MyDO\", () => {\n  it(\"should work\", async () => {\n    const stub = env.MY_DO.getByName(\"test\");\n    const result = await stub.addItem(\"test\");\n    expect(result).toBe(1);\n  });\n});\n```\n"
}

SHA-256: 3e581c5ddc2d37cd7b04e5553eb297de9d53e1a9b89c9f85deefbf5e5f610d71