durable-objects
por Cloudflare
Crear y revisar Cloudflare Durable Objects. Úselo al construir coordinación con estado (salas de chat, juegos multijugador, sistemas de reservas), implementar métodos RPC, almacenamiento SQLite, alarmas, WebSockets, o revisar código DO para mejores prácticas. Cubre integración con Workers, configuración de wrangler y pruebas con 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);
});
});
Más skills de Cloudflare
agents-sdk
Cloudflare
Construye agentes de IA en Cloudflare Workers usando el Agents SDK. Carga al crear agentes con estado, flujos de trabajo duraderos, aplicaciones WebSocket en tiempo real, tareas programadas, servidores MCP o aplicaciones de chat. Cubre la clase Agent, gestión de estado, RPC invocable, integración con Workflows y hooks de React.
official
building-ai-agent-on-cloudflare
Cloudflare
Construye agentes de IA en Cloudflare usando el SDK de Agents con gestión de estado, WebSockets en tiempo real, tareas programadas, integración de herramientas y capacidades de chat. Genera código de agente listo para producción desplegado en Workers. Úsalo cuando: el usuario quiera "construir un agente", "agente de IA", "agente de chat", "agente con estado", mencione "Agents SDK", necesite "IA en tiempo real", "WebSocket de IA", o pregunte sobre "gestión de estado" del agente, "tareas programadas" o "llamadas a herramientas".
developmentofficial
building-mcp-server-on-cloudflare
Cloudflare
Construye servidores MCP (Model Context Protocol) remotos en Cloudflare Workers con herramientas, autenticación OAuth y despliegue en producción. Genera código de servidor, configura proveedores de autenticación y despliega en Workers. Úsalo cuando: el usuario quiera "construir servidor MCP", "crear herramientas MCP", "MCP remoto", "desplegar MCP", agregar "OAuth a MCP", o mencione Model Context Protocol en Cloudflare. También se activa con "autenticación MCP" o "despliegue MCP".
developmentofficial
cloudflare
Cloudflare
Habilidad integral de la plataforma Cloudflare que cubre Workers, Pages, almacenamiento (KV, D1, R2), IA (Workers AI, Vectorize, Agents SDK), redes (Tunnel, Spectrum), seguridad (WAF, DDoS) e infraestructura como código (Terraform, Pulumi). Úsala para cualquier tarea de desarrollo en Cloudflare.
official
sandbox-sdk
Cloudflare
Construye aplicaciones en entornos aislados para la ejecución segura de código. Cárgalo al construir ejecución de código con IA, intérpretes de código, sistemas CI/CD, entornos de desarrollo interactivos o al ejecutar código no confiable. Cubre el ciclo de vida del Sandbox SDK, comandos, archivos, intérprete de código y URLs de vista previa.
official
web-perf
Cloudflare
Analiza el rendimiento web utilizando Chrome DevTools MCP. Mide Core Web Vitals (FCP, LCP, TBT, CLS, Speed Index), identifica recursos que bloquean el renderizado, cadenas de dependencia de red, cambios de diseño, problemas de caché y brechas de accesibilidad. Úsalo cuando se te pida auditar, perfilar, depurar u optimizar el rendimiento de carga de páginas, puntuaciones de Lighthouse o velocidad del sitio.
official
workers-best-practices
Cloudflare
Revisa y autoría el código de Cloudflare Workers según las mejores prácticas de producción. Cargar al escribir nuevos Workers, revisar código de Workers, configurar wrangler.jsonc o verificar anti-patrones comunes de Workers (streaming, promesas flotantes, estado global, secretos, enlaces, observabilidad). Se inclina hacia la recuperación desde la documentación de Cloudflare en lugar del conocimiento preentrenado.
official
wrangler
Cloudflare
CLI de Cloudflare Workers para desplegar, desarrollar y gestionar Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines y Secrets Store. Cargar antes de ejecutar comandos wrangler para garantizar la sintaxis correcta y las mejores prácticas.
official