Cloudflare Durable Objects

Builds and reviews Cloudflare Durable Objects: one object per entity, SQLite storage and migrations, RPC methods, alarms, WebSockets and Vitest tests, with links to current docs. Use when a Workers app needs shared state or coordination.

CodingPack: Cloudflare skills184 linesdurable-objects
Author
Source
cloudflare/skills/skills/durable-objects @ 5108325
License
Apache-2.0

About this skill

What it does

The skill helps the agent build, debug and review Cloudflare Durable Objects: classes that hold the state and storage of one entity, such as a chat room or a user. SKILL.md lists when they fit: coordination, strong consistency for inventory or bookings, per-entity storage, WebSockets, scheduled work per entity.

Seven rules carry most of it: one object per coordination atom, never one global object; getByName() for deterministic routing; SQLite storage through new_sqlite_classes migrations; blockConcurrencyWhile() only for schema setup in the constructor; RPC methods rather than a fetch() handler; write to storage before updating memory; one alarm per object, since setAlarm() replaces the previous one. The anti-patterns add no await between related storage writes, which breaks atomicity, and no external I/O inside blockConcurrencyWhile(). Access follows the Worker that implements the object; there are no separate roles.

references/rules.md maps design questions, from SQLite versus legacy KV storage to migrations and WebSocket hibernation, to docs pages. testing.md routes to the Vitest integration docs and lists what to test, such as state across calls and alarms without waiting for wall-clock time. workers.md covers the Worker side: config with KV, R2 and D1 bindings, Zod validation, CORS, timeouts, traces and Local Explorer. skill-feedback.md sends a fault report to cloudflare/skills once you approve the text.

When to use it, and when not

Use it for a new Durable Object class, alarms, RPC or WebSocket handlers, migrations, or a review of existing objects.

The skill itself rules out stateless handlers, maximum global distribution and high fan-out of independent requests.

How to run it

The install command below puts SKILL.md, the four references and the licence in place. The agent fetches the linked docs, so it needs web access. To call the skill yourself:

  • Claude Code: /durable-objects, or ask for the skill by name.
  • Codex: $durable-objects.
  • Cursor: type / in the Agent chat and pick durable-objects.

Example: /durable-objects Design a per-room chat object with SQLite message history and an inactivity alarm.

How it differs from similar skills

Cloudflare Agents SDK builds on the same objects: each agent class is a Durable Object with state sync, scheduling and RPC added; this skill is for writing the objects yourself. Cloudflare Workers best practices covers the Worker around them and sends Durable Objects questions here; note that workers.md writes Env by hand, which that skill flags in favour of wrangler types. Neon Functions also holds WebSocket connections and in-memory state, but in one long-running function next to Postgres, not one object per entity.

Install

Run one command — it saves SKILL.md and the files it uses into your agent's skills folder. Claude Code and Codex pick up a new skill without a restart; if it does not show up, restart the agent.

Claude Code — macOS, Linux
curl -fsSL --create-dirs -o ~/.claude/skills/durable-objects/SKILL.md https://anymodel.org/en/skills/cloudflare/durable-objects/SKILL.md -o ~/.claude/skills/durable-objects/LICENSE https://anymodel.org/en/skills/cloudflare/durable-objects/LICENSE -o ~/.claude/skills/durable-objects/references/rules.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/rules.md -o ~/.claude/skills/durable-objects/references/skill-feedback.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/skill-feedback.md -o ~/.claude/skills/durable-objects/references/testing.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/testing.md -o ~/.claude/skills/durable-objects/references/workers.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/workers.md
Codex, Cursor — macOS, Linux
curl -fsSL --create-dirs -o ~/.agents/skills/durable-objects/SKILL.md https://anymodel.org/en/skills/cloudflare/durable-objects/SKILL.md -o ~/.agents/skills/durable-objects/LICENSE https://anymodel.org/en/skills/cloudflare/durable-objects/LICENSE -o ~/.agents/skills/durable-objects/references/rules.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/rules.md -o ~/.agents/skills/durable-objects/references/skill-feedback.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/skill-feedback.md -o ~/.agents/skills/durable-objects/references/testing.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/testing.md -o ~/.agents/skills/durable-objects/references/workers.md https://anymodel.org/en/skills/cloudflare/durable-objects/references/workers.md
Claude Code — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE','references/rules.md','references/skill-feedback.md','references/testing.md','references/workers.md') { $p = Join-Path "$HOME\.claude\skills\durable-objects" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/cloudflare/durable-objects/$f" -UseBasicParsing -OutFile $p }
Codex, Cursor — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE','references/rules.md','references/skill-feedback.md','references/testing.md','references/workers.md') { $p = Join-Path "$HOME\.agents\skills\durable-objects" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/cloudflare/durable-objects/$f" -UseBasicParsing -OutFile $p }

