อธิบาย Durable Objects
ทำความเข้าใจ Durable Objects สำหรับแอปพลิเคชันแบบไร้เซิร์ฟเวอร์ที่มีสถานะ โดยรักษาสถานะให้สอดคล้องกันทั่วโลก
อธิบาย Durable Objects เป็นบทเรียน Edge Computing with Cloudflare Workers & Deno ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Edge Computing with Cloudflare Workers & Deno และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Edge Computing with Cloudflare Workers & Deno มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
The State Problem at the Edge
Serverless functions, like Cloudflare Workers, are typically stateless. This means each request is processed independently, without remembering past interactions.
While great for scalability and cost-efficiency, what if you need to maintain a consistent piece of information across multiple requests or users globally? Think about a live chat room, a game lobby, or a shared counter.
Introducing Durable Objects
Cloudflare Durable Objects solve this fundamental challenge. They are a powerful primitive for building stateful serverless applications directly at the edge.
- They provide a single-instance, globally consistent object.
- Each Durable Object instance has a unique ID and its own private storage.
- They act like tiny, persistent servers that live at the edge.
Unique IDs & Global Consistency
The core concept behind Durable Objects is their unique identity. When you create or retrieve a Durable Object using a specific ID, Cloudflare ensures that only one instance of that object exists and runs globally.
No matter where a request originates from (e.g., Tokyo, New York, London), if it targets the same Durable Object ID, it will be routed to that single, consistent instance. This eliminates the need for complex distributed synchronization.
Anatomy of a Durable Object
A Durable Object is defined as a standard JavaScript class. It must have:
- A
constructor(state, env)method, wherestateprovides access to its storage andenvholds environment variables. - An
async fetch(request)method, which processes incoming HTTP requests, similar to a regular Worker.
It's essentially a self-contained, stateful mini-Worker.
Persistent Storage with state.storage
Each Durable Object instance has its own private, durable key-value storage, accessible via this.state.storage. This allows the object to persist data across invocations and even across restarts.
await this.state.storage.put('key', value): Stores data.await this.state.storage.get('key'): Retrieves data.await this.state.storage.delete('key'): Removes data.
Values can be any JSON-serializable type, making it versatile for various data needs.
Code: Counter Worker & DO
This example shows a Cloudflare Worker interacting with a simple Counter Durable Object. The DO maintains a count that persists across requests and is globally consistent.
To run this, you'd define the Counter Durable Object binding in your wrangler.toml file.
export class Counter {
constructor(state, env) {
this.state = state;
this.env = env;
}
async fetch(request) {
let url = new URL(request.url);
// Retrieve current count from storage, default to 0
let currentCount = (await this.state.storage.get("value")) || 0;
if (url.pathname === "/increment") {
currentCount++;
await this.state.storage.put("value", currentCount);
return new Response(`Count: ${currentCount}`);
} else if (url.pathname === "/decrement") {
currentCount--;
await this.state.storage.put("value", currentCount);
return new Response(`Count: ${currentCount}`);
} else if (url.pathname === "/get") {
return new Response(`Count: ${currentCount}`);
}
return new Response("Not found", { status: 404 });
}
}
export default {
async fetch(request, env) {
// Get a unique Durable Object ID based on a name
// 'COUNTER' is the binding name configured in wrangler.toml
let id = env.COUNTER.idFromName("global-counter");
// Get a 'stub' (a proxy) to interact with the Durable Object
let stub = env.COUNTER.get(id);
// Forward the incoming request to the Durable Object's fetch method
return stub.fetch(request);
}
};How the Counter Code Works
1. The Counter class defines the Durable Object's behavior, handling /increment, /decrement, and /get routes and persisting its value.
2. The main Worker's fetch handler:
- It uses
env.COUNTER.idFromName("global-counter")to obtain a deterministic ID for our counter. env.COUNTER.get(id)returns a stub, which is a network proxy to the Durable Object.stub.fetch(request)forwards the original request to the Durable Object instance, allowing it to process the request and update its state.
Global Consistency in Action
Imagine users from different locations (e.g., Europe, Asia, Americas) all interacting with the /increment endpoint of your Worker. Because they all target the "global-counter" ID, Cloudflare guarantees they will all interact with the exact same instance of the Counter Durable Object.
This ensures that the count is always consistent, regardless of the user's location, simplifying complex distributed state management that would otherwise be very challenging.
Common Use Cases for DOs
Durable Objects are ideal for scenarios requiring strong consistency and shared, mutable state at the edge:
- Real-time Collaboration: Shared whiteboards, document editing.
- Gaming: Game lobbies, player state, matchmaking.
- Live Chat: Chat rooms, message queues for real-time communication.
- Stateful APIs: Managing user sessions, shopping carts, or unique resource locks.
They bring traditional stateful patterns to the serverless edge, making complex applications simpler to build.
Quick Check: Durable Objects
Which of the following best describes the primary benefit of Cloudflare Durable Objects?
Recap: Durable Objects Explained
In this lesson, we explored Cloudflare Durable Objects, a powerful tool for stateful serverless applications.
- They provide globally consistent, single-instance state at the edge.
- Each DO has a unique ID and private, durable storage (
state.storage). - Workers interact with DOs by obtaining stubs and forwarding requests.
- They are ideal for real-time, collaborative, and stateful applications that demand strong consistency.
Durable Objects bridge the gap between stateless serverless and traditional stateful services, simplifying complex distributed systems.
คำถามที่พบบ่อย
บทเรียน “อธิบาย Durable Objects” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “อธิบาย Durable Objects” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส 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 ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Edge Computing with Cloudflare Workers & Deno หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Edge Computing with Cloudflare Workers & Deno บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “อธิบาย Durable Objects” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Edge Computing with Cloudflare Workers & Deno นี้ได้ไหม
ได้ บทเรียน Edge Computing with Cloudflare Workers & Deno ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- คลังข้อมูล Cloudflare KV
- อธิบาย Durable Objects
- การผสาน Deno กับพื้นที่จัดเก็บใกล้ผู้ใช้
- สืบค้นด้วย D1 SQL ที่เอดจ์