blog.dopana

Back

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.

Workers vs Durable Objects#

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#

SQLite Storage — D1 Built-in#

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

SQL Queries Với storage.sql#

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

Alarm — Cron Cho DO#

Multiplayer Game Server#

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:

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#