| | |

Cloudflare 13 ☁️ Durable Objects & Real-Time WebSockets — Building strongly consistent state, rate limiters, and collaborative WebSocket servers

⏱️ Estimated read: 13 min | |

Standard Cloudflare Workers are inherently stateless and distributed; when a request comes in, a worker is spun up in the nearest data center, handles the request, and disappears. While this is excellent for scale, it makes coordination between users nearly impossible because two users in different cities will hit different workers that cannot easily share memory. Durable Objects (DO) solve this by providing a unique, stateful instance of a JavaScript class that lives in a single location globally. Every request for a specific Durable Object ID is routed to the exact same instance, allowing for shared state, strong consistency, and real-time communication via WebSockets.

This chapter explores the architecture of stateful edge computing. We will examine how Durable Objects provide a persistent storage API that guarantees “read-after-write” consistency, a feat not possible with the eventually consistent KV store. We will also dive deep into the WebSocket integration, showing how a Durable Object can act as a “room” or “server” where multiple clients maintain a persistent connection to synchronize state in real-time. Finally, we will cover advanced patterns like “Alarms” for scheduled execution and building high-performance global rate limiters.

The sections that follow cover the Durable Object class structure and lifecycle, the implementation of WebSocket servers for collaborative apps, and the use of persistent storage for building strongly consistent logic.

Key point: Durable Objects provide a single-instance, stateful execution environment with built-in persistent storage and WebSocket support, enabling the coordination and strong consistency that standard stateless Workers lack.


Why exists

The Coordination Problem. In a globally distributed network, having code run everywhere is great for speed but terrible for synchronization. If two users try to buy the last item in an inventory simultaneously, stateless workers in different regions might both see the item as “available.” Durable Objects provide a “Single Point of Truth” where all requests for that specific item are serialized and handled by one instance.

The State Persistence Problem. While Cloudflare KV is useful for high-read data, its eventual consistency means a write in London might not be visible in New York for several seconds. Durable Objects offer a private, persistent storage API that is strongly consistent; once a value is saved, the very next read is guaranteed to see that new value.

The WebSocket Context Problem. WebSockets require a persistent “home.” If a client connects to a stateless worker, there is no easy way for that worker to talk to another worker handling a different client. Durable Objects act as the “hub” where all clients in a specific session (like a chat room or a document) connect to the same instance, allowing for easy message broadcasting.

The Lifecycle and Alarm Problem. Sometimes logic needs to happen in the future, even if no user is currently connected. Durable Objects include an “Alarms” API that allows an object to schedule itself to wake up at a specific time to perform background tasks, like flushing logs to R2 or closing an inactive session.

The Rate Limiting Trade-off. Standard rate limiters are often “leaky” across regions. A global rate limiter built with Durable Objects can track every single request across the entire network in real-time, providing absolute precision for high-value API endpoints or security-sensitive paths.

The “Infinite Scale” via Sharding. While a single Durable Object handles one instance, you can create millions of unique IDs. This allows you to scale by sharding your application: one Durable Object per user, per chat room, or per document, ensuring that while individual units are coordinated, the system as a whole scales horizontally.


a. Durable Object Architecture and Storage

A Durable Object is defined as a JavaScript class. To use it, you must export the class from your Worker and define a binding in your wrangler.toml. The Worker acts as a “Gateway,” using the binding to generate a unique ID and then “fetching” that ID to reach the specific object instance. Once inside the object, you have access to state.storage, which provides a key-value interface directly on the object’s local disk.

// The Durable Object Class
export class Counter {
  state: DurableObjectState;

  constructor(state: DurableObjectState) {
    this.state = state;
  }

  async fetch(request: Request) {
    // Read the current value from persistent storage
    let value: number = await this.state.storage.get("count") || 0;
  
    // Increment and save (Strongly Consistent)
    value++;
    await this.state.storage.put("count", value);

    return new Response(value.toString());
  }
}

The storage API supports individual keys, bulk operations, and prefix-based listings. Because the storage is co-located with the code, it is extremely fast. However, it is important to remember that only one instance of the object exists globally at a time. Cloudflare automatically manages the placement of the object, usually moving it to the region where most traffic is originating to minimize latency.

