blog.dopana

Back

Durable Objects (DO) provide a stateful coordination layer for Cloudflare Workers. Each DO runs as a globally unique instance — retaining state with strong consistency guarantees.

Durable Object (Globally Unique Instance)Stateless Workers (Global Edge)Persistent StoragePersistent StorageRAM (In-Memory State)RAM (In-Memory State)"All requests with same ID<br/>routeto single instance""Strong Consistency<br/>(Zero raceconditions)""Continuous state retention"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
Multiple requests - multiple instancesSingle unique instance per ID
No in-memory state retentionRetains state in RAM + persistent storage
Infinite automatic horizontal scalingScale via sharding across multiple DOs
Distributed across 330+ locationsSingle global point of execution (supports migration)

Chat Room — Basic Example#

12345678GET /?room=general&name=Alice (Upgrade: WebSocket)stub.fetch(request) [idFromName("general")]server.accept(), save 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!"WebSocket Connection InitializationReal-time Message BroadcastUser AliceUser BobStateless Worker RouterChatRoom [Durable Object]User AliceUser BobStateless Worker RouterChatRoom [Durable Object]

SQLite Storage — Built-in Storage Engine#

Each Durable Object comes equipped with its own dedicated SQLite storage:

"/increment""/get""/reset"OtherRequest: 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 With storage.sql#

Execute direct SQL queries inside Durable Objects:

"GET""POST""PUT""DELETE"OtherHTTP RequestCreate table if not exists: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 &}

Alarms — Scheduled Tasks for DO#

123456GET /?delay=5000setAlarm(futureTimestamp){"message": "Alarm set for 5000ms"}Trigger alarm() handlerPOST https://hooks.example.com/notify { event: 'alarm_fired' }setAlarm(nextHourTimestamp) [Recurring trigger]1. Schedule Timer / Alarm2. Execution upon Expiry (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. Add player session to Map2. Initialize Player state: x=0,y=03. Broadcast: type: 'players'1. Update player.x += dx,player.y += dy2. Broadcast: type: 'move'1. Calculate bullet vector &angle2. Broadcast: type: 'shoot'WebSocket Close Event1. Remove player from Map &State2. Broadcast: type: 'leave'Broadcast updated state to allconnected room players

Migration — Moving DO Across Releases#

Durable Objects support zero-downtime migrations between classes and schemas:

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

Migration types:

  • new_tag — New class tag
  • new_classes — Add multiple classes
  • rename — Rename existing class
  • transfer — Transfer data between namespaces

Pattern — Sharding#

A single Durable Object instance lives in one physical location at a time. To scale horizontally, shard keys across multiple DOs:

"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

Conclusion#

Durable Objects address the state problem in serverless computing:

  • Real-time: WebSocket connections paired with globally consistent memory state
  • Game servers: Low-latency coordination and synchronization
  • Distributed Coordination: Global locks, leader election, rate limiting
  • Embedded SQLite: Full relational queries without maintaining external databases

Architecture pattern: Keep request handling stateless on Workers, and delegate stateful coordination to Durable Objects. Shard instances to achieve unbounded scale.

References#