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