durable-objects
作成者: Cloudflare
Cloudflare Durable Objectsを作成・レビューします。ステートフルな連携(チャットルーム、マルチプレイヤーゲーム、予約システム)の構築時、RPCメソッド、SQLiteストレージ、アラーム、WebSocketの実装時、またはDOコードのベストプラクティス確認時に使用します。Workers統合、wrangler設定、Vitestを使ったテストをカバーします。
npx skills add https://github.com/cloudflare/skills --skill durable-objectsDurable 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.
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/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_classesin 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
awaitbetween related storage writes (breaks atomicity) - Holding
blockConcurrencyWhile()acrossfetch()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);
});
});
Cloudflareのその他のスキル
agents-sdk
Cloudflare
Cloudflare Workers上でAgents SDKを使用してAIエージェントを構築します。ステートフルなエージェント、耐久性のあるワークフロー、リアルタイムWebSocketアプリ、スケジュールタスク、MCPサーバー、チャットアプリケーションを作成する際に読み込んでください。Agentクラス、状態管理、呼び出し可能RPC、Workflows統合、Reactフックをカバーします。
official
building-ai-agent-on-cloudflare
Cloudflare
| Cloudflare上でAIエージェントを構築します。Agents SDKを使用し、状態管理、リアルタイムWebSocket、スケジュールタスク、ツール統合、チャット機能を備え、Workersにデプロイ可能なプロダクション対応のエージェントコードを生成します。 使用するタイミング: ユーザーが「エージェントを構築」「AIエージェント」「チャットエージェント」「ステートフルエージェント」を希望する場合、「Agents SDK」に言及する場合、「リアルタイムAI」「WebSocket AI」が必要な場合、またはエージェントの「状態管理」「スケジュールタスク」「ツール呼び出し」について質問する場合。
developmentofficial
building-mcp-server-on-cloudflare
Cloudflare
Cloudflare Workers上でツール、OAuth認証、本番デプロイを備えたリモートMCP(Model Context Protocol)サーバーを構築します。サーバーコードの生成、認証プロバイダーの設定、Workersへのデプロイを行います。 使用タイミング: ユーザーが「MCPサーバーを構築」「MCPツールを作成」「リモートMCP」「MCPをデプロイ」「MCPにOAuthを追加」、またはCloudflare上のModel Context Protocolについて言及した場合。また、「MCP認証」や「MCPデプロイ」にも反応します。
developmentofficial
cloudflare
Cloudflare
Cloudflareプラットフォームに関する包括的なスキル。Workers、Pages、ストレージ(KV、D1、R2)、AI(Workers AI、Vectorize、Agents SDK)、ネットワーキング(Tunnel、Spectrum)、セキュリティ(WAF、DDoS)、およびインフラストラクチャ・アズ・コード(Terraform、Pulumi)をカバー。あらゆるCloudflare開発タスクに使用可能。
official
sandbox-sdk
Cloudflare
サンドボックス化されたアプリケーションを構築し、安全なコード実行を実現します。AIコード実行、コードインタプリタ、CI/CDシステム、インタラクティブな開発環境、または信頼できないコードの実行時にロードしてください。Sandbox SDKのライフサイクル、コマンド、ファイル、コードインタプリタ、プレビューURLをカバーします。
official
web-perf
Cloudflare
Chrome DevTools MCPを使用してウェブパフォーマンスを分析します。Core Web Vitals(FCP、LCP、TBT、CLS、Speed Index)を測定し、レンダリングをブロックするリソース、ネットワーク依存関係チェーン、レイアウトシフト、キャッシュ問題、アクセシビリティのギャップを特定します。ページ読み込みパフォーマンス、Lighthouseスコア、サイト速度の監査、プロファイリング、デバッグ、最適化を求められた際に使用します。
official
workers-best-practices
Cloudflare
Cloudflare Workersのコードをレビューし、本番環境のベストプラクティスに照らして作成します。新しいWorkersの作成時、Workerコードのレビュー時、wrangler.jsoncの設定時、または一般的なWorkersのアンチパターン(ストリーミング、フローティングプロミス、グローバルステート、シークレット、バインディング、可観測性)の確認時に読み込んでください。事前学習された知識よりもCloudflareのドキュメントからの取得を優先します。
official
wrangler
Cloudflare
Cloudflare Workers CLIを使用して、Workers、KV、R2、D1、Vectorize、Hyperdrive、Workers AI、Containers、Queues、Workflows、Pipelines、Secrets Storeのデプロイ、開発、管理を行います。wranglerコマンドを実行する前にロードして、正しい構文とベストプラクティスを確保します。
official