Durable Objects
Build stateful, coordinated applications on Cloudflare's edge using Durable Objects.
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/vitest-pool-workers
- Designing sharding strategies and parent-child relationships
Reference Documentation
./references/rules.md - Core rules, storage, concurrency, RPC, alarms
./references/testing.md - Vitest setup, unit/integration tests, alarm testing
./references/workers.md - Workers handlers, types, wrangler config, observability
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
// wrangler.jsonc
{
"durable_objects": {
"bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }]
}
Basic Durable Object Pattern
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
- Model around coordination atoms - One DO per chat room/game/user, not one global DO
- Use
getByName() for deterministic routing - Same input = same DO instance
- Use SQLite storage - Configure
new_sqlite_classes in migrations
- Initialize in constructor - Use
blockConcurrencyWhile() for schema setup only
- Use RPC methods - Not fetch() handler (compatibility date >= 2024-04-03)
- Persist first, cache second - Always write to storage before updating in-memory state
- One alarm per DO -
setAlarm() replaces any existing alarm
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
// 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
// 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
// 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 Quick Start
import { env } from "cloudflare:test";
import { describe, it, expect } from "vitest";
describe("MyDO", () => {
it("should work", async () => {
const stub = env.MY_DO.getByName("test");
const result = await stub.addItem("test");
expect(result).toBe(1);
});
});
1---2name: durable-objects3description: 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.4---5
6# Durable Objects
7
8Build stateful, coordinated applications on Cloudflare's edge using Durable Objects.
9
10## When to Use
11
12- Creating new Durable Object classes for stateful coordination
13- Implementing RPC methods, alarms, or WebSocket handlers
14- Reviewing existing DO code for best practices
15- Configuring wrangler.jsonc/toml for DO bindings and migrations
16- Writing tests with `@cloudflare/vitest-pool-workers`
17- Designing sharding strategies and parent-child relationships
18
19## Reference Documentation
20
21- `./references/rules.md` - Core rules, storage, concurrency, RPC, alarms
22- `./references/testing.md` - Vitest setup, unit/integration tests, alarm testing
23- `./references/workers.md` - Workers handlers, types, wrangler config, observability
24
25Search: `blockConcurrencyWhile`, `idFromName`, `getByName`, `setAlarm`, `sql.exec`
26
27## Core Principles
28
29### Use Durable Objects For
30
31| Need | Example |
32|------|---------|
33| Coordination | Chat rooms, multiplayer games, collaborative docs |
34| Strong consistency | Inventory, booking systems, turn-based games |
35| Per-entity storage | Multi-tenant SaaS, per-user data |
36| Persistent connections | WebSockets, real-time notifications |
37| Scheduled work per entity | Subscription renewals, game timeouts |
38
39### Do NOT Use For
40
41- Stateless request handling (use plain Workers)
42- Maximum global distribution needs
43- High fan-out independent requests
44
45## Quick Reference
46
47### Wrangler Configuration
48
49```jsonc
50// wrangler.jsonc
51{
52 "durable_objects": {
53 "bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }]
54 },
55 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }]
56}
57```
58
59### Basic Durable Object Pattern
60
61```typescript
62import { DurableObject } from "cloudflare:workers";
63
64export interface Env {
65 MY_DO: DurableObjectNamespace<MyDurableObject>;
66}
67
68export class MyDurableObject extends DurableObject<Env> {
69 constructor(ctx: DurableObjectState, env: Env) {
70 super(ctx, env);
71 ctx.blockConcurrencyWhile(async () => {
72 this.ctx.storage.sql.exec(`
73 CREATE TABLE IF NOT EXISTS items (
74 id INTEGER PRIMARY KEY AUTOINCREMENT,
75 data TEXT NOT NULL
76 )
77 `);
78 });
79 }
80
81 async addItem(data: string): Promise<number> {
82 const result = this.ctx.storage.sql.exec<{ id: number }>(
83 "INSERT INTO items (data) VALUES (?) RETURNING id",
84 data
85 );
86 return result.one().id;
87 }
88}
89
90export default {
91 async fetch(request: Request, env: Env): Promise<Response> {
92 const stub = env.MY_DO.getByName("my-instance");
93 const id = await stub.addItem("hello");
94 return Response.json({ id });
95 },
96};
97```
98
99## Critical Rules
100
1011. **Model around coordination atoms** - One DO per chat room/game/user, not one global DO
1022. **Use `getByName()` for deterministic routing** - Same input = same DO instance
1033. **Use SQLite storage** - Configure `new_sqlite_classes` in migrations
1044. **Initialize in constructor** - Use `blockConcurrencyWhile()` for schema setup only
1055. **Use RPC methods** - Not fetch() handler (compatibility date >= 2024-04-03)
1066. **Persist first, cache second** - Always write to storage before updating in-memory state
1077. **One alarm per DO** - `setAlarm()` replaces any existing alarm
108
109## Anti-Patterns (NEVER)
110
111- Single global DO handling all requests (bottleneck)
112- Using `blockConcurrencyWhile()` on every request (kills throughput)
113- Storing critical state only in memory (lost on eviction/crash)
114- Using `await` between related storage writes (breaks atomicity)
115- Holding `blockConcurrencyWhile()` across `fetch()` or external I/O
116
117## Stub Creation
118
119```typescript
120// Deterministic - preferred for most cases
121const stub = env.MY_DO.getByName("room-123");
122
123// From existing ID string
124const id = env.MY_DO.idFromString(storedIdString);
125const stub = env.MY_DO.get(id);
126
127// New unique ID - store mapping externally
128const id = env.MY_DO.newUniqueId();
129const stub = env.MY_DO.get(id);
130```
131
132## Storage Operations
133
134```typescript
135// SQL (synchronous, recommended)
136this.ctx.storage.sql.exec("INSERT INTO t (c) VALUES (?)", value);
137const rows = this.ctx.storage.sql.exec<Row>("SELECT * FROM t").toArray();
138
139// KV (async)
140await this.ctx.storage.put("key", value);
141const val = await this.ctx.storage.get<Type>("key");
142```
143
144## Alarms
145
146```typescript
147// Schedule (replaces existing)
148await this.ctx.storage.setAlarm(Date.now() + 60_000);
149
150// Handler
151async alarm(): Promise<void> {
152 // Process scheduled work
153 // Optionally reschedule: await this.ctx.storage.setAlarm(...)
154}
155
156// Cancel
157await this.ctx.storage.deleteAlarm();
158```
159
160## Testing Quick Start
161
162```typescript
163import { env } from "cloudflare:test";
164import { describe, it, expect } from "vitest";
165
166describe("MyDO", () => {
167 it("should work", async () => {
168 const stub = env.MY_DO.getByName("test");
169 const result = await stub.addItem("test");
170 expect(result).toBe(1);
171 });
172});
173```