Software DevelopmentOfficial · cloudflare

Durable Objects skill for Claude

Build, debug, or review Cloudflare Durable Objects code for persistent state and coordination.

Durable Objects SKILL.md

The full skill file from cloudflare/skills (Apache-2.0).

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.

ResourceURL
Docshttps://developers.cloudflare.com/durable-objects/index.md
API Referencehttps://developers.cloudflare.com/durable-objects/api/index.md
Best Practiceshttps://developers.cloudflare.com/durable-objects/best-practices/index.md
Exampleshttps://developers.cloudflare.com/durable-objects/examples/index.md
Roles and permissionshttps://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

NeedExample
CoordinationChat rooms, multiplayer games, collaborative docs
Strong consistencyInventory, booking systems, turn-based games
Per-entity storageMulti-tenant SaaS, per-user data
Persistent connectionsWebSockets, real-time notifications
Scheduled work per entitySubscription 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.

How to install Durable Objects

Claude Code

Copy the skill into your personal skills folder (or into .claude/skills/ inside a project):

npx degit cloudflare/skills/skills/durable-objects#main ~/.claude/skills/durable-objects

Codex

npx degit cloudflare/skills/skills/durable-objects#main ~/.codex/skills/durable-objects

Claude.ai and Claude Desktop

Download the skill folder from GitHub, zip it, and upload it under Settings → Capabilities → Skills.

Frequently asked questions

+What does the Durable Objects skill do?

Build, debug, or review Cloudflare Durable Objects code for persistent state and coordination.

+How do I install Durable Objects in Claude Code?

Copy the skill folder into ~/.claude/skills/durable-objects, for example with "npx degit cloudflare/skills/skills/durable-objects#main ~/.claude/skills/durable-objects". Claude Code loads it automatically and uses it when a task matches.

+Does Durable Objects work with ChatGPT or Codex?

Yes. Durable Objects uses the open SKILL.md format. In Codex, put the folder in ~/.codex/skills/durable-objects. In Claude.ai, zip the folder and upload it under Settings → Capabilities → Skills.

+Is Durable Objects free?

Durable Objects is published on GitHub by cloudflare under the Apache-2.0 license, which allows free use.

Related software development skills

  1. Code Review

    Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's…

    mattpocock/skills★ 327k
  2. Using Agent Skills

    Discovers and invokes agent skills. Use when starting a session, or when you need to decide which skill or workflow applies to the piece of…

    addyosmani/agent-skills★ 119k
  3. Build

    Fully automate a coding task with make-plan, do, and babysit.

    thedotmack/claude-mem★ 118k
  4. Frameworks On Cloudflare

    Official

    Build, migrate, and deploy web-framework applications on Cloudflare Workers.

    cloudflare/skills★ 3.4k
  5. Gateway Workers

    Official

    Build, debug, or review Cloudflare Workers invoked by the Forward action in Gateway HTTP policies, including the GatewayMiddleware…

    cloudflare/skills★ 3.4k
  6. Workers Development

    Official

    Run, inspect, and debug Cloudflare Workers during local development with cf dev, wrangler dev, or the Cloudflare Vite plugin, using Local…

    cloudflare/skills★ 3.4k
  7. Workers Profiling

    Official

    Profile or debug CPU usage and memory allocation in deployed Cloudflare Workers and Durable Objects.

    cloudflare/skills★ 3.4k
  8. Wrangler

    Official

    Run or troubleshoot Wrangler CLI commands in projects that have a wrangler.jsonc, wrangler.json, or wrangler.toml file, including local…

    cloudflare/skills★ 3.4k
  9. Application Form Filler

    Fill out job application form fields with context-aware, tailored answers drawn from the candidate's CV and the job description

    Paramchoudhary/ResumeSkills★ 3.2k

See all software development skills →

More skills from cloudflare

  1. K2

    Official

    Build and troubleshoot Cloudflare K2 or K2 Streams durable logs.

    cloudflare/skills★ 3.4k

All skills by cloudflare →

Give your whole team an AI agent with skills

Cody runs managed AI agents your team can message in Slack, Teams, WhatsApp and the web, with 50+ business integrations, scheduled tasks and memory. No terminal required.