In the wrangler.toml, you must declare the class and the binding. This tells Cloudflare which class to instantiate when a request is routed to a specific ID.

[[durable_objects.bindings]]
name = "COUNTER_OBJECT"
class_name = "Counter"

[[migrations]]
tag = "v1" # Required for the first deployment
new_classes = ["Counter"]

b. Real-Time WebSockets and Broadcasting

One of the most common use cases for Durable Objects is as a WebSocket server. When a Worker receives a WebSocket upgrade request, it can pass that request to a Durable Object. The Durable Object then “accepts” the WebSocket, maintaining the connection. The object can keep a list of all active WebSockets in memory, allowing it to broadcast messages to all connected clients.

// Inside the Durable Object fetch handler
async fetch(request: Request) {
  if (request.headers.get("Upgrade") !== "websocket") {
    return new Response("Expected Upgrade: websocket", { status: 426 });
  }

  // Create the WebSocket pair
  const [client, server] = new WebSocketPair();

  // Accept and track the connection
  server.accept();
  this.sessions.add(server); // Keep track in a Set

  server.addEventListener("message", (msg) => {
    // Broadcast message to everyone else
    for (let session of this.sessions) {
      session.send(msg.data);
    }
  });

  return new Response(null, { status: 101, webSocket: client });
}

Durable Objects handle the “hibernation” of WebSockets. If an object is idle but has open WebSockets, Cloudflare can hibernate the object to save resources and automatically wake it up when a new message arrives. This allows you to maintain thousands of concurrent connections without paying for active CPU time for every single second they are open.

To identify which Durable Object to connect to, you can use idFromName(name). This generates a deterministic ID based on a string (like a room name). All users who request the ID for “room-101” will be routed to the exact same Durable Object instance.


c. Advanced Patterns: Alarms and Rate Limiters

Durable Objects include an Alarms API, which is essentially a per-instance cron job. An object can set an alarm for a specific timestamp. When that time is reached, the alarm() method on the class is invoked. This is critical for cleanup tasks or synchronizing state to an external database like D1 or R2.

async fetch(request: Request) {
  // Set an alarm to run in 10 seconds
  await this.state.storage.setAlarm(Date.now() + 10000);
  return new Response("Alarm set");
}

async alarm() {
  // This runs even if no requests are active
  const data = await this.state.storage.get("temp_data");
  await saveToPermanentStore(data);
  await this.state.storage.delete("temp_data");
}

Building a global rate limiter with Durable Objects provides much higher precision than KV. Since every request for a specific user ID or IP passes through the same Durable Object, you can maintain a precise counter in memory. If the counter exceeds a threshold, you return a 429 status code. Because it’s a single instance, there is no propagation delay.

async fetch(request: Request) {
  let count: number = (await this.state.storage.get("req_count")) || 0;
  if (count > 100) return new Response("Too Many Requests", { status: 429 });

  await this.state.storage.put("req_count", count + 1);
  return new Response("Success");
}

The trade-off for this precision is a single point of failure (if the region where the DO lives has issues) and a throughput limit. A single Durable Object can typically handle hundreds to a few thousand requests per second. For massive scale, you must shard your data across multiple Durable Objects.


Complete Example Session

// ============================================
// PART 1: THE DURABLE OBJECT CLASS
// ============================================
export class ChatRoom {
  state: DurableObjectState;
  sessions: Set<WebSocket> = new Set();

  constructor(state: DurableObjectState) {
    this.state = state;
  }

  // ============================================
  // PART 2: THE FETCH HANDLER (GATEWAY)
  // ============================================
  async fetch(request: Request) {
    const url = new URL(request.url);
  
    // Handle persistent count storage
    if (url.pathname === "/info") {
      const count = await this.state.storage.get("msg_count") || 0;
      return new Response(`Messages sent here: ${count}`);
    }

    // Handle WebSocket Upgrade
    if (request.headers.get("Upgrade") === "websocket") {
      return this.handleWebSocket(request);
    }

    return new Response("Not Found", { status: 404 });
  }

