blog.dopana

Back

Building a global, low-latency Real-Time Chat Application for millions of users has traditionally been a tricky System Design problem. On standard serverless platforms like AWS Lambda, long-lived stateful WebSocket connections are challenging because functions are inherently short-lived and stateless.

Using the Cloudflare Edge Platform, we can elegantly solve this using Cloudflare Workers, Durable Objects, Cloudflare KV, and D1 Database.

1. The Core Challenge: WebSockets on Serverless#

Traditional serverless operates on short request-response cycles. Chat applications require:

  • Stateful WebSocket Connections: Maintaining active client-server channels.
  • Global Message Routing: Delivering messages across geographically dispersed edge nodes.
  • Low-Latency Persistence: Saving and fetching history without bottlenecking performance.

2. System Architecture#

The design relies on four primary building blocks:

  1. Cloudflare Workers: Acts as the global API Gateway for WebSocket handshakes and routing.
  2. Durable Objects (DO): Edge-native Singleton Actors managing WebSocket connections and broadcasting within individual chat rooms.
  3. Cloudflare D1: Distributed SQLite storage for chat history and relational data.
  4. Cloudflare KV: High-speed key-value cache for user sessions and feature flags.

3. Core Implementation#

3.1. Durable Object: Room State Coordinator#

Each room instance maintains WebSocket state and broadcasts messages effortlessly.

[!NOTE] Durable Objects execute in a single-threaded actor model, eliminating race conditions when managing room state.

3.2. Worker Gateway Routing#

Workers route incoming requests directly to the corresponding Durable Object instance.

4. Key Takeaways & Trade-offs#

[!TIP] Advantages:

  • Zero Cold Starts: Fast execution via V8 Isolates at edge POPs.
  • Global Scalability: Instant connection termination near users.

[!WARNING] Limits:

  • Single DO instances scale up to thousands of connections per room; mega-rooms require a hierarchical DO broadcast tree architecture.

5. References#