$npx -y skills add cloudflare/skills --skill durable-objectsCreate 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 conf
| 1 | # Durable Objects |
| 2 | |
| 3 | Build stateful, coordinated applications on Cloudflare's edge using Durable Objects. |
| 4 | |
| 5 | ## Retrieval Sources |
| 6 | |
| 7 | Your knowledge of Durable Objects APIs and configuration may be outdated. **Prefer retrieval over pre-training** for any Durable Objects task. |
| 8 | |
| 9 | | Resource | URL | |
| 10 | |----------|-----| |
| 11 | | Docs | https://developers.cloudflare.com/durable-objects/ | |
| 12 | | API Reference | https://developers.cloudflare.com/durable-objects/api/ | |
| 13 | | Best Practices | https://developers.cloudflare.com/durable-objects/best-practices/ | |
| 14 | | Examples | https://developers.cloudflare.com/durable-objects/examples/ | |
| 15 | |
| 16 | Fetch the relevant doc page when implementing features. |
| 17 | |
| 18 | ## When to Use |
| 19 | |
| 20 | - Creating new Durable Object classes for stateful coordination |
| 21 | - Implementing RPC methods, alarms, or WebSocket handlers |
| 22 | - Reviewing existing DO code for best practices |
| 23 | - Configuring wrangler.jsonc/toml for DO bindings and migrations |
| 24 | - Writing tests with `@cloudflare/vitest-pool-workers` |
| 25 | - Designing sharding strategies and parent-child relationships |
| 26 | |
| 27 | ## Reference Documentation |
| 28 | |
| 29 | - `./references/rules.md` - Core rules, storage, concurrency, RPC, alarms |
| 30 | - `./references/testing.md` - Vitest setup, unit/integration tests, alarm testing |
| 31 | - `./references/workers.md` - Workers handlers, types, wrangler config, observability |
| 32 | |
| 33 | Search: `blockConcurrencyWhile`, `idFromName`, `getByName`, `setAlarm`, `sql.exec` |
| 34 | |
| 35 | ## Core Principles |
| 36 | |
| 37 | ### Use Durable Objects For |
| 38 | |
| 39 | | Need | Example | |
| 40 | |------|---------| |
| 41 | | Coordination | Chat rooms, multiplayer games, collaborative docs | |
| 42 | | Strong consistency | Inventory, booking systems, turn-based games | |
| 43 | | Per-entity storage | Multi-tenant SaaS, per-user data | |
| 44 | | Persistent connections | WebSockets, real-time notifications | |
| 45 | | Scheduled work per entity | Subscription renewals, game timeouts | |
| 46 | |
| 47 | ### Do NOT Use For |
| 48 | |
| 49 | - Stateless request handling (use plain Workers) |
| 50 | - Maximum global distribution needs |
| 51 | - High fan-out independent requests |
| 52 | |
| 53 | ## Quick Reference |
| 54 | |
| 55 | ### Wrangler Configuration |
| 56 | |
| 57 | ```jsonc |
| 58 | // wrangler.jsonc |
| 59 | { |
| 60 | "durable_objects": { |
| 61 | "bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }] |
| 62 | }, |
| 63 | "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }] |
| 64 | } |
| 65 | ``` |
| 66 | |
| 67 | ### Basic Durable Object Pattern |
| 68 | |
| 69 | ```typescript |
| 70 | import { DurableObject } from "cloudflare:workers"; |
| 71 | |
| 72 | export interface Env { |
| 73 | MY_DO: DurableObjectNamespace<MyDurableObject>; |
| 74 | } |
| 75 | |
| 76 | export class MyDurableObject extends DurableObject<Env> { |
| 77 | constructor(ctx: DurableObjectState, env: Env) { |
| 78 | super(ctx, env); |
| 79 | ctx.blockConcurrencyWhile(async () => { |
| 80 | this.ctx.storage.sql.exec(` |
| 81 | CREATE TABLE IF NOT EXISTS items ( |
| 82 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 83 | data TEXT NOT NULL |
| 84 | ) |
| 85 | `); |
| 86 | }); |
| 87 | } |
| 88 | |
| 89 | async addItem(data: string): Promise<number> { |
| 90 | const result = this.ctx.storage.sql.exec<{ id: number }>( |
| 91 | "INSERT INTO items (data) VALUES (?) RETURNING id", |
| 92 | data |
| 93 | ); |
| 94 | return result.one().id; |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | export default { |
| 99 | async fetch(request: Request, env: Env): Promise<Response> { |
| 100 | const stub = env.MY_DO.getByName("my-instance"); |
| 101 | const id = await stub.addItem("hello"); |
| 102 | return Response.json({ id }); |
| 103 | }, |
| 104 | }; |
| 105 | ``` |
| 106 | |
| 107 | ## Critical Rules |
| 108 | |
| 109 | 1. **Model around coordination atoms** - One DO per chat room/game/user, not one global DO |
| 110 | 2. **Use `getByName()` for deterministic routing** - Same input = same DO instance |
| 111 | 3. **Use SQLite storage** - Configure `new_sqlite_classes` in migrations |
| 112 | 4. **Initialize in constructor** - Use `blockConcurrencyWhile()` for schema setup only |
| 113 | 5. **Use RPC methods** - Not fetch() handler (compatibility date >= 2024-04-03) |
| 114 | 6. **Persist first, cache second** - Always write to storage before updating in-memory state |
| 115 | 7. **One alarm per DO** - `setAlarm()` replaces any existing alarm |
| 116 | |
| 117 | ## Anti-Patterns (NEVER) |
| 118 | |
| 119 | - Single global DO handling all requests (bottleneck) |
| 120 | - Using `blockConcurrencyWhile()` on every request (kills throughput) |
| 121 | - Storing critical state only in memory (lost on eviction/crash) |
| 122 | - Using `await` between related storage writes (breaks atomicity) |
| 123 | - Holding `blockConcurrencyWhile()` across `fetch()` or external I/O |
| 124 | |
| 125 | ## Stub Creation |
| 126 | |
| 127 | ```typescript |
| 128 | // Deterministic - preferred for most cases |
| 129 | const stub = env.MY_DO.getByName("room-123"); |
| 130 | |
| 131 | // From existing ID string |
| 132 | const id = env.MY_DO.idFromString(storedIdString); |
| 133 | const stub = env.MY_DO.get(id); |
| 134 | |
| 135 | // New unique ID - store mapping externally |
| 136 | const id = env.MY_DO.newUniqueId(); |
| 137 | const stub = env.MY_DO.get(id); |
| 138 | ``` |
| 139 | |
| 140 | ## Storage Operations |
| 141 | |
| 142 | ```typescript |
| 143 | // SQL (synchronous, recommended) |
| 144 | this.ctx.s |