  // ============================================
  // PART 3: WEBSOCKET LOGIC
  // ============================================
  async handleWebSocket(request: Request) {
    const [client, server] = new WebSocketPair();
    server.accept();
    this.sessions.add(server);

    server.addEventListener("message", async (msg) => {
      // PART 4: UPDATE PERSISTENT STATE
      let count: number = await this.state.storage.get("msg_count") || 0;
      await this.state.storage.put("msg_count", ++count);

      // PART 5: BROADCAST TO ALL
      for (let s of this.sessions) {
        try { s.send(msg.data); } catch (e) { this.sessions.delete(s); }
      }
    
      // PART 6: SCHEDULE CLEANUP ALARM
      await this.state.storage.setAlarm(Date.now() + 86400000); // 24h
    });

    server.addEventListener("close", () => this.sessions.delete(server));
    return new Response(null, { status: 101, webSocket: client });
  }

  // ============================================
  // PART 7: THE ALARM HANDLER
  // ============================================
  async alarm() {
    console.log("Cleaning up old room data...");
    await this.state.storage.deleteAll();
  }
}

// ============================================
// PART 8: THE WORKER (ROUTER)
// ============================================
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const roomName = url.searchParams.get("room") || "default";
  
    // PART 9: GENERATE UNIQUE ID
    const id = env.CHAT_ROOM.idFromName(roomName);
  
    // PART 10: GET OBJECT STUB AND FETCH
    const obj = env.CHAT_ROOM.get(id);
    return obj.fetch(request);
  }
}

The example above covers the full lifecycle: defining the DO, routing to it via the Worker, handling WebSockets, persistent storage, and background alarms.


Quick Reference

Durable Object Storage API

MethodDescriptionReturn Type
get(key)Get a single valuePromise<any>
put(key, val)Store a single valuePromise<void>
delete(key)Remove a keyPromise<boolean>
list(options?)List all keys/valuesPromise<Map<string, any>>
setAlarm(time)Schedule an alarmPromise<void>

Durable Object Identity

MethodDescriptionContext
idFromName(str)Deterministic ID from stringWorker (Binding)
newUniqueId()Random unique IDWorker (Binding)
idFromString(hex)Reconstruct ID from hex stringWorker (Binding)
get(id)Get a communication “Stub”Worker (Binding)

WebSocket Events

EventTriggerUsage
messageData receivedProcess logic / Broadcast
closeClient disconnectedCleanup session list
errorConnection failureLogging / Cleanup

Best Practices

✅ Do This:

// Use idFromName for deterministic resources like chat rooms
const id = env.ROOMS.idFromName("room-alpha");                 // ✅

// Handle WebSocket closures to prevent memory leaks
server.addEventListener("close", () => sessions.delete(s));    // ✅

// Use batch storage operations for performance
await state.storage.put({ key1: val1, key2: val2 });           // ✅

// Use WebGL/Hibernation API for long-lived idle WebSockets
// (Automatically managed by Cloudflare)                     // ✅

❌ Don’t Do This:

// Don't store massive amounts of data in a single DO
// (Durable Objects have a 10GB storage limit)                // ❌

// Don't use a single Durable Object for your entire app
// (It creates a global bottleneck)                            // ❌

// Don't perform long-running CPU tasks in the DO
// (It blocks the single thread for that instance)            // ❌

// Don't forget to handle 'failure' in broadcasting
try { s.send(msg); } catch (e) { /* remove stale s */ }       // ❌

Common Pitfalls

PitfallWhy It HappensFix
Global BottleneckRouting all users to one IDShard by user, room, or document ID.
Memory LeaksNot deleting closed WebSockets from SetsUse the close listener to prune your session Set.
Inconsistent StateForgetting await on storage operationsAlways await state.storage.put() before returning.
Unexpected MigrationsChanging class names without configUpdate [[migrations]] in wrangler.toml carefully.
High LatencyDO instance is far from the userCloudflare moves DOs automatically; usually just wait.

Real-World Examples

1. Collaborative Document Editing

Multiple users connect to a specific DO (mapped to a document ID) to synchronize text changes via WebSockets.

2. Multiplayer Game Server

A DO manages the “Game State” (scores, player positions) and broadcasts updates to all players 20 times per second.

3. Shopping Cart (Consistency)

Using a DO per user session to ensure that “Add to Cart” and “Checkout” are perfectly synchronized.

4. Global Rate Limiter

