cloudflare-durable-objects
Cloudflare Durable Objects for stateful coordination and real-time apps. Use for chat, multiplayer games, WebSocket hibernation, or encountering class export, migration, alarm errors.
What this skill does
# Cloudflare Durable Objects **Status**: Production Ready ✅ **Last Updated**: 2025-11-25 **Dependencies**: cloudflare-worker-base (recommended) **Latest Versions**: [email protected]+, @cloudflare/[email protected]+ **Official Docs**: https://developers.cloudflare.com/durable-objects/ ## Table of Contents [What are Durable Objects?](#what-are-durable-objects) • [Quick Start](#quick-start-10-minutes) • [When to Load References](#when-to-load-references) • [Class Structure](#durable-object-class-structure) • [State API](#state-api---persistent-storage) • [WebSocket Hibernation](#websocket-hibernation-api) • [Alarms](#alarms-api---scheduled-tasks) • [RPC vs HTTP](#rpc-vs-http-fetch) • [Stubs & Routing](#creating-durable-object-stubs-and-routing) • [Migrations](#migrations---managing-do-classes) • [Common Patterns](#common-patterns) • [Critical Rules](#critical-rules) • [Known Issues](#known-issues-prevention) ## What are Durable Objects? **Globally unique, stateful objects** with single-point coordination, strong consistency (ACID), WebSocket Hibernation (thousands of connections), SQLite storage (1GB), and alarms API. **Use for:** Chat rooms, multiplayer games, rate limiting, session management, leader election, stateful workflows --- ## Quick Start (10 Minutes) ### Option 1: Scaffold New DO Project ```bash npm create cloudflare@latest my-durable-app -- \ --template=cloudflare/durable-objects-template --ts --git --deploy false cd my-durable-app && bun install && npm run dev ``` ### Option 2: Add to Existing Worker **1. Install types:** ```bash bun add -d @cloudflare/workers-types ``` **2. Create DO class** (`src/counter.ts`): ```typescript import { DurableObject } from 'cloudflare:workers'; export class Counter extends DurableObject { async increment(): Promise<number> { let value: number = (await this.ctx.storage.get('value')) || 0; await this.ctx.storage.put('value', ++value); return value; } } export default Counter; // CRITICAL ``` **3. Configure** (`wrangler.jsonc`): ```jsonc { "durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter" }] }, "migrations": [ { "tag": "v1", "new_sqlite_classes": ["Counter"] } ] } ``` **4. Call from Worker** (`src/index.ts`): ```typescript import { Counter } from './counter'; interface Env { COUNTER: DurableObjectNamespace<Counter>; } export { Counter }; export default { async fetch(request: Request, env: Env): Promise<Response> { const stub = env.COUNTER.getByName('global-counter'); return new Response(`Count: ${await stub.increment()}`); }, }; ``` **Deploy:** ```bash bunx wrangler deploy ``` --- ## Available Commands Use these interactive commands for guided workflows: - **`/do-setup`** - Initialize new DO project with interactive setup wizard - Choose storage backend (SQL, KV, both) - Select use case pattern (WebSocket, Sessions, Rate Limiting, etc.) - Optional Vitest testing setup - Generates complete DO implementation - **`/do-migrate`** - Interactive migration assistant - New class creation (new_sqlite_classes, new_classes) - Rename existing classes (renamed_classes) - Delete classes with safety confirmations (deleted_classes) - Transfer classes between scripts (transferred_classes) - Auto-increments migration tags (v1, v2, v3...) - **`/do-debug`** - Step-by-step debugging workflow - Detects error categories (deployment, runtime, performance, etc.) - Runs diagnostic checks on configuration and code - Provides specific fixes with code examples - Guides local testing and production verification - **`/do-patterns`** - Pattern selection wizard - Recommends DO pattern based on use case - Supports WebSocket, Rate Limiting, Sessions, Analytics, Leader Election - Generates complete pattern implementation - Provides best practices and optimization tips - **`/do-optimize`** - Performance optimization assistant - Analyzes existing DO code for bottlenecks - Provides targeted optimization recommendations - Covers constructor, queries, WebSocket, memory, alarms - Measures performance improvements ## Autonomous Agents These agents work autonomously without user interaction: - **`do-debugger`** - Automatic error detection and fixing - Validates wrangler.jsonc configuration - Detects 16+ common DO errors - Applies fixes automatically with backups - Tests fixes before reporting - **`do-setup-assistant`** - Automatic project scaffolding - Analyzes user requirements from natural language - Generates complete DO implementation - Creates tests, documentation, validation - Supports all use case patterns - **`do-pattern-implementer`** - Production pattern implementation - Analyzes existing DO code - Recommends patterns by priority - Implements TTL cleanup, RPC metadata, SQL indexes, etc. - Generates pattern-specific tests --- ## When to Load References **Load immediately when user mentions:** - **`state-api-reference.md`** → "storage", "sql", "database", "query", "get/put", "KV", "1GB limit" - **`websocket-hibernation.md`** → "websocket", "real-time", "chat", "hibernation", "serializeAttachment" - **`alarms-api.md`** → "alarms", "scheduled tasks", "cron", "periodic", "batch processing" - **`rpc-patterns.md`** → "RPC", "fetch", "HTTP", "methods", "routing" - **`rpc-metadata.md`** → "RpcTarget", "metadata", "DO name", "idFromName access" - **`stubs-routing.md`** → "stubs", "idFromName", "newUniqueId", "location hints", "jurisdiction" - **`migrations-guide.md`** → "migrations", "rename", "delete", "transfer", "schema changes" - **`migration-cheatsheet.md`** → "migration quick reference", "migration types", "common migrations" - **`common-patterns.md`** → "patterns", "examples", "rate limiting", "sessions", "leader election" - **`vitest-testing.md`** → "test", "testing", "vitest", "unit test", "@cloudflare/vitest-pool-workers" - **`gradual-deployments.md`** → "gradual", "deployment", "traffic split", "rollout", "canary" - **`typescript-config.md`** → "TypeScript", "types", "tsconfig", "wrangler.jsonc", "bindings" - **`advanced-sql-patterns.md`** → "CTE", "window functions", "FTS5", "full-text search", "JSON functions", "complex SQL" - **`security-best-practices.md`** → "security", "authentication", "authorization", "SQL injection", "CORS", "encryption", "rate limiting" - **`error-codes.md`** → "error codes", "error catalog", "specific error", "E001", "troubleshooting" - **`top-errors.md`** → errors, "not working", debugging, "binding not found" **Load proactively when:** - Building new feature → Load relevant pattern from `common-patterns.md` - Debugging issue → Load `error-codes.md` for specific errors, then `top-errors.md` - Implementing WebSocket → Load `websocket-hibernation.md` before coding - Setting up storage → Load `state-api-reference.md` for SQL/KV APIs - Complex SQL queries → Load `advanced-sql-patterns.md` for CTEs, window functions, FTS5 - Security review → Load `security-best-practices.md` for authentication, authorization, SQL injection prevention - Creating first DO → Load `stubs-routing.md` for ID methods - Writing tests → Load `vitest-testing.md` for testing patterns - Planning deployment → Load `gradual-deployments.md` for rollout strategy - Migration needed → Load `migration-cheatsheet.md` for quick reference - Using DO name inside DO → Load `rpc-metadata.md` for RpcTarget pattern - TypeScript configuration → Load `typescript-config.md` for setup --- ## Durable Object Class Structure All DOs extend `DurableObject` and **MUST be exported**: ```typescript import { DurableObject } from 'cloudflare:workers'; export class MyDO extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); // Required first line // Keep minimal - heavy work blocks hibernation ctx.blockConcurrencyWhile(async () => { // Load from storage before handling requests }); } async myMethod(): Promise<string> { /
Related in Cloud & DevOps
appbuilder-action-scaffolder
IncludedCreate, implement, deploy, and debug Adobe Runtime actions with consistent layout, validation, and error handling. Use this skill whenever the user needs to add actions to an App Builder project, understand action structure (params, response format, web/raw actions), configure actions in the manifest, use App Builder SDKs (State, Files, Events, database), deploy and invoke actions via CLI, debug action issues, or implement patterns such as webhook receivers, custom event providers, journaling consumers, large payload redirects, action sequence pipelines, and Asset Compute workers. Also trigger when users mention serverless functions in Adobe context, action logging, IMS authentication for actions, or cron-style scheduled actions.
orchestrating-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. Use this skill when the user needs a multi-step Data Cloud pipeline, cross-phase troubleshooting, or data space and data kit management. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase sf data360 workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching phase-specific skill), the task is STDM/session tracing/parquet telemetry (use observing-agentforce), standard CRM SOQL (use querying-soql), or Apex implementation (use generating-apex).
github-project-automation
IncludedAutomate GitHub repository setup with CI/CD workflows, issue templates, Dependabot, and CodeQL security scanning. Includes 12 production-tested workflows and prevents 18 errors: YAML syntax, action pinning, and configuration. Use when: setting up GitHub Actions CI/CD, creating issue/PR templates, enabling Dependabot or CodeQL scanning, deploying to Cloudflare Workers, implementing matrix testing, or troubleshooting YAML indentation, action version pinning, secrets syntax, runner versions, or CodeQL configuration. Keywords: github actions, github workflow, ci/cd, issue templates, pull request templates, dependabot, codeql, security scanning, yaml syntax, github automation, repository setup, workflow templates, github actions matrix, secrets management, branch protection, codeowners, github projects, continuous integration, continuous deployment, workflow syntax error, action version pinning, runner version, github context, yaml indentation error
sf-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase `sf data360` workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching sf-datacloud-* skill), the task is STDM/session tracing/parquet telemetry (use sf-ai-agentforce-observability), standard CRM SOQL (use sf-soql), or Apex implementation (use sf-apex).
fabric-cli
IncludedUse this skill for Fabric.so CLI workflows with the `fabric` terminal command: diagnose/install/login, search or browse a Fabric library, save notes/links/files, create folders, ask the Fabric AI assistant, manage tasks/workspaces, generate shell completion, check subscription usage, produce JSON output, and use Fabric as persistent agent memory. Do not use for Microsoft Fabric/Azure/Power BI `fab`, Daniel Miessler's Fabric framework, Python Fabric SSH, Fabric.js, or textile/fashion fabric.
lark
IncludedLark/Feishu CLI skills: lark-cli operations for docs, markdown, sheets, base, calendar, im, mail, task, okr, drive, wiki, slides, whiteboard, apps, approval, attendance, contact, vc, minutes, event. Use when the user needs to operate Lark/Feishu resources via lark-cli, send messages, manage documents, spreadsheets, calendars, tasks, OKRs, deploy web pages, or any Feishu/Lark workspace operations.