durable-objects
por Cloudflare
Criar e revisar Durable Objects do Cloudflare. Use ao construir coordenação com estado (salas de chat, jogos multiplayer, sistemas de reserva), implementar métodos RPC, armazenamento SQLite, alarmes, WebSockets ou revisar código DO para melhores práticas. Abrange integração com Workers, configuração do wrangler e testes com Vitest.
npx skills add https://github.com/cloudflare/skills --skill durable-objectsDurable 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.
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<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
- Model around coordination atoms - One DO per chat room/game/user, not one global DO
- Use
getByName()for deterministic routing - Same input = same DO instance - Use SQLite storage - Configure
new_sqlite_classesin migrations - Initialize in constructor - Use
blockConcurrencyWhile()for schema setup only - Use RPC methods - Not fetch() handler (compatibility date >= 2024-04-03)
- Persist first, cache second - Always write to storage before updating in-memory state
- 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
awaitbetween related storage writes (breaks atomicity) - Holding
blockConcurrencyWhile()acrossfetch()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);
});
});
Mais skills de Cloudflare
agents-sdk
Cloudflare
Construa agentes de IA no Cloudflare Workers usando o Agents SDK. Carregue ao criar agentes com estado, fluxos de trabalho duráveis, aplicativos WebSocket em tempo real, tarefas agendadas, servidores MCP ou aplicativos de chat. Abrange a classe Agent, gerenciamento de estado, RPC chamável, integração com Workflows e hooks React.
official
building-ai-agent-on-cloudflare
Cloudflare
Constrói agentes de IA na Cloudflare usando o Agents SDK com gerenciamento de estado, WebSockets em tempo real, tarefas agendadas, integração de ferramentas e capacidades de chat. Gera código de agente pronto para produção implantado em Workers. Use quando: o usuário quiser "construir um agente", "agente de IA", "agente de chat", "agente com estado", mencionar "Agents SDK", precisar de "IA em tempo real", "WebSocket de IA", ou perguntar sobre "gerenciamento de estado" do agente, "tarefas agendadas" ou "chamada de ferramentas".
developmentofficial
building-mcp-server-on-cloudflare
Cloudflare
Constrói servidores MCP (Model Context Protocol) remotos no Cloudflare Workers com ferramentas, autenticação OAuth e implantação em produção. Gera código do servidor, configura provedores de autenticação e faz deploy nos Workers. Use quando: o usuário quiser "construir servidor MCP", "criar ferramentas MCP", "MCP remoto", "implantar MCP", adicionar "OAuth ao MCP" ou mencionar Model Context Protocol no Cloudflare. Também ativa em "autenticação MCP" ou "implantação 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
Construa aplicações em sandbox para execução segura de código. Carregue ao construir execução de código por IA, interpretadores de código, sistemas de CI/CD, ambientes de desenvolvimento interativos ou ao executar código não confiável. Abrange o ciclo de vida do Sandbox SDK, comandos, arquivos, interpretador de código e URLs de pré-visualização.
official
web-perf
Cloudflare
Analisa o desempenho web usando o Chrome DevTools MCP. Mede os Core Web Vitals (FCP, LCP, TBT, CLS, Speed Index), identifica recursos que bloqueiam a renderização, cadeias de dependência de rede, mudanças de layout, problemas de cache e lacunas de acessibilidade. Use quando solicitado a auditar, perfilar, depurar ou otimizar o desempenho de carregamento de páginas, pontuações do Lighthouse ou velocidade do site.
official
workers-best-practices
Cloudflare
Revisa e orienta o código do Cloudflare Workers de acordo com as melhores práticas de produção. Carregue ao escrever novos Workers, revisar código de Workers, configurar o wrangler.jsonc ou verificar anti-padrões comuns de Workers (streaming, promessas soltas, estado global, segredos, bindings, observabilidade). Prioriza a recuperação da documentação do Cloudflare em vez do conhecimento pré-treinado.
official
wrangler
Cloudflare
CLI do Cloudflare Workers para implantar, desenvolver e gerenciar Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines e Secrets Store. Carregue antes de executar comandos wrangler para garantir sintaxe correta e melhores práticas.
official