A single DO that tracks API consumption across 300+ data centers for an enterprise customer.

5. Notification Hub

Users connect via WebSocket to their personal DO; when an event happens, a Worker pings the DO, which sends the alert.

6. Smart IoT Gateway

Managing state for millions of IoT devices; each device has its own DO instance to track current status.

7. Voting Systems

Ensuring that “Live Polls” don’t over-count or under-count by serializing all votes through one instance.

8. Transaction Log Flusher

A DO collects small logs and uses an Alarm to flush them in batches to R2 every 5 minutes to save on Class A operations.

9. Distributed Locking

A DO acts as a “Mutex” or “Semaphore” to ensure only one process can perform a specific task across the entire network.

10. Presence Indicator

A DO tracks which users are currently “Online” in a chat room and broadcasts the list changes to everyone.


Visual

Durable Object Topology

┌───────────────────────────────────────────────────────────┐
│ CLOUDFLARE GLOBAL NETWORK                                 │
│                                                           │
│  [ User A - New York ]    [ User B - Tokyo ]              │
│          │                        │                       │
│          ▼                        ▼                       │
│  [ Worker NY Data Center ] [ Worker TYO Data Center ]     │
│          │                        │                       │
│          └───────────┬────────────┘                       │
│                      ▼                                    │
│       ┌───────────────────────────────┐                   │
│       │ DURABLE OBJECT INSTANCE       │                   │
│       │ (Single Location Worldwide)   │                   │
│       │                               │                   │
│       │ ┌──────────┐  ┌─────────────┐ │                   │
│       │ │ In-Memory│  │ Persistent  │ │                   │
│       │ │ State    │  │ Storage     │ │                   │
│       │ └──────────┘  └─────────────┘ │                   │
│       └───────────────────────────────┘                   │
└───────────────────────────────────────────────────────────┘

WebSocket Broadcast Flow

┌───────────────────────────────────────────────────────────┐
│ DURABLE OBJECT MESSAGING                                  │
│                                                           │
│   Client 1 <───(WS)───┐           ┌───(WS)───> Client 3   │
│                       ▼           ▼                       │
│                   ┌───────────────────┐                   │
│   Client 2 <───WS─┤  DURABLE OBJECT   ├─WS───> Client 4   │
│                   │  - Tracks Set()   │                   │
│                   │  - Loops & Sends  │                   │
│                   └───────────────────┘                   │
└───────────────────────────────────────────────────────────┘

Alarm Lifecycle

┌───────────────────────────────────────────────────────────┐
│ DO ALARM SYSTEM                                           │
│                                                           │
│ 1. Request arrives ──► .fetch() executes                  │
│ 2. .fetch() calls  ──► storage.setAlarm(T + 60s)          │
│ 3. Worker Shuts down (Instance hibernates)                │
│ 4. 60 Seconds Pass                                        │
│ 5. Cloudflare wakes up instance ──► .alarm() executes     │
│ 6. Instance hibernates again                              │
└───────────────────────────────────────────────────────────┘

Summary

ItemValue
ConsistencyStrong (Read-after-write)
Instance CountOne per ID globally
Storage Limit10GB per instance
IdentityidFromName or newUniqueId
Real-timeBuilt-in WebSocket support
BackgroundAlarm API for scheduled tasks
ConcurrencyRequests are serialized (One at a time)

Key takeaways:

  • Durable Objects provide global coordination. Unlike standard Workers, they ensure that all requests for a specific ID are handled by the same piece of code in the same place.
  • Strong consistency is the baseline. The state.storage API allows you to build reliable transactional logic that isn’t possible with the eventually consistent KV store.
  • WebSockets find their home here. Durable Objects are the ideal server-side component for WebSockets, allowing for broadcasts and real-time state synchronization between users.
  • Alarms enable background persistence. The ability for an object to wake itself up ensures that data cleanup or synchronization happens even without user activity.
  • Sharding is the path to scale. While a single DO instance handles requests sequentially, you can create millions of independent DOs to scale your application globally.

Remember: Use Durable Objects when you need “Consistency” and “Coordination.” For high-volume reads and global distribution without synchronization, stick to KV or D1. But for the “real-time” and “stateful” parts of your app, Durable Objects are the indispensable architectural component.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!