Durable Objects 与有状态协调
使用 Durable Objects 为原本无状态的边缘架构添加强一致性、单实例状态和协调能力。
Durable Objects 与有状态协调 是 CoddyKit 上的免费 Edge Computing with Cloudflare Workers & Deno 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Edge Computing with Cloudflare Workers & Deno 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「Durable Objects 与有状态协调」课时是免费的吗?
是的 — 「Durable Objects 与有状态协调」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Edge Computing with Cloudflare Workers & Deno 课程的其余内容,请升级到 CoddyKit PRO。 Edge Computing with Cloudflare Workers & Deno 课程共包含 4 节课。
「Durable Objects 与有状态协调」这节课中我会学到什么?
使用 Durable Objects 为原本无状态的边缘架构添加强一致性、单实例状态和协调能力。 你通过在浏览器中直接运行的动手代码来练习 Edge Computing with Cloudflare Workers & Deno,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Edge Computing with Cloudflare Workers & Deno 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Edge Computing with Cloudflare Workers & Deno 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「Durable Objects 与有状态协调」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Edge Computing with Cloudflare Workers & Deno 课中编写并运行代码吗?
能。每节 Edge Computing with Cloudflare Workers & Deno 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。