Durable Objects y coordinación con estado
Use Durable Objects para añadir estado fuertemente consistente de instancia única y coordinación a arquitecturas edge que, de otro modo, no tendrían estado.
Durable Objects y coordinación con estado es una lección gratuita de Edge Computing with Cloudflare Workers & Deno en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Edge Computing with Cloudflare Workers & Deno, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Stateless Problem
Workers are stateless by design, each request may hit a different instance anywhere on Earth.
That is great for scale, but hard when you need:
- A single source of truth
- Coordination between many clients
- Strong consistency, not eventual
Durable Objects solve exactly this.
What Is a Durable Object?
A Durable Object (DO) is a single, globally-addressable instance with its own private storage.
For a given object ID, all requests route to the same instance, giving you a consistent place to hold state.
Defining a Durable Object Class
A DO is a class with a fetch() method and access to persistent state.storage.
export class Counter {
constructor(state, env) {
this.state = state;
}
async fetch(request) {
let count = (await this.state.storage.get('count')) || 0;
count++;
await this.state.storage.put('count', count);
return new Response(String(count));
}
}Binding the Object
Declare the DO class as a binding in wrangler.toml and add a migration so Cloudflare knows about it.
[[durable_objects.bindings]]
name = "COUNTER"
class_name = "Counter"
[[migrations]]
tag = "v1"
new_classes = ["Counter"]Getting an Object Stub
From a Worker, derive an ID then get a stub to talk to that specific instance.
const id = env.COUNTER.idFromName('global-counter');
const stub = env.COUNTER.get(id);
const res = await stub.fetch('https://do/increment');idFromName vs newUniqueId
Two ways to get an ID:
idFromName('room-42')deterministic, same name always maps to the same object, ideal for named resources like chat roomsnewUniqueId()a brand-new unique object, ideal for per-session state
Strong Consistency Guarantee
Because every request for an ID hits the same instance and runs single-threaded, DO operations are strongly consistent, no race conditions on its own storage.
This makes DOs perfect for counters, locks, and leaderboards.
Coordinating Many Clients
A DO is a natural hub. Combined with WebSockets it can broadcast to all connected clients, the basis for collaborative apps and multiplayer rooms.
// Inside the DO: track sockets and fan out
this.sessions.forEach((ws) => ws.send(message));Storage API Basics
state.storage is a transactional key-value store local to the object.
await this.state.storage.put('user:1', { name: 'Ada' });
const user = await this.state.storage.get('user:1');
await this.state.storage.delete('user:1');Alarms for Scheduled Logic
Durable Objects support alarms, schedule the object to wake itself up later for cleanup or timeouts.
await this.state.storage.setAlarm(Date.now() + 60000);
// later, the runtime calls:
async alarm() {
await this.cleanup();
}When to Use Durable Objects
Reach for DOs when you need:
- Coordination across requests or clients
- Strong consistency on a single entity
- Real-time rooms, locks, rate counters, or queues
For simple cached reads, KV is cheaper. Choose the right tool.
Quick Check
Which method gives you a deterministic Durable Object ID for a named resource like a chat room?
Recap
Durable Objects bring stateful coordination to the edge:
- One globally-addressable instance per ID
- Private transactional storage and alarms
- Strong consistency and single-threaded execution
- Use
idFromNamefor named resources,newUniqueIdfor sessions
They are the missing piece for real-time, consistent, edge-native systems.
Preguntas frecuentes
¿La lección «Durable Objects y coordinación con estado» es gratis?
Sí — el texto completo de «Durable Objects y coordinación con estado» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Edge Computing with Cloudflare Workers & Deno, actualiza a CoddyKit PRO. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.
¿Qué aprenderé en «Durable Objects y coordinación con estado»?
Use Durable Objects para añadir estado fuertemente consistente de instancia única y coordinación a arquitecturas edge que, de otro modo, no tendrían estado. Practicas Edge Computing with Cloudflare Workers & Deno con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Edge Computing with Cloudflare Workers & Deno?
No se requiere experiencia previa. Edge Computing with Cloudflare Workers & Deno en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Durable Objects y coordinación con estado»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Edge Computing with Cloudflare Workers & Deno?
Sí. Cada lección de Edge Computing with Cloudflare Workers & Deno incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Microservicios en el edge
- Arquitecturas orientadas a eventos
- Geolocalización y localización
- Durable Objects y coordinación con estado