Scaling Real-Time Apps with Cloudflare Durable Objects
For years, the serverless paradigm and WebSockets have existed in a state of mutual friction. Serverless functions are, by definition, ephemeral and stateless. WebSockets are, by definition, persistent and stateful. To bridge this gap, engineers have traditionally reached for external state providers—most commonly a managed Redis instance acting as a Pub/Sub broker.
While this architecture works, it introduces significant overhead: connection pooling issues, additional latency, and the 'Redis Tax' (both in terms of cost and operational complexity). Cloudflare Durable Objects (DO) change this equation by providing a stateful actor model directly on the edge. This article explores how to leverage Durable Objects to build high-performance, collaborative applications without the need for a separate database or message broker for real-time synchronization.
The Fundamental Conflict: Stateless Functions vs. Stateful Connections
In a traditional AWS Lambda or Google Cloud Function environment, every request is an isolated event. When a client opens a WebSocket connection, that connection must be terminated somewhere. Since a serverless function cannot run indefinitely, providers usually offer a 'gateway' service (like AWS API Gateway) to maintain the connection and trigger functions on message events.
However, the challenge arises when you need to synchronize state across multiple users. If User A sends a message in a collaborative document, User B needs to receive it instantly. In a stateless environment, the function handling User A's message has no awareness of User B's connection. To solve this, you push the message to Redis, and a separate process (or another triggered function) pushes it back out to User B.
This 'Stateless-to-Stateful' bridge is a workaround, not a solution. It adds a network hop to every single message and forces you to manage a global state store that must be scaled independently of your compute.
Enter Cloudflare Durable Objects
Cloudflare Durable Objects provide a unique primitive: a class-based 'Actor' that is guaranteed to be unique across the entire Cloudflare network. If you create a Durable Object with the ID 'room-123', every single request from anywhere in the world for 'room-123' will be routed to the exact same instance of that object.
This instance runs in a single-threaded event loop and has access to its own private, persistent storage. For WebSockets, this is a game-changer. The Durable Object is the server. It holds the WebSocket connections in memory, manages the shared state, and broadcasts updates to connected peers—all within a single execution context at the edge.
Architecture: The Actor Model at the Edge
When building a collaborative application (like a shared whiteboard or a real-time editor) with Durable Objects, the architecture shifts from a centralized database model to a distributed actor model.
- The Worker (Entry Point): Acts as a router. It receives the initial HTTP request, determines which Durable Object ID is needed (e.g., based on a URL slug), and passes the request to that DO.
- The Durable Object: Manages the lifecycle of the WebSocket connections. It performs the 'Upgrade' from HTTP to WebSocket and stores the connection references in an internal list.
- State Management: The DO uses in-memory variables for 'hot' state (like current cursor positions) and the
storageAPI for 'cold' state (like the document content) that must survive a restart.
Implementation: Building a Collaborative Hub
Let's look at how to implement a basic state-synchronized hub. We will use TypeScript to define a ChatRoom Durable Object that handles multiple connections and broadcasts messages.
1. The Durable Object Class
export class ChatRoom { state: DurableObjectState; sessions: WebSocket[] = []; constructor(state: DurableObjectState) { this.state = state; } async fetch(request: Request) { const pair = new WebSocketPair(); const [client, server] = Object.values(pair); await this.handleSession(server); return new Response(null, { status: 101, webSocket: client }); } async handleSession(ws: WebSocket) { ws.accept(); this.sessions.push(ws); ws.addEventListener("message", async (msg) => { try { // Broadcast the message to all other connected clients this.broadcast(msg.data); // Optionally persist state await this.state.storage.put("lastMessage", msg.data); } catch (err) { ws.close(1011, "Registration failed"); } }); ws.addEventListener("close", () => { this.sessions = this.sessions.filter(s => s !== ws); }); } broadcast(message: string | ArrayBuffer) { this.sessions.forEach(ws => { try { ws.send(message); } catch (e) { // Handle broken connections } }); } }
2. The Worker Router
export default { async fetch(request: Request, env: Env) { const url = new URL(request.url); const roomId = url.searchParams.get("room") || "default"; // Get the DO namespace and create a unique ID const id = env.CHAT_ROOM.idFromName(roomId); const roomObject = env.CHAT_ROOM.get(id); // Forward the request to the DO return roomObject.fetch(request); } };
Solving the Cost Problem: WebSocket Hibernation
In the early days of Durable Objects, you paid for the duration the object was in memory. For WebSockets, this was expensive because an object had to stay 'awake' as long as a client was connected, even if no messages were being sent.
Cloudflare solved this with the WebSocket Hibernation API. This allows a Durable Object to serialize its state and shut down while keeping the WebSocket connections open at the infrastructure level. When a message arrives from a client, Cloudflare 'wakes up' the DO, injects the state, and allows it to handle the event. This reduces the billable duration significantly, making serverless WebSockets commercially viable for large-scale applications.
To use hibernation, you use state.acceptWebSocket(ws) instead of ws.accept(). You then handle events via a webSocketMessage method on the class rather than an event listener on the socket itself.
Data Integrity and Transactional Storage
One of the most powerful features of Durable Objects is the storage API. Unlike an external Redis instance where you might worry about race conditions between multiple serverless instances, a Durable Object is a single-threaded execution context.
When you use this.state.storage.put() or get(), you are guaranteed that no other code is modifying that object's state at the same time. Furthermore, DO storage provides transactional guarantees. You can use this.state.blockConcurrencyWhile(async () => { ... }) to ensure that a sequence of operations (like reading a value, incrementing it, and saving it) happens atomically.
This makes DOs ideal for building collaborative tools like Figma or Notion, where the 'Operational Transformation' (OT) or 'Conflict-free Replicated Data Types' (CRDT) logic requires a strict order of operations.
Performance: The Edge Advantage
In a traditional setup, a user in Tokyo connecting to a WebSocket server in Virginia (US-East-1) suffers from high speed-of-light latency. With Cloudflare, the Worker runs at the PoP (Point of Presence) nearest to the user.
Durable Objects can be configured with Location Hints. While a DO is a single instance, you can tell Cloudflare to instantiate it in a specific region (like jurisdiction: 'eu') or let it automatically migrate to the region where the most traffic is originating. This minimizes the round-trip time (RTT) for the majority of your users, resulting in 'local-feeling' real-time interactions.
When to Use Durable Objects vs. Redis
While Durable Objects are revolutionary, they aren't a silver bullet for every use case. Here is a senior-level breakdown of the trade-offs:
Use Durable Objects when:
- State is Partitioned: Your application naturally divides into 'rooms', 'documents', or 'projects'.
- Low Latency is Critical: You are building a game, a collaborative editor, or a live auction where every millisecond counts.
- You want to simplify the stack: You prefer a single codebase and a single provider over managing a VPC, IAM roles, and Redis clusters.
- Strict Consistency is required: You need atomic transactions for state updates.
Use Managed Redis when:
- Global State is Monolithic: You need to query across all active connections or aggregate data that isn't easily partitioned.
- Massive Broadcasts: If you need to send a single message to 1,000,000+ concurrent users (like a major sporting event update), a specialized Pub/Sub engine like Redis or Ably is better suited for the fan-out load.
- Existing Ecosystem: Your backend is already heavily invested in a specific cloud provider's ecosystem (e.g., AWS AppSync).
Operational Considerations and Limits
As a senior engineer, you must be aware of the constraints. Durable Objects have limits on memory (currently 128MB per object) and storage (standard Key-Value limits). If your collaborative state grows beyond these limits, you'll need to implement a strategy to offload data to an R2 bucket or a D1 database.
Additionally, while the single-threaded nature simplifies concurrency, it means a single 'hot' Durable Object can become a bottleneck if it's handling thousands of messages per second. In such cases, you should implement a 'sharding' pattern, where you split a single logical room into multiple sub-objects that communicate with each other.
Conclusion
Cloudflare Durable Objects represent a fundamental shift in how we approach stateful serverless. By moving the state to the edge and providing a guaranteed unique actor for every connection group, we can eliminate the 'Redis Tax' and build collaborative applications that are faster, cheaper, and easier to maintain.
Actionable Next Steps:
- Audit your current real-time stack: Identify the latency overhead introduced by your message broker.
- Prototype a 'Room' Actor: Use the
wranglerCLI to deploy a basic Durable Object and test the connection persistence. - Implement Hibernation: If your app has long-lived but 'quiet' connections, migrate to the Hibernation API to optimize costs.
- Evaluate CRDTs: For complex collaboration, combine Durable Objects with a CRDT library like Yjs to handle state merging at the edge.