blog.dopana

Quay lại

Durable Objects (DO) là giải pháp stateful cho Cloudflare Workers. Mỗi DO có một instance duy nhất — state tồn tại, consistency mạnh.

Durable Object (Instance Duy Nhất Toàn Cầu)Stateless Workers (Toàn cầu)Persistent StoragePersistent StorageRAM (In-Memory State)RAM (In-Memory State)"Tất cả request cùng ID<br/>đượcđiều hướng về 1 điểm""Strong Consistency<br/>(Không bịrace condition)""Tồn tại state liên tục"Worker TokyoWorker LondonWorker USID: 'user-room-42'Active Connections & State"SQLite / KV Storage"

Workers vs Durable Objects#

Clients & BrowsersDurable Objects (Single Coordinated Instance per ID)Durable Objects (Single Coordinated Instance per ID)Chat Room DO (ID: room-456)Chat Room DO (ID: room-456)Chat Room DO (ID: room-123)Chat Room DO (ID: room-123)Cloudflare Global Edge (Stateless Workers)Cloudflare Global Edge (Stateless Workers)"Edge Connection""Edge Connection""Request""Route by ID: room-123""Route by ID: room-123""Route by ID: room-456"User A (WebSocket)User B (WebSocket)User C (HTTP REST)Worker (Edge Location 1)Worker (Edge Location 2)In-Memory State & ActiveWebSockets"Built-in SQLite / KV Storage"Alarms / TimersIn-Memory State"SQLite Storage"
WorkersDurable Objects
StatelessStateful
Nhiều request - nhiều instanceMỗi ID - một instance duy nhất
Không giữ stateGiữ state trong memory + storage
Scale vô hạnScale by sharding (nhiều DO)
330+ locationsMột location (có migration)

Chat Room — Ví Dụ Cơ Bản#

12345678GET /?room=general&name=Alice (Upgrade: WebSocket)stub.fetch(request) [idFromName("general")]server.accept(), lưu session "Alice"101 Switching Protocols (WebSocket Connected)Broadcast "Alice joined the chat"WS Message: "Hello room!"broadcast("Alice: Hello room!", sender=Alice)WS Message: "Alice: Hello room!"Khởi tạo kết nối WebSocketGửi tin nhắn Real-timeUser AliceUser BobStateless Worker RouterChatRoom [Durable Object]User AliceUser BobStateless Worker RouterChatRoom [Durable Object]

SQLite Storage — D1 Built-in#

Mỗi Durable Object có SQLite storage riêng:

"/increment""/get""/reset"KhácRequest: GET /increment /get/reseturl.pathnamestorage.get('count')storage.put('count', count + 1)storage.get('count')storage.put('count', 0)404 Not FoundReturn JSON count

SQL Queries Với storage.sql#

Dùng SQL trực tiếp với Durable Objects:

"GET""POST""PUT""DELETE"OtherHTTP RequestTạo bảng nếu chưa có:CREATE TABLE IF NOTEXISTS todos (...)HTTP MethodSELECT * FROM todosORDER BY id DESCINSERT INTO todos (title)VALUES (?)UPDATE todos SET completed= ? WHERE id = ?DELETE FROM todos WHEREid = ?405 Method Not AllowedJSON: List of todos201 Created: new todoJSON: &{ success: true &}JSON: &{ success: true &}

Alarm — Cron Cho DO#

123456GET /?delay=5000setAlarm(futureTimestamp){"message": "Alarm set for 5000ms"}Kích hoạt handler alarm()POST https://hooks.example.com/notify { event: 'alarm_fired' }setAlarm(nextHourTimestamp) [Đặt lịch lặp lại]1. Đăng ký Timer / Cron2. Kích hoạt khi hết giờ (Wake up DO)User / ClientReminder DOctx.storage [Alarm Queue]External WebhookUser / ClientReminder DOctx.storage [Alarm Queue]External Webhook

Multiplayer Game Server#

"join""move""shoot"WebSocket Message Eventmsg.type1. Lưu session player vào Map2. Thêm Player state: x=0, y=03. Broadcast: type: 'players'1. Cập nhật player.x += dx,player.y += dy2. Broadcast: type: 'move'1. Tính góc & tọa độ bắn2. Broadcast: type: 'shoot'WebSocket Close Event1. Xóa player khỏi Player Map& State2. Broadcast: type: 'leave'Gửi State cập nhật tới toàn bộngười chơi trong phòng

Migration — Di Chuyển DO#

DO có thể migrate giữa các region:

// wrangler.jsonc
{
  "durable_objects": {
    "bindings": [
      {
        "name": "COUNTER",
        "class_name": "Counter",
        "migration": "new_tag"
      }
    ]
  }
}
typescript

Migration types:

  • new_tag — Class mới
  • new_classes — Thêm nhiều class
  • rename — Đổi tên class
  • transfer — Chuyển dữ liệu

Pattern — Sharding#

Một DO chỉ chạy ở một location. Để scale, shard theo key:

"userId: 0 - 999""userId: 1000 - 1999""userId: 2000 - 2999""userId: N - N+999"Request: userIdshardId = floor(userId / 1000)Shard RouterDO Instance: shard-0DO Instance: shard-1DO Instance: shard-2DO Instance: shard-N

Kết Luận#

Durable Objects giải quyết vấn đề state trong serverless:

  • Real-time — WebSocket với state central consistency
  • Game server — multiplayer coordination
  • Coordination — distributed lock, rate limiting
  • SQLite storage — không cần DB riêng

Kiến trúc: Workers stateless cho request thông thường, DO cho những gì cần state. Shard DO theo key để scale ngang.

Tài liệu tham khảo#