← Back to Skills Marketplace
creativerezz

Durable Objects

by Reza · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ Security Clean
22
Downloads
0
Stars
0
Active Installs
1
Versions
Install in OpenClaw
/install durable-objects
Description
Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC meth...
README (SKILL.md)

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/
API Reference https://developers.cloudflare.com/durable-objects/api/
Best Practices https://developers.cloudflare.com/durable-objects/best-practices/
Examples https://developers.cloudflare.com/durable-objects/examples/

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\x3CMyDurableObject>;
}

export class MyDurableObject extends DurableObject\x3CEnv> {
  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\x3Cnumber> {
    const result = this.ctx.storage.sql.exec\x3C{ id: number }>(
      "INSERT INTO items (data) VALUES (?) RETURNING id",
      data
    );
    return result.one().id;
  }
}

export default {
  async fetch(request: Request, env: Env): Promise\x3CResponse> {
    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

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\x3CRow>("SELECT * FROM t").toArray();

// KV (async)
await this.ctx.storage.put("key", value);
const val = await this.ctx.storage.get\x3CType>("key");

Alarms

// Schedule (replaces existing)
await this.ctx.storage.setAlarm(Date.now() + 60_000);

// Handler
async alarm(): Promise\x3Cvoid> {
  // 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);
  });
});
Usage Guidance
Before using the production logging examples, avoid forwarding secrets, auth headers, tokens, raw request bodies, or unnecessary user identifiers. Treat Wrangler deploy and secret commands as real Cloudflare account operations and review configuration changes before applying them.
Capability Tags
cryptorequires-sensitive-credentials
Capability Assessment
Purpose & Capability
The skill teaches how to create, configure, test, and review Cloudflare Durable Objects, Workers handlers, storage, alarms, WebSockets, and Wrangler configuration; these capabilities match the declared purpose.
Instruction Scope
The instructions are broad technical guidance and encourage consulting Cloudflare documentation, but they do not contain role overrides, hidden behavior, unrelated data access, or prompt-injection style instructions.
Install Mechanism
The artifact contains only Markdown files and no executable scripts, install hooks, binaries, or package code.
Credentials
Examples include Wrangler deploy, secrets setup, production logging, and Tail Workers, which are expected for Cloudflare Workers development but may affect real infrastructure if the user applies them.
Persistence & Privilege
Persistent storage, alarms, and log forwarding are part of the Durable Objects/Workers domain and are disclosed in the guidance; the skill itself does not create persistence or request elevated local privileges.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install durable-objects
  3. After installation, invoke the skill by name or use /durable-objects
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
v1.0.0
Initial release of the durable-objects skill. - Create and review Cloudflare Durable Objects for stateful apps, RPC, WebSockets, alarms, and SQLite storage. - Strong bias toward retrieving latest documentation from Cloudflare resources rather than relying on pre-trained knowledge. - Covers Workers integration, wrangler configuration, code review, and best practices for Durable Objects. - Quick references and patterns for configuration, storage, alarms, sharding, and stub usage. - Guidance and anti-patterns included for building robust, scalable stateful systems.
Metadata
Slug durable-objects
Version 1.0.0
License MIT-0
All-time Installs 0
Active Installs 0
Total Versions 1
Frequently Asked Questions

What is Durable Objects?

Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC meth... It is an AI Agent Skill for Claude Code / OpenClaw, with 22 downloads so far.

How do I install Durable Objects?

Run "/install durable-objects" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is Durable Objects free?

Yes, Durable Objects is completely free, licensed under MIT-0. You can download, install and use it at no cost.

Which platforms does Durable Objects support?

Durable Objects is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created Durable Objects?

It is built and maintained by Reza (@creativerezz); the current version is v1.0.0.

💬 Comments