Any other agent: save the file into its skills folder, or give it the link to the file: https://anymodel.org/en/skills/cloudflare/durable-objects/SKILL.md

SKILL.md

Raw

Durable 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.

Resource URL
Docs https://developers.cloudflare.com/durable-objects/index.md
API Reference https://developers.cloudflare.com/durable-objects/api/index.md
Best Practices https://developers.cloudflare.com/durable-objects/best-practices/index.md
Examples https://developers.cloudflare.com/durable-objects/examples/index.md
Roles and permissions https://developers.cloudflare.com/workers/authorization/durable-objects/index.md

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’s Vitest integration
  • Designing sharding strategies and parent-child relationships

Reference Documentation

  • ./references/rules.md - Core rules, storage, concurrency, RPC, alarms
  • Testing reference - Current Vitest documentation, migration choices, and test selection
  • Workers reference - Workers handlers, types, configuration, tracing, and local debugging

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

  1. Model around coordination atoms - One DO per chat room/game/user, not one global DO
  2. Use getByName() for deterministic routing - Same input = same DO instance
  3. Use SQLite storage - Configure new_sqlite_classes in migrations
  4. Initialize in constructor - Use blockConcurrencyWhile() for schema setup only
  5. Use RPC methods - Not fetch() handler (compatibility date >= 2024-04-03)
  6. Persist first, cache second - Always write to storage before updating in-memory state
  7. One alarm per DO - setAlarm() replaces any existing alarm

Authorization

Durable Objects do not have separate roles or permissions; access follows the Worker that implements them. Retrieve the current Durable Objects authorization guidance before granting observability or Data Studio access, and scope the Workers role to the intended Worker or Workers product.

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

Read the testing reference before configuring a suite or writing Durable Object tests. It routes to current setup, APIs, and examples and identifies the behavior to cover.

Skill feedback

If the user reports that this skill gave incorrect or outdated guidance, or is missing information, read references/skill-feedback.md.

Connect through AnyModel API

This skill runs on whatever model your agent uses. Point Claude Code, Codex or Cursor at AnyModel to run it on Claude, GPT, Gemini and more with one key — pay per token, no subscription.

More from the pack Cloudflare skills

Cloudflare Workers best practices

Checks Cloudflare Workers code and config against production rules: current compatibility dates, logs and traces, streaming, waitUntil, bindings over REST calls, Web Crypto, generated Env types. Use when writing, reviewing or shipping a Worker.

Wrangler CLI

Guides Wrangler commands and config in projects with wrangler.jsonc or wrangler.toml, checking installed help and current docs and guarding secrets, environments and Previews. Use when deploying, configuring or debugging a Worker with Wrangler.

Cloudflare Agents SDK

Builds and reviews apps on Cloudflare's Agents SDK: stateful agents on Durable Objects, callable RPC, scheduling, queues, Workflows, AIChatAgent chat, MCP and email. Use when building an AI agent or chat app on Workers.

Web frameworks on Cloudflare Workers

Sets up Astro, SvelteKit, React Router, TanStack Start, Nuxt, Hono and SPA apps on Cloudflare Workers, choosing C3, Wrangler or cf by the project's state. Use when creating, migrating or deploying a framework app on Workers.

Local Workers development

Runs and debugs Workers locally with cf dev, wrangler dev or the Vite plugin, using Local Explorer to read and seed binding data and query traces. Use when a local request fails or you need to see what a binding returned.

Cloudflare cf CLI

Finds and runs commands of Cloudflare's beta cf CLI through cf cli search, cf schema and dry runs, and picks cf or Wrangler per project. Use when managing DNS, zones, D1, KV or R2 from the terminal or starting a new Workers project.

Web performance audit

Audits a web page's loading performance through Chrome DevTools MCP: a trace, Core Web Vitals against thresholds, network, an accessibility snapshot and bundle config, with ranked fixes. Use when a page is slow or its Lighthouse score is low.