durable-objects

Tạo và xem xét Cloudflare Durable Objects. Sử dụng khi xây dựng phối hợp có trạng thái (phòng chat, trò chơi nhiều người chơi, hệ thống đặt chỗ), triển khai phương thức RPC, lưu trữ SQLite, báo thức, WebSockets, hoặc xem xét mã DO để áp dụng các phương pháp tốt nhất. Bao gồm tích hợp Workers, cấu hình wrangler và kiểm thử với Vitest.

npx skills add https://github.com/cloudflare/skills --skill durable-objects

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/
API Referencehttps://developers.cloudflare.com/durable-objects/api/
Best Practiceshttps://developers.cloudflare.com/durable-objects/best-practices/
Exampleshttps://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

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

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 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);
  });
});

Thêm skills từ Cloudflare

agents-sdk
Cloudflare
Xây dựng AI agent trên Cloudflare Workers bằng Agents SDK. Tải khi tạo agent có trạng thái, quy trình làm việc bền vững, ứng dụng WebSocket thời gian thực, tác vụ theo lịch, máy chủ MCP hoặc ứng dụng trò chuyện. Bao gồm lớp Agent, quản lý trạng thái, RPC có thể gọi, tích hợp Workflows và React hooks.
official
building-ai-agent-on-cloudflare
Cloudflare
| Xây dựng các tác tử AI trên Cloudflare bằng Agents SDK với quản lý trạng thái, WebSocket thời gian thực, tác vụ theo lịch, tích hợp công cụ và khả năng trò chuyện. Tạo mã tác tử sẵn sàng cho production được triển khai lên Workers. Sử dụng khi: người dùng muốn "xây dựng tác tử", "tác tử AI", "tác tử trò chuyện", "tác tử có trạng thái", đề cập đến "Agents SDK", cần "AI thời gian thực", "WebSocket AI", hoặc hỏi về "quản lý trạng thái" tác tử, "tác vụ theo lịch" hoặc "gọi công cụ".
developmentofficial
building-mcp-server-on-cloudflare
Cloudflare
| Xây dựng máy chủ MCP (Model Context Protocol) từ xa trên Cloudflare Workers với các công cụ, xác thực OAuth và triển khai sản xuất. Tạo mã máy chủ, cấu hình nhà cung cấp xác thực và triển khai lên Workers. Sử dụng khi: người dùng muốn "xây dựng máy chủ MCP", "tạo công cụ MCP", "MCP từ xa", "triển khai MCP", thêm "OAuth vào MCP" hoặc đề cập đến Model Context Protocol trên Cloudflare. Cũng kích hoạt khi có "xác thực MCP" hoặc "triển khai MCP".
developmentofficial
cloudflare
Cloudflare
Comprehensive Cloudflare platform skill covering Workers, Pages, storage (KV, D1, R2), AI (Workers AI, Vectorize, Agents SDK), networking (Tunnel, Spectrum), security (WAF, DDoS), and infrastructure-as-code (Terraform, Pulumi). Use for any Cloudflare development task. references: - workers - pages - d1 - durable-objects - workers-ai
official
sandbox-sdk
Cloudflare
Xây dựng các ứng dụng sandbox để thực thi mã an toàn. Tải khi xây dựng hệ thống thực thi mã AI, trình thông dịch mã, hệ thống CI/CD, môi trường phát triển tương tác hoặc thực thi mã không đáng tin cậy. Bao gồm vòng đời Sandbox SDK, lệnh, tệp, trình thông dịch mã và URL xem trước.
official
web-perf
Cloudflare
Phân tích hiệu suất web bằng Chrome DevTools MCP. Đo lường Core Web Vitals (FCP, LCP, TBT, CLS, Speed Index), xác định tài nguyên chặn hiển thị, chuỗi phụ thuộc mạng, thay đổi bố cục, vấn đề bộ nhớ đệm và lỗ hổng khả năng tiếp cận. Sử dụng khi được yêu cầu kiểm tra, lập hồ sơ, gỡ lỗi hoặc tối ưu hóa hiệu suất tải trang, điểm Lighthouse hoặc tốc độ trang web.
official
workers-best-practices
Cloudflare
Xem xét và tác giả mã Cloudflare Workers theo các phương pháp thực hành tốt nhất cho sản xuất. Tải khi viết Workers mới, xem xét mã Worker, cấu hình wrangler.jsonc, hoặc kiểm tra các phản mẫu Workers phổ biến (streaming, floating promises, global state, secrets, bindings, observability). Ưu tiên truy xuất từ tài liệu Cloudflare hơn kiến thức được huấn luyện trước.
official
wrangler
Cloudflare
CLI của Cloudflare Workers để triển khai, phát triển và quản lý Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines và Secrets Store. Tải trước khi chạy các lệnh wrangler để đảm bảo cú pháp chính xác và các phương pháp tốt nhất.
official